From e8ad92f8aa34b598286a9e2380573802c66c3bec Mon Sep 17 00:00:00 2001 From: annatisch Date: Mon, 21 Mar 2016 14:51:24 -0700 Subject: [PATCH 01/99] Removed raw from Azure LRO --- .../Python/msrest/msrest/serialization.py | 4 ++-- .../msrestazure/azure_active_directory.py | 2 +- .../msrestazure/msrestazure/azure_operation.py | 15 ++------------- 3 files changed, 5 insertions(+), 16 deletions(-) diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index 256f6379fb2b4..2fe97beaf7728 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -590,7 +590,7 @@ def __call__(self, target_obj, response_data): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :raises: DeserializationError if deserialization fails. - :returns: Deserialized object. + :return: Deserialized object. """ data = self._unpack_content(response_data) response, class_name = self._classify_target(target_obj, data) @@ -708,7 +708,7 @@ def deserialize_data(self, data, data_type): :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. :raises: DeserializationError if deserialization fails. - :returns: Deserialized object. + :return: Deserialized object. """ if data is None: return data diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py b/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py index 74618d5a44131..80cbbb7fb5e23 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py @@ -416,7 +416,7 @@ def get_auth_url(self, msa=False, **additional_args): :param additional_args: Set and additional kwargs for requrired AAD configuration: msdn.microsoft.com/en-us/library/azure/dn645542.aspx :rtype: Tuple - :returns: The URL for authentication (str), and state code that will + :return: The URL for authentication (str), and state code that will be verified in the response (str). """ if msa: diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py index 9f0c1729a56d4..085082b6ce028 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py @@ -31,7 +31,6 @@ except ImportError: from urllib.parse import urlparse -from msrest.pipeline import ClientRawResponse from msrest.exceptions import DeserializationError from msrestazure.azure_exceptions import CloudError @@ -130,12 +129,7 @@ def _deserialize(self, response): :raises: OperationFinished if deserialised resource has status succeeded. """ - resource = self.get_outputs(response) - if isinstance(resource, ClientRawResponse): - self.resource = resource.output - self.raw = resource - else: - self.resource = resource + self.resource = self.get_outputs(response) try: if failed(self.resource.provisioning_state): @@ -312,7 +306,6 @@ def __init__(self, response, outputs): self.get_outputs = outputs self.async_url = None self.location_url = None - self.raw = None def _check_status(self, response): """Check response status code is valid for a Put or Patch @@ -400,7 +393,6 @@ def __init__(self, response, outputs): self.get_outputs = outputs self.async_url = None self.location_url = None - self.raw = None def _check_status(self, response): """Check response status code is valid for a Put or Patch @@ -626,10 +618,7 @@ def result(self, timeout=None): :raises CloudError: Server problem with the query. """ self.wait(timeout) - if self._operation.raw: - return self._operation.raw - else: - return self._operation.resource + return self._operation.resource def wait(self, timeout=None): """Wait on the long running operation for a specified length From 619ce59a5b5b958dfe4033e372da99c7d945ea5e Mon Sep 17 00:00:00 2001 From: annatisch Date: Mon, 21 Mar 2016 14:52:13 -0700 Subject: [PATCH 02/99] Changed raw LROs in Python generator --- .../Templates/AzureLongRunningMethodTemplate.cshtml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml b/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml index edb91f8ea7a02..b98c7dbaadcc0 100644 --- a/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml +++ b/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml @@ -31,9 +31,9 @@ @: @ParameterWrapComment(string.Empty, ":param callback: When specified, will be called with each chunk of data that is streamed. The callback should take two arguments, the bytes of the current chunk of data and the response object. If the data is uploading, response will be None.") @: @ParameterWrapComment(string.Empty, ":type callback: Callable[Bytes, response=None]") } - @ParameterWrapComment(string.Empty, ":param operation_config: :ref:`Operation configuration overrides`.") @ParameterWrapComment(string.Empty, ":rtype: :class:`AzureOperationPoller`") - @ParameterWrapComment(string.Empty, ":return: A poller object which can return " + Model.GetDocumentationType(Model.ReturnType.Body) + " or :class:`ClientRawResponse` if raw=true") + @ParameterWrapComment(string.Empty, ":rtype: :class:`ClientRawResponse` if raw=true") + @ParameterWrapComment(string.Empty, ":return: A poller object which returns " + Model.GetDocumentationType(Model.ReturnType.Body)) """ @Model.BuildInputMappings() @if (Model.InputParameterTransformation.Any()) @@ -140,6 +140,10 @@ else { @:@Model.ReturnEmptyResponse } +@EmptyLine + if raw: + response = long_running_send() + return get_long_running_output(response) @EmptyLine long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', From 7f3bb55c69a4edf468713ccec97c06ba6fe62550 Mon Sep 17 00:00:00 2001 From: annatisch Date: Mon, 21 Mar 2016 14:52:38 -0700 Subject: [PATCH 03/99] Updated tests and regenerated --- .../AcceptanceTests/lro_tests.py | 12 +- .../lr_os_custom_header_operations.py | 52 +- .../operations/lr_os_operations.py | 484 ++++++++++-------- .../operations/lro_retrys_operations.py | 90 ++-- .../operations/lrosa_ds_operations.py | 318 +++++++----- .../operations/storage_accounts_operations.py | 12 +- 6 files changed, 557 insertions(+), 411 deletions(-) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py b/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py index ba72f0477c7b3..7e52e686bda1a 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py @@ -102,16 +102,16 @@ def test_lro_happy_paths(self): # Testing raw process = self.client.lr_os.put201_creating_succeeded200(product, raw=True) - self.assertEqual("Succeeded", process.result().output.provisioning_state) + self.assertEqual("Creating", process.output.provisioning_state) - self.assertRaisesWithMessage("Long running operation failed", - self.client.lr_os.put201_creating_failed200(product, raw=True).result) + process = self.client.lr_os.put201_creating_failed200(product, raw=True) + self.assertEqual("Created", process.output.provisioning_state) process = self.client.lr_os.put200_updating_succeeded204(product, raw=True) - self.assertEqual("Succeeded", process.result().output.provisioning_state) + self.assertEqual("Updating", process.output.provisioning_state) - self.assertRaisesWithMessage("Long running operation failed", - self.client.lr_os.put200_acceptedcanceled200(product, raw=True).result) + process = self.client.lr_os.put200_acceptedcanceled200(product, raw=True) + self.assertEqual("Accepted", process.output.provisioning_state) process = self.client.lr_os.put_no_header_in_retry(product) self.assertEqual("Succeeded", process.result().provisioning_state) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py index 79e601f333e0c..de9c85024466f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py @@ -49,14 +49,12 @@ def put_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/customheader/putasync/retry/succeeded' @@ -119,6 +117,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -141,14 +143,12 @@ def put201_creating_succeeded200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/customheader/put/201/creating/succeeded/200' @@ -206,6 +206,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -228,13 +232,11 @@ def post202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/customheader/post/202/retry/200' @@ -287,6 +289,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -309,13 +315,11 @@ def post_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/customheader/postasync/retry/succeeded' @@ -369,6 +373,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py index f5c417d272ed2..8c2983fab9789 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py @@ -46,14 +46,12 @@ def put200_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/200/succeeded' @@ -109,6 +107,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -129,14 +131,12 @@ def put200_succeeded_no_state( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/200/succeeded/nostate' @@ -192,6 +192,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -212,14 +216,12 @@ def put202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/202/retry/200' @@ -275,6 +277,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -296,14 +302,12 @@ def put201_creating_succeeded200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/201/creating/succeeded/200' @@ -361,6 +365,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -382,14 +390,12 @@ def put200_updating_succeeded204( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/200/updating/succeeded/200' @@ -445,6 +451,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -466,14 +476,12 @@ def put201_creating_failed200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/201/created/failed/200' @@ -531,6 +539,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -552,14 +564,12 @@ def put200_acceptedcanceled200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/200/accepted/canceled/200' @@ -615,6 +625,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -635,14 +649,12 @@ def put_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/put/noheader/202/200' @@ -703,6 +715,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -724,14 +740,12 @@ def put_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/putasync/retry/succeeded' @@ -794,6 +808,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -815,14 +833,12 @@ def put_async_no_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/putasync/noretry/succeeded' @@ -884,6 +900,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -905,14 +925,12 @@ def put_async_retry_failed( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/putasync/retry/failed' @@ -975,6 +993,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -996,14 +1018,12 @@ def put_async_no_retrycanceled( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/putasync/noretry/canceled' @@ -1065,6 +1085,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1085,14 +1109,12 @@ def put_async_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/putasync/noheader/201/200' @@ -1153,6 +1175,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1170,14 +1196,12 @@ def put_non_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Sku - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Sku + ` """ # Construct URL url = '/lro/putnonresource/202/200' @@ -1233,6 +1257,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1250,14 +1278,12 @@ def put_async_non_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Sku - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Sku + ` """ # Construct URL url = '/lro/putnonresourceasync/202/200' @@ -1313,6 +1339,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1331,14 +1361,12 @@ def put_sub_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`SubProduct - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`SubProduct + ` """ # Construct URL url = '/lro/putsubresource/202/200' @@ -1394,6 +1422,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1412,14 +1444,12 @@ def put_async_sub_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`SubProduct - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`SubProduct + ` """ # Construct URL url = '/lro/putsubresourceasync/202/200' @@ -1475,6 +1505,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1493,14 +1527,12 @@ def delete_provisioning202_accepted200_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/delete/provisioning/202/accepted/200/succeeded' @@ -1561,6 +1593,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1579,14 +1615,12 @@ def delete_provisioning202_deleting_failed200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/delete/provisioning/202/deleting/200/failed' @@ -1647,6 +1681,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1665,14 +1703,12 @@ def delete_provisioning202_deletingcanceled200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/delete/provisioning/202/deleting/200/canceled' @@ -1733,6 +1769,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1748,13 +1788,11 @@ def delete204_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/delete/204/succeeded' @@ -1796,6 +1834,10 @@ def get_long_running_output(response): client_raw_response = ClientRawResponse(None, response) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1813,14 +1855,12 @@ def delete202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/delete/202/retry/200' @@ -1875,6 +1915,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1892,14 +1936,12 @@ def delete202_no_retry204( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/delete/202/noretry/204' @@ -1954,6 +1996,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1971,13 +2017,11 @@ def delete_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/delete/noheader' @@ -2022,6 +2066,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2039,13 +2087,11 @@ def delete_async_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/noheader/202/204' @@ -2090,6 +2136,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2107,13 +2157,11 @@ def delete_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/retry/succeeded' @@ -2160,6 +2208,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2177,13 +2229,11 @@ def delete_async_no_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/noretry/succeeded' @@ -2230,6 +2280,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2247,13 +2301,11 @@ def delete_async_retry_failed( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/retry/failed' @@ -2300,6 +2352,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2317,13 +2373,11 @@ def delete_async_retrycanceled( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/retry/canceled' @@ -2370,6 +2424,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2387,14 +2445,12 @@ def post200_with_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Sku - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Sku + ` """ # Construct URL url = '/lro/post/payload/200' @@ -2445,6 +2501,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2465,13 +2525,11 @@ def post202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/post/202/retry/200' @@ -2524,6 +2582,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2544,14 +2606,12 @@ def post202_no_retry204( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/post/202/noretry/204' @@ -2613,6 +2673,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2634,14 +2698,12 @@ def post_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/postasync/retry/succeeded' @@ -2704,6 +2766,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2725,14 +2791,12 @@ def post_async_no_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/postasync/noretry/succeeded' @@ -2795,6 +2859,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2816,13 +2884,11 @@ def post_async_retry_failed( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/postasync/retry/failed' @@ -2876,6 +2942,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2897,13 +2967,11 @@ def post_async_retrycanceled( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/postasync/retry/canceled' @@ -2957,6 +3025,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py index c6512164959df..159d7f5086b7d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py @@ -48,14 +48,12 @@ def put201_creating_succeeded200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/retryerror/put/201/creating/succeeded/200' @@ -113,6 +111,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -134,14 +136,12 @@ def put_async_relative_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/retryerror/putasync/retry/succeeded' @@ -204,6 +204,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -222,14 +226,12 @@ def delete_provisioning202_accepted200_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/retryerror/delete/provisioning/202/accepted/200/succeeded' @@ -290,6 +292,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -307,13 +313,11 @@ def delete202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/delete/202/retry/200' @@ -359,6 +363,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -376,13 +384,11 @@ def delete_async_relative_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/deleteasync/retry/succeeded' @@ -429,6 +435,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -449,13 +459,11 @@ def post202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/post/202/retry/200' @@ -508,6 +516,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -529,13 +541,11 @@ def post_async_relative_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/postasync/retry/succeeded' @@ -589,6 +599,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py index b02cf952e3e91..ccedc78c08c25 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py @@ -45,14 +45,12 @@ def put_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/nonretryerror/put/400' @@ -110,6 +108,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -129,14 +131,12 @@ def put_non_retry201_creating400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/nonretryerror/put/201/creating/400' @@ -194,6 +194,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -214,14 +218,12 @@ def put_async_relative_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/nonretryerror/putasync/retry/400' @@ -284,6 +286,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -299,13 +305,11 @@ def delete_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/delete/400' @@ -351,6 +355,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -367,13 +375,11 @@ def delete202_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/delete/202/retry/400' @@ -419,6 +425,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -436,13 +446,11 @@ def delete_async_relative_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/deleteasync/retry/400' @@ -489,6 +497,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -507,13 +519,11 @@ def post_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/post/400' @@ -566,6 +576,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -584,13 +598,11 @@ def post202_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/post/202/retry/400' @@ -643,6 +655,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -663,13 +679,11 @@ def post_async_relative_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/postasync/retry/400' @@ -723,6 +737,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -742,14 +760,12 @@ def put_error201_no_provisioning_state_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/error/put/201/noprovisioningstatepayload' @@ -807,6 +823,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -828,14 +848,12 @@ def put_async_relative_retry_no_status( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/error/putasync/retry/nostatus' @@ -898,6 +916,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -919,14 +941,12 @@ def put_async_relative_retry_no_status_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/error/putasync/retry/nostatuspayload' @@ -989,6 +1009,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1005,13 +1029,11 @@ def delete204_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/delete/204/nolocation' @@ -1053,6 +1075,10 @@ def get_long_running_output(response): client_raw_response = ClientRawResponse(None, response) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1070,13 +1096,11 @@ def delete_async_relative_retry_no_status( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/deleteasync/retry/nostatus' @@ -1123,6 +1147,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1142,13 +1170,11 @@ def post202_no_location( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/post/202/nolocation' @@ -1201,6 +1227,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1222,13 +1252,11 @@ def post_async_relative_retry_no_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/postasync/retry/nopayload' @@ -1282,6 +1310,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1301,14 +1333,12 @@ def put200_invalid_json( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/error/put/200/invalidjson' @@ -1364,6 +1394,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1384,14 +1418,12 @@ def put_async_relative_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/error/putasync/retry/invalidheader' @@ -1454,6 +1486,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1475,14 +1511,12 @@ def put_async_relative_retry_invalid_json_polling( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`Product + ` """ # Construct URL url = '/lro/error/putasync/retry/invalidjsonpolling' @@ -1545,6 +1579,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1562,13 +1600,11 @@ def delete202_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/delete/202/retry/invalidheader' @@ -1614,6 +1650,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1631,13 +1671,11 @@ def delete_async_relative_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/deleteasync/retry/invalidheader' @@ -1684,6 +1722,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1701,13 +1743,11 @@ def delete_async_relative_retry_invalid_json_polling( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/deleteasync/retry/invalidjsonpolling' @@ -1754,6 +1794,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1773,13 +1817,11 @@ def post202_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/post/202/retry/invalidheader' @@ -1832,6 +1874,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1852,13 +1898,11 @@ def post_async_relative_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/postasync/retry/invalidheader' @@ -1912,6 +1956,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1933,13 +1981,11 @@ def post_async_relative_retry_invalid_json_polling( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns None """ # Construct URL url = '/lro/error/postasync/retry/invalidjsonpolling' @@ -1993,6 +2039,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py index 424d097b470fe..9805fe8057bb7 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py @@ -124,14 +124,12 @@ def create( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`StorageAccount + :rtype: :class:`ClientRawResponse` + if raw=true + :return: A poller object which returns :class:`StorageAccount ` - or :class:`ClientRawResponse` if - raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' @@ -191,6 +189,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) From d67b08fd00da11bfb137859f565f7f53c12fc5c0 Mon Sep 17 00:00:00 2001 From: tbombach Date: Mon, 21 Mar 2016 15:07:27 -0700 Subject: [PATCH 04/99] Adding primary type for base64url format --- AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs | 3 ++- AutoRest/Modelers/Swagger/Model/SwaggerObject.cs | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs b/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs index 25465a14c18e6..200dcfe018dfc 100644 --- a/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs +++ b/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs @@ -24,6 +24,7 @@ public enum KnownPrimaryType TimeSpan, Boolean, Credentials, - Uuid + Uuid, + Base64Url } } diff --git a/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs b/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs index 29b7e35a11275..2ca86ef10d3e1 100644 --- a/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs +++ b/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs @@ -116,6 +116,10 @@ public PrimaryType ToType() { return new PrimaryType(KnownPrimaryType.Uuid); } + if (string.Equals("base64url", Format, StringComparison.OrdinalIgnoreCase)) + { + return new PrimaryType(KnownPrimaryType.Base64Url); + } return new PrimaryType(KnownPrimaryType.String); case DataType.Number: if (string.Equals("decimal", Format, StringComparison.OrdinalIgnoreCase)) From 48d268a83693dffa649c7dfd4cc8c9956608f252 Mon Sep 17 00:00:00 2001 From: tbombach Date: Mon, 21 Mar 2016 17:27:26 -0700 Subject: [PATCH 05/99] Updating C# Client runtime to handle the base64url format and add the associated Json serializer for properties of that format --- .../CSharp/CSharp/CSharpCodeNamer.cs | 9 +- .../CSharp/CSharp/ClientModelExtensions.cs | 4 + .../TemplateModels/MethodTemplateModel.cs | 8 ++ .../CSharp/Templates/ModelTemplate.cshtml | 8 ++ .../Serialization/Base64UrlJsonConverter.cs | 94 +++++++++++++++++++ 5 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/Base64UrlJsonConverter.cs diff --git a/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs b/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs index bd368f3f4262e..d9562cf4ca63c 100644 --- a/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs +++ b/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs @@ -237,7 +237,11 @@ protected virtual IType NormalizePrimaryType(PrimaryType primaryType) return null; } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "byte[]"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "bool"; } @@ -396,7 +400,8 @@ public override string EscapeDefaultValue(string defaultValue, IType type) primaryType.Type == KnownPrimaryType.DateTime || primaryType.Type == KnownPrimaryType.DateTimeRfc1123 || primaryType.Type == KnownPrimaryType.TimeSpan || - primaryType.Type == KnownPrimaryType.ByteArray) + primaryType.Type == KnownPrimaryType.ByteArray || + primaryType.Type == KnownPrimaryType.Base64Url) { return "SafeJsonConvert.DeserializeObject<" + primaryType.Name.TrimEnd('?') + diff --git a/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs index 6e98dcce5997e..ded2055e683be 100644 --- a/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs @@ -221,6 +221,10 @@ public static string ToString(this IType type, string clientReference, string re { serializationSettings = "new DateTimeRfc1123JsonConverter()"; } + else if (primaryType.Type == KnownPrimaryType.Base64Url) + { + serializationSettings = "new Base64UrlJsonConverter()"; + } } return string.Format(CultureInfo.InvariantCulture, diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs index f286b20fd7b84..b9824eb7ff383 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs @@ -342,6 +342,14 @@ public string GetSerializationSettingsReference(IType serializationType) { return "new DateTimeRfc1123JsonConverter()"; } + else if (serializationType.IsPrimaryType(KnownPrimaryType.Base64Url) || + (sequenceType != null && sequenceType.ElementType is PrimaryType + && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Base64Url) || + (dictionaryType != null && dictionaryType.ValueType is PrimaryType + && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Base64Url)) + { + return "new Base64UrlJsonConverter()"; + } return ClientReference + ".SerializationSettings"; } diff --git a/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml b/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml index 7807c491ce63e..2bcf9676f0951 100644 --- a/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml @@ -119,6 +119,10 @@ namespace @(Settings.Namespace).Models { @:[JsonConverter(typeof(DateTimeRfc1123JsonConverter))] } + if (property.Type.IsPrimaryType(KnownPrimaryType.Base64Url)) + { + @:[JsonConverter(typeof(Base64UrlJsonConverter))] + } @:[JsonProperty(PropertyName = "@property.SerializedName")] @:public @property.Type.Name @property.Name { get; @(property.IsReadOnly ? "private " : "")set; } @EmptyLine @@ -137,6 +141,10 @@ namespace @(Settings.Namespace).Models { @:[JsonConverter(typeof(DateTimeRfc1123JsonConverter))] } + if (property.Type.IsPrimaryType(KnownPrimaryType.Base64Url)) + { + @:[JsonConverter(typeof(Base64UrlJsonConverter))] + } @:[JsonProperty(PropertyName = "@property.SerializedName")] @:public static @property.Type.Name @property.Name { get; private set; } @EmptyLine diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/Base64UrlJsonConverter.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/Base64UrlJsonConverter.cs new file mode 100644 index 0000000000000..3120ec92c4841 --- /dev/null +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/Base64UrlJsonConverter.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Microsoft.Rest.Serialization +{ + public class Base64UrlJsonConverter : JsonConverter + { + /// + /// Converts a byte array to a Base64Url encoded string + /// + /// The byte array to convert + /// The Base64Url encoded form of the input + private static string ToBase64UrlString(byte[] input) + { + if (input == null) + throw new ArgumentNullException("input"); + + return Convert.ToBase64String(input).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + /// + /// Converts a Base64Url encoded string to a byte array + /// + /// The Base64Url encoded string + /// The byte array represented by the enconded string + private static byte[] FromBase64UrlString(string input) + { + if (string.IsNullOrEmpty(input)) + throw new ArgumentNullException("input"); + + return Convert.FromBase64String(Pad(input.Replace('-', '+').Replace('_', '/'))); + } + + /// + /// Adds padding to the input + /// + /// the input string + /// the padded string + private static string Pad(string input) + { + var count = 3 - ((input.Length + 3) % 4); + + if (count == 0) + { + return input; + } + + return input + new string('=', count); + } + + public override bool CanConvert(Type objectType) + { + if (objectType == typeof(byte[])) + return true; + + return false; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (objectType != typeof(byte[])) + { + return serializer.Deserialize(reader, objectType); + } + else + { + var value = serializer.Deserialize(reader); + + if (!string.IsNullOrEmpty(value)) + { + return FromBase64UrlString(value); + } + } + + return null; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value.GetType() != typeof(byte[])) + { + JToken.FromObject(value).WriteTo(writer); + } + else + { + JToken.FromObject(ToBase64UrlString((byte[])value)).WriteTo(writer); + } + } + } +} \ No newline at end of file From 35220361e5ca5940fbd952840c160028b9a83171 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 21 Mar 2016 18:18:33 -0700 Subject: [PATCH 06/99] Add download streaming support --- .../AzureMethodGroupRetrofitTemplate.cshtml | 4 ++++ .../AzureServiceClientRetrofitTemplate.cshtml | 4 ++++ .../fixtures/bodyfile/FilesOperationsImpl.java | 4 ++++ .../bodyformdata/FormdataOperationsImpl.java | 3 +++ .../test/java/fixtures/bodyfile/FilesTests.java | 15 +++++++++------ .../Java/TemplateModels/MethodTemplateModel.cs | 4 ++++ .../Templates/MethodGroupRetrofitTemplate.cshtml | 4 ++++ .../ServiceClientRetrofitTemplate.cshtml | 4 ++++ ClientRuntimes/Java/client-runtime/build.gradle | 1 + .../microsoft/rest/ServiceResponseBuilder.java | 1 - 10 files changed, 37 insertions(+), 7 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml index e80f2a2fc7dd3..0ff560088979c 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml @@ -31,6 +31,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml index 8d643f9c62fb5..ce2a71a4e1727 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml @@ -31,6 +31,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java index 79dc46b022b25..06511befcedf1 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java @@ -23,6 +23,7 @@ import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Headers; +import retrofit2.http.Streaming; import retrofit2.Response; import retrofit2.Retrofit; @@ -54,14 +55,17 @@ public FilesOperationsImpl(Retrofit retrofit, AutoRestSwaggerBATFileService clie interface FilesService { @Headers("Content-Type: application/json; charset=utf-8") @GET("files/stream/nonempty") + @Streaming Call getFile(); @Headers("Content-Type: application/json; charset=utf-8") @GET("files/stream/verylarge") + @Streaming Call getFileLarge(); @Headers("Content-Type: application/json; charset=utf-8") @GET("files/stream/empty") + @Streaming Call getEmptyFile(); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java index 83711cf6fbca2..2a9ac6f0779b5 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java @@ -30,6 +30,7 @@ import retrofit2.http.Part; import retrofit2.http.POST; import retrofit2.http.PUT; +import retrofit2.http.Streaming; import retrofit2.Response; import retrofit2.Retrofit; @@ -61,10 +62,12 @@ public FormdataOperationsImpl(Retrofit retrofit, AutoRestSwaggerBATFormDataServi interface FormdataService { @Multipart @POST("formdata/stream/uploadfile") + @Streaming Call uploadFile(@Part("fileContent") RequestBody fileContent, @Part("fileName") String fileName); @Headers("Content-Type: application/octet-stream") @PUT("formdata/stream/uploadfile") + @Streaming Call uploadFileViaBody(@Body RequestBody fileContent); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java index b25cfb18b3f21..9843874e5b23d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java @@ -1,19 +1,23 @@ package fixtures.bodyfile; -import org.junit.Assert; import org.apache.commons.io.IOUtils; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.Ignore; import java.io.InputStream; +import java.util.concurrent.TimeUnit; + +import okhttp3.OkHttpClient; +import retrofit2.Retrofit; public class FilesTests { private static AutoRestSwaggerBATFileService client; @BeforeClass public static void setup() { - client = new AutoRestSwaggerBATFileServiceImpl("http://localhost.:3000"); + OkHttpClient.Builder builder = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES); + client = new AutoRestSwaggerBATFileServiceImpl("http://localhost.:3000", builder, new Retrofit.Builder()); } @Test @@ -27,11 +31,10 @@ public void getFile() throws Exception { } } - @Ignore("This fails -- needs to be fixed") + @Test public void getLargeFile() throws Exception { - ClassLoader classLoader = getClass().getClassLoader(); try (InputStream result = client.getFilesOperations().getFileLarge().getBody()) { - long streamSize = 3000 * 1024 * 1024; + long streamSize = 3000L * 1024L * 1024L; long skipped = result.skip(streamSize); Assert.assertEquals(streamSize, skipped); } diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index b6855a82cec50..74b247dd488c1 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -799,6 +799,10 @@ public virtual List ImplImports .ForEach(p => imports.AddRange(p.ImportFrom())); // return type imports.AddRange(this.ReturnType.Body.ImportFrom(ServiceClient.Namespace, Namer)); + if (ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) + { + imports.Add("retrofit2.http.Streaming"); + } // response type (can be different from return type) this.Responses.ForEach(r => imports.AddRange(r.Value.Body.ImportFrom(ServiceClient.Namespace, Namer))); // Header type diff --git a/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml index 164af9fa862f6..f53af2be734d2 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml @@ -27,6 +27,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml index bc17e7d092fa1..7c8432c6a7625 100644 --- a/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml @@ -27,6 +27,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/ClientRuntimes/Java/client-runtime/build.gradle b/ClientRuntimes/Java/client-runtime/build.gradle index 47cbaf08c6397..b1bea55897fb1 100644 --- a/ClientRuntimes/Java/client-runtime/build.gradle +++ b/ClientRuntimes/Java/client-runtime/build.gradle @@ -32,6 +32,7 @@ dependencies { compile 'com.fasterxml.jackson.core:jackson-databind:2.7.1' compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.7.1' compile 'org.apache.commons:commons-lang3:3.4' + compile 'commons-io:commons-io:2.4' testCompile 'junit:junit:4.12' testCompile 'junit:junit-dep:4.11' deployerJars "org.apache.maven.wagon:wagon-ftp:2.10" diff --git a/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java b/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java index 2915ae5e44b8d..e94a166cd1765 100644 --- a/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java +++ b/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java @@ -272,7 +272,6 @@ protected Object buildBody(int statusCode, ResponseBody responseBody) throws IOE // Return raw response if InputStream is the target type else if (type == InputStream.class) { InputStream stream = responseBody.byteStream(); - responseBody.close(); return stream; } // Deserialize From 50561ec7d439ebb53e2f731583d8c4831e59c5ee Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 21 Mar 2016 18:20:26 -0700 Subject: [PATCH 07/99] commons-io was for debugging --- ClientRuntimes/Java/client-runtime/build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/ClientRuntimes/Java/client-runtime/build.gradle b/ClientRuntimes/Java/client-runtime/build.gradle index b1bea55897fb1..47cbaf08c6397 100644 --- a/ClientRuntimes/Java/client-runtime/build.gradle +++ b/ClientRuntimes/Java/client-runtime/build.gradle @@ -32,7 +32,6 @@ dependencies { compile 'com.fasterxml.jackson.core:jackson-databind:2.7.1' compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.7.1' compile 'org.apache.commons:commons-lang3:3.4' - compile 'commons-io:commons-io:2.4' testCompile 'junit:junit:4.12' testCompile 'junit:junit-dep:4.11' deployerJars "org.apache.maven.wagon:wagon-ftp:2.10" From ba3ca3df48c70f09b356bd41372ff6cf3fc89d5c Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 21 Mar 2016 18:23:06 -0700 Subject: [PATCH 08/99] Remove entry from coverage reporter --- .../src/test/java/fixtures/report/CoverageReporter.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java index 4c6d1f4099264..f394131cc8b52 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java @@ -29,8 +29,6 @@ public static void main(String[] args) throws Exception { report.put("HttpRedirect301Put", 1); report.put("HttpRedirect302Patch", 1); - report.put("FileStreamVeryLarge", 1); - int total = report.size(); int hit = 0; List missing = new ArrayList<>(); From 1aeb717a11c12138a2c02426ccc51807b0961c82 Mon Sep 17 00:00:00 2001 From: annatisch Date: Tue, 22 Mar 2016 10:47:56 -0700 Subject: [PATCH 09/99] Reformatted docstring --- .../lr_os_custom_header_operations.py | 12 +- .../operations/lr_os_operations.py | 124 +++++++++--------- .../operations/lro_retrys_operations.py | 20 +-- .../operations/lrosa_ds_operations.py | 68 +++++----- .../operations/storage_accounts_operations.py | 4 +- .../AzureLongRunningMethodTemplate.cshtml | 3 +- 6 files changed, 115 insertions(+), 116 deletions(-) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py index de9c85024466f..96ade6d8e3ad8 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py @@ -51,10 +51,10 @@ def put_async_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/customheader/putasync/retry/succeeded' @@ -145,10 +145,10 @@ def put201_creating_succeeded200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/customheader/put/201/creating/succeeded/200' @@ -234,9 +234,9 @@ def post202_retry200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/customheader/post/202/retry/200' @@ -317,9 +317,9 @@ def post_async_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/customheader/postasync/retry/succeeded' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py index 8c2983fab9789..4a078a8a86f8f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py @@ -48,10 +48,10 @@ def put200_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/200/succeeded' @@ -133,10 +133,10 @@ def put200_succeeded_no_state( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/200/succeeded/nostate' @@ -218,10 +218,10 @@ def put202_retry200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/202/retry/200' @@ -304,10 +304,10 @@ def put201_creating_succeeded200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/201/creating/succeeded/200' @@ -392,10 +392,10 @@ def put200_updating_succeeded204( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/200/updating/succeeded/200' @@ -478,10 +478,10 @@ def put201_creating_failed200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/201/created/failed/200' @@ -566,10 +566,10 @@ def put200_acceptedcanceled200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/200/accepted/canceled/200' @@ -651,10 +651,10 @@ def put_no_header_in_retry( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/put/noheader/202/200' @@ -742,10 +742,10 @@ def put_async_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/putasync/retry/succeeded' @@ -835,10 +835,10 @@ def put_async_no_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/putasync/noretry/succeeded' @@ -927,10 +927,10 @@ def put_async_retry_failed( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/putasync/retry/failed' @@ -1020,10 +1020,10 @@ def put_async_no_retrycanceled( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/putasync/noretry/canceled' @@ -1111,10 +1111,10 @@ def put_async_no_header_in_retry( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/putasync/noheader/201/200' @@ -1198,10 +1198,10 @@ def put_non_resource( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Sku + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Sku - ` """ # Construct URL url = '/lro/putnonresource/202/200' @@ -1280,10 +1280,10 @@ def put_async_non_resource( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Sku + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Sku - ` """ # Construct URL url = '/lro/putnonresourceasync/202/200' @@ -1363,10 +1363,10 @@ def put_sub_resource( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`SubProduct + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`SubProduct - ` """ # Construct URL url = '/lro/putsubresource/202/200' @@ -1446,10 +1446,10 @@ def put_async_sub_resource( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`SubProduct + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`SubProduct - ` """ # Construct URL url = '/lro/putsubresourceasync/202/200' @@ -1529,10 +1529,10 @@ def delete_provisioning202_accepted200_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/delete/provisioning/202/accepted/200/succeeded' @@ -1617,10 +1617,10 @@ def delete_provisioning202_deleting_failed200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/delete/provisioning/202/deleting/200/failed' @@ -1705,10 +1705,10 @@ def delete_provisioning202_deletingcanceled200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/delete/provisioning/202/deleting/200/canceled' @@ -1790,9 +1790,9 @@ def delete204_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/delete/204/succeeded' @@ -1857,10 +1857,10 @@ def delete202_retry200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/delete/202/retry/200' @@ -1938,10 +1938,10 @@ def delete202_no_retry204( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/delete/202/noretry/204' @@ -2019,9 +2019,9 @@ def delete_no_header_in_retry( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/delete/noheader' @@ -2089,9 +2089,9 @@ def delete_async_no_header_in_retry( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/noheader/202/204' @@ -2159,9 +2159,9 @@ def delete_async_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/retry/succeeded' @@ -2231,9 +2231,9 @@ def delete_async_no_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/noretry/succeeded' @@ -2303,9 +2303,9 @@ def delete_async_retry_failed( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/retry/failed' @@ -2375,9 +2375,9 @@ def delete_async_retrycanceled( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/deleteasync/retry/canceled' @@ -2447,10 +2447,10 @@ def post200_with_payload( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Sku + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Sku - ` """ # Construct URL url = '/lro/post/payload/200' @@ -2527,9 +2527,9 @@ def post202_retry200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/post/202/retry/200' @@ -2608,10 +2608,10 @@ def post202_no_retry204( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/post/202/noretry/204' @@ -2700,10 +2700,10 @@ def post_async_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/postasync/retry/succeeded' @@ -2793,10 +2793,10 @@ def post_async_no_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/postasync/noretry/succeeded' @@ -2886,9 +2886,9 @@ def post_async_retry_failed( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/postasync/retry/failed' @@ -2969,9 +2969,9 @@ def post_async_retrycanceled( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/postasync/retry/canceled' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py index 159d7f5086b7d..786c3c3bf6d7d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py @@ -50,10 +50,10 @@ def put201_creating_succeeded200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/retryerror/put/201/creating/succeeded/200' @@ -138,10 +138,10 @@ def put_async_relative_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/retryerror/putasync/retry/succeeded' @@ -228,10 +228,10 @@ def delete_provisioning202_accepted200_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/retryerror/delete/provisioning/202/accepted/200/succeeded' @@ -315,9 +315,9 @@ def delete202_retry200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/delete/202/retry/200' @@ -386,9 +386,9 @@ def delete_async_relative_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/deleteasync/retry/succeeded' @@ -461,9 +461,9 @@ def post202_retry200( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/post/202/retry/200' @@ -543,9 +543,9 @@ def post_async_relative_retry_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/retryerror/postasync/retry/succeeded' 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 ccedc78c08c25..f4bb777cedec5 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py @@ -47,10 +47,10 @@ def put_non_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/nonretryerror/put/400' @@ -133,10 +133,10 @@ def put_non_retry201_creating400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/nonretryerror/put/201/creating/400' @@ -220,10 +220,10 @@ def put_async_relative_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/nonretryerror/putasync/retry/400' @@ -307,9 +307,9 @@ def delete_non_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/delete/400' @@ -377,9 +377,9 @@ def delete202_non_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/delete/202/retry/400' @@ -448,9 +448,9 @@ def delete_async_relative_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/deleteasync/retry/400' @@ -521,9 +521,9 @@ def post_non_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/post/400' @@ -600,9 +600,9 @@ def post202_non_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/post/202/retry/400' @@ -681,9 +681,9 @@ def post_async_relative_retry400( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/nonretryerror/postasync/retry/400' @@ -762,10 +762,10 @@ def put_error201_no_provisioning_state_payload( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/error/put/201/noprovisioningstatepayload' @@ -850,10 +850,10 @@ def put_async_relative_retry_no_status( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/error/putasync/retry/nostatus' @@ -943,10 +943,10 @@ def put_async_relative_retry_no_status_payload( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/error/putasync/retry/nostatuspayload' @@ -1031,9 +1031,9 @@ def delete204_succeeded( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/delete/204/nolocation' @@ -1098,9 +1098,9 @@ def delete_async_relative_retry_no_status( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/deleteasync/retry/nostatus' @@ -1172,9 +1172,9 @@ def post202_no_location( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/post/202/nolocation' @@ -1254,9 +1254,9 @@ def post_async_relative_retry_no_payload( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/postasync/retry/nopayload' @@ -1335,10 +1335,10 @@ def put200_invalid_json( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/error/put/200/invalidjson' @@ -1420,10 +1420,10 @@ def put_async_relative_retry_invalid_header( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/error/putasync/retry/invalidheader' @@ -1513,10 +1513,10 @@ def put_async_relative_retry_invalid_json_polling( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`Product + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`Product - ` """ # Construct URL url = '/lro/error/putasync/retry/invalidjsonpolling' @@ -1602,9 +1602,9 @@ def delete202_retry_invalid_header( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/delete/202/retry/invalidheader' @@ -1673,9 +1673,9 @@ def delete_async_relative_retry_invalid_header( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/deleteasync/retry/invalidheader' @@ -1745,9 +1745,9 @@ def delete_async_relative_retry_invalid_json_polling( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/deleteasync/retry/invalidjsonpolling' @@ -1819,9 +1819,9 @@ def post202_retry_invalid_header( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/post/202/retry/invalidheader' @@ -1900,9 +1900,9 @@ def post_async_relative_retry_invalid_header( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/postasync/retry/invalidheader' @@ -1983,9 +1983,9 @@ def post_async_relative_retry_invalid_json_polling( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns None :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns None """ # Construct URL url = '/lro/error/postasync/retry/invalidjsonpolling' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py index 9805fe8057bb7..2250ab10c1468 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py @@ -126,10 +126,10 @@ def create( deserialized response :rtype: :class:`AzureOperationPoller` + instance that returns :class:`StorageAccount + ` :rtype: :class:`ClientRawResponse` if raw=true - :return: A poller object which returns :class:`StorageAccount - ` """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' diff --git a/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml b/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml index b98c7dbaadcc0..78533cd451225 100644 --- a/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml +++ b/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml @@ -31,9 +31,8 @@ @: @ParameterWrapComment(string.Empty, ":param callback: When specified, will be called with each chunk of data that is streamed. The callback should take two arguments, the bytes of the current chunk of data and the response object. If the data is uploading, response will be None.") @: @ParameterWrapComment(string.Empty, ":type callback: Callable[Bytes, response=None]") } - @ParameterWrapComment(string.Empty, ":rtype: :class:`AzureOperationPoller`") + @ParameterWrapComment(string.Empty, ":rtype: :class:`AzureOperationPoller` instance that returns " + Model.GetDocumentationType(Model.ReturnType.Body)) @ParameterWrapComment(string.Empty, ":rtype: :class:`ClientRawResponse` if raw=true") - @ParameterWrapComment(string.Empty, ":return: A poller object which returns " + Model.GetDocumentationType(Model.ReturnType.Body)) """ @Model.BuildInputMappings() @if (Model.InputParameterTransformation.Any()) From a26728c21ff7555f2ad2c00e766a1ad6ef380244 Mon Sep 17 00:00:00 2001 From: annatisch Date: Tue, 22 Mar 2016 13:35:06 -0700 Subject: [PATCH 10/99] Added accept header --- ClientRuntimes/Python/msrest/msrest/service_client.py | 1 + 1 file changed, 1 insertion(+) diff --git a/ClientRuntimes/Python/msrest/msrest/service_client.py b/ClientRuntimes/Python/msrest/msrest/service_client.py index 14ea3f3cff2b8..523c6648582f1 100644 --- a/ClientRuntimes/Python/msrest/msrest/service_client.py +++ b/ClientRuntimes/Python/msrest/msrest/service_client.py @@ -117,6 +117,7 @@ def _configure_session(self, session, **config): session.headers.update(self._headers) session.headers['User-Agent'] = self.config.user_agent + session.headers['Accept'] = 'application/json' session.max_redirects = config.get( 'max_redirects', self.config.redirect_policy()) session.proxies = config.get( From 74c3a758d5ceb4de83481d7b82ca018422272f9f Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Tue, 22 Mar 2016 13:58:37 -0700 Subject: [PATCH 11/99] Update travis node version to 4 --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ab73003e51f94..700c37840023e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,7 @@ install: - export LD_LIBRARY_PATH=$HOME/.local/lib/:$LD_LIBRARY_PATH # Install npm - curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | sh && source ~/.dnx/dnvm/dnvm.sh && dnvm upgrade + - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install 4 - npm install -g npm@'>=1.4.3' - npm install # Install ruby dependencies @@ -49,4 +50,4 @@ after_script: - cat TestResults/*.log notifications: slack: - secure: d0PFVLcyqcMxNtmZ8JaEpIBzXbUbZCgKs8QtBB5qEIXDnxflSR3AhczlILNhTBKtMEBlwVzsz65yP09XcmvB6xpAfJbHqSRzk2frKa5viPcAD8Wr/NYamt9/UiTCsnql8MqzjVy0tLdMscXKRmsUey4YF570zl0b7gAbq7XTqxM= \ No newline at end of file + secure: d0PFVLcyqcMxNtmZ8JaEpIBzXbUbZCgKs8QtBB5qEIXDnxflSR3AhczlILNhTBKtMEBlwVzsz65yP09XcmvB6xpAfJbHqSRzk2frKa5viPcAD8Wr/NYamt9/UiTCsnql8MqzjVy0tLdMscXKRmsUey4YF570zl0b7gAbq7XTqxM= From e1082839305dae61972a37b7d823e9dc0a2bbbb5 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Tue, 22 Mar 2016 14:08:54 -0700 Subject: [PATCH 12/99] Fix DateTimeRfc in parameter mappings --- .../Java/Java/TemplateModels/MethodTemplateModel.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 4c613a265e16f..8526cbbf41aac 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -270,7 +270,7 @@ public virtual string BuildInputMappings() if (conditionalAssignment) { builder.AppendLine("{0} {1} = null;", - JavaCodeNamer.WrapPrimitiveType(transformation.OutputParameter.Type).Name, + JavaCodeNamer.WrapPrimitiveType(transformation.OutputParameter.Type.UserHandledType()).Name, transformation.OutputParameter.Name); builder.AppendLine("if ({0}) {{", nullCheck).Indent(); } @@ -279,7 +279,7 @@ public virtual string BuildInputMappings() transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0}{1} = new {2}();", - !conditionalAssignment ? transformation.OutputParameter.Type.Name + " " : "", + !conditionalAssignment ? transformation.OutputParameter.Type.UserHandledType().Name + " " : "", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } @@ -287,8 +287,8 @@ public virtual string BuildInputMappings() foreach (var mapping in transformation.ParameterMappings) { builder.AppendLine("{0}{1}{2};", - !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? - transformation.OutputParameter.Type.Name + " " : "", + !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? + transformation.OutputParameter.Type.UserHandledType().Name + " " : "", transformation.OutputParameter.Name, GetMapping(mapping)); } From f92ffb3e462f28ec9191e873618b12e57c2559d1 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Tue, 22 Mar 2016 14:38:16 -0700 Subject: [PATCH 13/99] Fix stream type in input mappings --- .../TemplateModels/AzureMethodTemplateModel.cs | 10 ++++++---- .../Generators/Java/Java/ClientModelExtensions.cs | 13 +++++++++++++ AutoRest/Generators/Java/Java/JavaCodeNamer.cs | 2 +- .../Java/Java/TemplateModels/MethodTemplateModel.cs | 10 +++++----- .../Java/Java/Templates/MethodTemplate.cshtml | 8 ++++---- .../main/java/com/microsoft/azure/PagedList.java | 8 +++++--- 6 files changed, 34 insertions(+), 17 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 4ea67d6a62153..32ec961c47898 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -114,11 +114,11 @@ public override string MethodParameterDeclaration { if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) { - declarations.Add("final File " + parameter.Name); + declarations.Add("final byte[] " + parameter.Name); } else { - declarations.Add("final " + parameter.Type.UserHandledType().ToString() + " " + parameter.Name); + declarations.Add("final " + parameter.Type.ParameterType().Name + " " + parameter.Name); } } @@ -138,7 +138,7 @@ public override string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add("final " + parameter.Type.UserHandledType().ToString() + " " + parameter.Name); + declarations.Add("final " + parameter.Type.ParameterType().Name + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -309,7 +309,9 @@ public override string ResponseGeneration builder.AppendLine("PagedList<{0}> result = new PagedList<{0}>(response.getBody()) {{", ((SequenceType)ReturnType.Body).ElementType.Name) .Indent().AppendLine("@Override") - .AppendLine("public Page<{0}> nextPage(String nextPageLink) throws CloudException, IOException {{", ((SequenceType)ReturnType.Body).ElementType.Name) + .AppendLine("public Page<{0}> nextPage(String nextPageLink) throws {1}, IOException {{", + ((SequenceType)ReturnType.Body).ElementType.Name, + OperationExceptionTypeString) .Indent(); TransformPagingGroupedParameter(builder, nextMethod); builder.AppendLine("return {0}({1}).getBody();", invocation, nextMethod.MethodParameterInvocation) diff --git a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs index e7ef1baa88fda..e89a151cf9897 100644 --- a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs +++ b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs @@ -124,6 +124,19 @@ public static void AddRange(this HashSet hashSet, IEnumerable range) } } + public static IType ParameterType(this IType type) + { + PrimaryType primaryType = type as PrimaryType; + if (primaryType.IsPrimaryType(KnownPrimaryType.Stream)) + { + return JavaCodeNamer.NormalizePrimaryType(new PrimaryType(KnownPrimaryType.ByteArray)); + } + else + { + return type.UserHandledType(); + } + } + public static IType UserHandledType(this IType type) { PrimaryType primaryType = type as PrimaryType; diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index af18dbb59f6b1..00dc938d2965c 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -330,7 +330,7 @@ private IType NormalizeCompositeType(CompositeType compositeType) return compositeType; } - private static PrimaryType NormalizePrimaryType(PrimaryType primaryType) + public static PrimaryType NormalizePrimaryType(PrimaryType primaryType) { if (primaryType == null) { diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 8526cbbf41aac..ac7107f51f93c 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -147,7 +147,7 @@ public virtual string MethodParameterDeclaration } else { - declarations.Add(parameter.Type.UserHandledType().ToString() + " " + parameter.Name); + declarations.Add(parameter.Type.ParameterType().Name + " " + parameter.Name); } } @@ -163,7 +163,7 @@ public virtual string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add(parameter.Type.UserHandledType().ToString() + " " + parameter.Name); + declarations.Add(parameter.Type.ParameterType().Name + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -270,7 +270,7 @@ public virtual string BuildInputMappings() if (conditionalAssignment) { builder.AppendLine("{0} {1} = null;", - JavaCodeNamer.WrapPrimitiveType(transformation.OutputParameter.Type.UserHandledType()).Name, + JavaCodeNamer.WrapPrimitiveType(transformation.OutputParameter.Type.ParameterType()).Name, transformation.OutputParameter.Name); builder.AppendLine("if ({0}) {{", nullCheck).Indent(); } @@ -279,7 +279,7 @@ public virtual string BuildInputMappings() transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0}{1} = new {2}();", - !conditionalAssignment ? transformation.OutputParameter.Type.UserHandledType().Name + " " : "", + !conditionalAssignment ? transformation.OutputParameter.Type.ParameterType().Name + " " : "", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } @@ -288,7 +288,7 @@ public virtual string BuildInputMappings() { builder.AppendLine("{0}{1}{2};", !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? - transformation.OutputParameter.Type.UserHandledType().Name + " " : "", + transformation.OutputParameter.Type.ParameterType().Name + " " : "", transformation.OutputParameter.Name, GetMapping(mapping)); } diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index c90a59e9b7f9c..e3a722c848842 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -49,11 +49,11 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi { if (!parameter.IsRequired) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = null; +@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = null; } if (parameter.IsConstant) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = @(parameter.DefaultValue); } } @@ -109,11 +109,11 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW { if (!parameter.IsRequired) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = null; +@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = null; } if (parameter.IsConstant) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = @(parameter.DefaultValue); } } @Model.BuildInputMappings() diff --git a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java index 8c42851d4e851..e13926390c42f 100644 --- a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java +++ b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java @@ -7,6 +7,8 @@ package com.microsoft.azure; +import com.microsoft.rest.AutoRestException; + import java.io.IOException; import java.util.Collection; import java.util.Iterator; @@ -44,10 +46,10 @@ public PagedList(Page page) { * * @param nextPageLink the link to get the next page of items. * @return the {@link Page} object storing a page of items and a link to the next page. - * @throws CloudException thrown if an error is raised from Azure. + * @throws AutoRestException thrown if an error is raised from Azure. * @throws IOException thrown if there's any failure in deserialization. */ - public abstract Page nextPage(String nextPageLink) throws CloudException, IOException; + public abstract Page nextPage(String nextPageLink) throws AutoRestException, IOException; /** * If there are more pages available. @@ -67,7 +69,7 @@ public void loadNextPage() { Page nextPage = nextPage(this.nextPageLink); this.nextPageLink = nextPage.getNextPageLink(); this.items.addAll(nextPage.getItems()); - } catch (CloudException e) { + } catch (AutoRestException e) { throw new WebServiceException(e.toString(), e); } catch (IOException e) { throw new DataBindingException(e.getMessage(), e); From daf75d923615b342614640afb202301e08fd04b4 Mon Sep 17 00:00:00 2001 From: tbombach Date: Tue, 22 Mar 2016 17:36:11 -0700 Subject: [PATCH 14/99] Adding tests for C# for base64url --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 5 + .../BodyString/IStringModel.cs | 32 ++ .../AcceptanceTests/BodyString/StringModel.cs | 349 ++++++++++++++++++ .../BodyString/StringModelExtensions.cs | 85 +++++ .../TemplateModels/MethodTemplateModel.cs | 8 + AutoRest/TestServer/server/app.js | 5 +- AutoRest/TestServer/server/routes/string.js | 15 + AutoRest/TestServer/swagger/body-string.json | 77 ++++ 8 files changed, 575 insertions(+), 1 deletion(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 77b5768b57dac..9e878f96f9805 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -275,6 +275,11 @@ public void StringTests() Assert.Null(client.StringModel.GetNotProvided()); Assert.Equal(Colors.Redcolor, client.EnumModel.GetNotExpandable()); client.EnumModel.PutNotExpandable(Colors.Redcolor); + var base64UrlEncodedString = client.StringModel.GetBase64UrlEncoded(); + var base64EncodedString = client.StringModel.GetBase64Encoded(); + Assert.Equal(Encoding.UTF8.GetString(base64UrlEncodedString), "a string that gets padded with base64url"); + Assert.Equal(Encoding.UTF8.GetString(base64EncodedString), "a string that gets padded with base64url"); + client.StringModel.PutBase64UrlEncoded(base64UrlEncodedString); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs index ead7a87735a93..e76321744770f 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs @@ -136,5 +136,37 @@ public partial interface IStringModel /// The cancellation token. /// Task> GetNotProvidedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get value that is base64 encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get value that is base64url encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put value that is base64url encoded + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutBase64UrlEncodedWithHttpMessagesAsync(byte[] stringBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs index 61557a3917295..a4e2c74c7f3c9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs @@ -1095,5 +1095,354 @@ public StringModel(AutoRestSwaggerBATService client) return _result; } + /// + /// Get value that is base64 encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64Encoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/base64Encoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get value that is base64url encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64UrlEncoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/base64UrlEncoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put value that is base64url encoded + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutBase64UrlEncodedWithHttpMessagesAsync(byte[] stringBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (stringBody == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "stringBody"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("stringBody", stringBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutBase64UrlEncoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/base64UrlEncoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + _requestContent = SafeJsonConvert.SerializeObject(stringBody, new Base64UrlJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs index aaa2faa66b405..515ce39f4ea70 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs @@ -301,5 +301,90 @@ public static string GetNotProvided(this IStringModel operations) } } + /// + /// Get value that is base64 encoded + /// + /// + /// The operations group for this extension method. + /// + public static byte[] GetBase64Encoded(this IStringModel operations) + { + return Task.Factory.StartNew(s => ((IStringModel)s).GetBase64EncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get value that is base64 encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetBase64EncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64EncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + public static byte[] GetBase64UrlEncoded(this IStringModel operations) + { + return Task.Factory.StartNew(s => ((IStringModel)s).GetBase64UrlEncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetBase64UrlEncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64UrlEncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Put value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// + public static void PutBase64UrlEncoded(this IStringModel operations, byte[] stringBody) + { + Task.Factory.StartNew(s => ((IStringModel)s).PutBase64UrlEncodedAsync(stringBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Put value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutBase64UrlEncodedAsync(this IStringModel operations, byte[] stringBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutBase64UrlEncodedWithHttpMessagesAsync(stringBody, null, cancellationToken).ConfigureAwait(false); + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs index b9824eb7ff383..440187b3a32cb 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs @@ -370,6 +370,14 @@ public string GetDeserializationSettingsReference(IType deserializationType) { return "new DateJsonConverter()"; } + if (deserializationType.IsPrimaryType(KnownPrimaryType.Base64Url) || + (sequenceType != null && sequenceType.ElementType is PrimaryType + && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Base64Url) || + (dictionaryType != null && dictionaryType.ValueType is PrimaryType + && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Base64Url)) + { + return "new Base64UrlJsonConverter()"; + } return ClientReference + ".DeserializationSettings"; } diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index 4d8d3d47144d1..5f69e690a193c 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -113,7 +113,7 @@ var coverage = { "getArrayComplexValid": 0, "putArrayComplexValid": 0, "getArrayDictionaryNull": 0, - "getArrayDictionaryEmpty": 0, + "getArrayDictionaryEmpty": 0, "getArrayDictionaryItemNull": 0, "getArrayDictionaryItemEmpty": 0, "getArrayDictionaryValid": 0, @@ -195,6 +195,9 @@ var coverage = { "getStringWithLeadingAndTrailingWhitespace" : 0, "putStringWithLeadingAndTrailingWhitespace" : 0, "getStringNotProvided": 0, + "getStringBase64Encoded": 0, + "getStringBase64UrlEncoded": 0, + "putStringBase64UrlEncoded": 0, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, diff --git a/AutoRest/TestServer/server/routes/string.js b/AutoRest/TestServer/server/routes/string.js index 461f4106b8e80..4717617a383ab 100644 --- a/AutoRest/TestServer/server/routes/string.js +++ b/AutoRest/TestServer/server/routes/string.js @@ -5,6 +5,8 @@ var constants = require('../util/constants'); var utils = require('../util/utils') var string = function(coverage) { + var base64String = "YSBzdHJpbmcgdGhhdCBnZXRzIHBhZGRlZCB3aXRoIGJhc2U2NHVybA=="; + var base64UrlString = "YSBzdHJpbmcgdGhhdCBnZXRzIHBhZGRlZCB3aXRoIGJhc2U2NHVybA"; router.put('/:scenario', function(req, res, next) { if (req.params.scenario === 'null') { if (req.body !== null) { @@ -34,6 +36,13 @@ var string = function(coverage) { coverage['putStringWithLeadingAndTrailingWhitespace']++; res.status(200).end(); } + } else if (req.params.scenario === 'base64UrlEncoding') { + if (req.body !== 'YSBzdHJpbmcgdGhhdCBnZXRzIHBhZGRlZCB3aXRoIGJhc2U2NHVybA') { + utils.send400(res, next, "Did not like base64url req '" + util.inspect(req.body) + "'"); + } else { + coverage['putStringBase64UrlEncoded']++; + res.status(200).end(); + } } else { utils.send400(res, next, 'Request path must contain true or false'); } @@ -43,6 +52,12 @@ var string = function(coverage) { if (req.params.scenario === 'null') { coverage['getStringNull']++; res.status(200).end(); + } else if (req.params.scenario === 'base64Encoding') { + coverage['getStringBase64Encoded']++; + res.status(200).end('"' + base64String + '"'); + } else if (req.params.scenario === 'base64UrlEncoding') { + coverage['getStringBase64UrlEncoded']++; + res.status(200).end('"' + base64UrlString + '"'); } else if (req.params.scenario === 'notProvided') { coverage['getStringNotProvided']++; res.status(200).end(); diff --git a/AutoRest/TestServer/swagger/body-string.json b/AutoRest/TestServer/swagger/body-string.json index 744ca60ec1e14..0e2fd0969635e 100644 --- a/AutoRest/TestServer/swagger/body-string.json +++ b/AutoRest/TestServer/swagger/body-string.json @@ -300,6 +300,83 @@ } } } + }, + "/string/base64Encoding": { + "get": { + "operationId": "string_getBase64Encoded", + "description": "Get value that is base64 encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The base64 encoded string value", + "schema": { + "type": "string", + "format": "base64url" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/string/base64UrlEncoding": { + "get": { + "operationId": "string_getBase64UrlEncoded", + "description": "Get value that is base64url encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The base64url encoded string value", + "schema": { + "type": "string", + "format": "base64url" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "put": { + "operationId": "string_putBase64UrlEncoded", + "description": "Put value that is base64url encoded", + "parameters": [ + { + "name": "stringBody", + "in": "body", + "schema": { + "type": "string", + "format": "base64url" + }, + "required": true + } + ], + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "Empty Response" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } } }, "definitions": { From d6f75394f77f07bf0c67cff8a0aee4ee91c06a4e Mon Sep 17 00:00:00 2001 From: tbombach Date: Tue, 22 Mar 2016 23:49:39 -0700 Subject: [PATCH 15/99] Making the code namers for each language treat base64url encoding as string if they don't handle encoding/decoding --- AutoRest/Generators/Java/Java/JavaCodeNamer.cs | 6 +++++- AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs | 6 +++++- AutoRest/Generators/Python/Python/PythonCodeNamer.cs | 6 +++++- AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs | 6 +++++- 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index 048f9cab5fdce..ea0de8874798c 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -337,7 +337,11 @@ private static PrimaryType NormalizePrimaryType(PrimaryType primaryType) throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "String"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "boolean"; } diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs index 907584895d8fd..3fdcbfb3465b1 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs @@ -341,7 +341,11 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "String"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "Boolean"; } diff --git a/AutoRest/Generators/Python/Python/PythonCodeNamer.cs b/AutoRest/Generators/Python/Python/PythonCodeNamer.cs index 779c4ebd70120..4aebfb6378a11 100644 --- a/AutoRest/Generators/Python/Python/PythonCodeNamer.cs +++ b/AutoRest/Generators/Python/Python/PythonCodeNamer.cs @@ -324,7 +324,11 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "str"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "bool"; } diff --git a/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs b/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs index 489f02d4fea8e..b54d22f077218 100644 --- a/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs +++ b/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs @@ -323,7 +323,11 @@ private IType NormalizePrimaryType(PrimaryType primaryType) throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "String"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "Boolean"; } From 9337878c9a3e79a041ceec5d183e1d73b126cb80 Mon Sep 17 00:00:00 2001 From: tbombach Date: Wed, 23 Mar 2016 01:35:33 -0700 Subject: [PATCH 16/99] Updating unit tests for swagger generation for base64url format --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 4 ++-- .../Expected/Mirror.Primitives/Models/Product.cs | 15 ++++++++++++++- .../Swagger/swagger-mirror-primitives.json | 13 ++++++++++++- .../CSharp.Tests/Utilities/MirrorTestHelpers.cs | 4 +++- .../Swagger.Tests/Swagger/swagger-data-types.json | 8 +++++++- .../Modelers/Swagger.Tests/SwaggerModelerTests.cs | 3 ++- AutoRest/TestServer/server/routes/string.js | 6 +++--- 7 files changed, 43 insertions(+), 10 deletions(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 9e878f96f9805..6cf4d4da107a9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -277,8 +277,8 @@ public void StringTests() client.EnumModel.PutNotExpandable(Colors.Redcolor); var base64UrlEncodedString = client.StringModel.GetBase64UrlEncoded(); var base64EncodedString = client.StringModel.GetBase64Encoded(); - Assert.Equal(Encoding.UTF8.GetString(base64UrlEncodedString), "a string that gets padded with base64url"); - Assert.Equal(Encoding.UTF8.GetString(base64EncodedString), "a string that gets padded with base64url"); + Assert.Equal(Encoding.UTF8.GetString(base64UrlEncodedString), "a string that gets encoded with base64url"); + Assert.Equal(Encoding.UTF8.GetString(base64EncodedString), "a string that gets encoded with base64url"); client.StringModel.PutBase64UrlEncoded(base64UrlEncodedString); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs index 2c3e2bafc98f6..d2ea149e267a9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs @@ -25,7 +25,7 @@ public Product() { } /// /// Initializes a new instance of the Product class. /// - public Product(int? integer = default(int?), int? intProperty = default(int?), long? longProperty = default(long?), double? number = default(double?), double? floatProperty = default(double?), double? doubleProperty = default(double?), byte[] byteProperty = default(byte[]), string stringProperty = default(string), Guid? uuid = default(Guid?), string enumProperty = default(string), bool? boolean = default(bool?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), IList integerArray = default(IList), IList intArray = default(IList), IList longArray = default(IList), IList numberArray = default(IList), IList floatArray = default(IList), IList doubleArray = default(IList), IList byteArray = default(IList), IList booleanArray = default(IList), IList stringArray = default(IList), IList dateArray = default(IList), IList dateTimeArray = default(IList), IList uuidArray = default(IList)) + public Product(int? integer = default(int?), int? intProperty = default(int?), long? longProperty = default(long?), double? number = default(double?), double? floatProperty = default(double?), double? doubleProperty = default(double?), byte[] byteProperty = default(byte[]), string stringProperty = default(string), byte[] base64url = default(byte[]), Guid? uuid = default(Guid?), string enumProperty = default(string), bool? boolean = default(bool?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), IList integerArray = default(IList), IList intArray = default(IList), IList longArray = default(IList), IList numberArray = default(IList), IList floatArray = default(IList), IList doubleArray = default(IList), IList byteArray = default(IList), IList booleanArray = default(IList), IList stringArray = default(IList), IList base64urlArray = default(IList), IList dateArray = default(IList), IList dateTimeArray = default(IList), IList uuidArray = default(IList)) { Integer = integer; IntProperty = intProperty; @@ -35,6 +35,7 @@ public Product() { } DoubleProperty = doubleProperty; ByteProperty = byteProperty; StringProperty = stringProperty; + Base64url = base64url; Uuid = uuid; EnumProperty = enumProperty; Boolean = boolean; @@ -49,6 +50,7 @@ public Product() { } ByteArray = byteArray; BooleanArray = booleanArray; StringArray = stringArray; + Base64urlArray = base64urlArray; DateArray = dateArray; DateTimeArray = dateTimeArray; UuidArray = uuidArray; @@ -94,6 +96,12 @@ public Product() { } [JsonProperty(PropertyName = "string")] public string StringProperty { get; set; } + /// + /// + [JsonConverter(typeof(Base64UrlJsonConverter))] + [JsonProperty(PropertyName = "base64url")] + public byte[] Base64url { get; set; } + /// /// [JsonProperty(PropertyName = "uuid")] @@ -166,6 +174,11 @@ public Product() { } [JsonProperty(PropertyName = "stringArray")] public IList StringArray { get; set; } + /// + /// + [JsonProperty(PropertyName = "base64urlArray")] + public IList Base64urlArray { get; set; } + /// /// [JsonProperty(PropertyName = "dateArray")] diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json b/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json index 3fa190be4cf05..91fa027d2107c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json @@ -185,6 +185,10 @@ "string": { "type": "string" }, + "base64url": { + "type": "string", + "format": "base64url" + }, "uuid": { "type": "string", "format": "uuid" @@ -244,7 +248,7 @@ "format": "double" } }, - "byteArray": { + "byteArray": { "type": "array", "items": { "type": "string", @@ -263,6 +267,13 @@ "type": "string" } }, + "base64urlArray": { + "type": "array", + "items": { + "type": "string", + "format": "base64url" + } + }, "dateArray": { "type": "array", "items": { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs index 0710d373ee783..513368cb1f4cf 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs @@ -34,7 +34,8 @@ public static Product GenerateProduct() DateTime = DateTime.UtcNow, Uuid = new Guid("122F1443-D736-4C16-8207-06B978AA4FF9"), ByteArray = - new List {GenerateBytes(100), GenerateBytes(200), GenerateBytes(300), GenerateBytes(100)} + new List { GenerateBytes(100), GenerateBytes(200), GenerateBytes(300), GenerateBytes(100) }, + Base64url = System.Text.Encoding.UTF8.GetBytes("Now is the time for all good men to come to the aid of their country") }; } @@ -72,6 +73,7 @@ public static void ValidateProduct(Product expected, Product actual) Assert.Equal(expected.StringProperty, actual.StringProperty); Assert.Equal(expected.DateTime, actual.DateTime); Assert.Equal(expected.Uuid, actual.Uuid); + Assert.Equal(expected.Base64url, actual.Base64url); ValidateList(expected.ByteArray, actual.ByteArray, (s, t) => Assert.Equal(s, t)); } diff --git a/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json b/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json index afec02a0266f4..4e7e1da3f3084 100644 --- a/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json +++ b/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json @@ -13,7 +13,7 @@ "produces": [ "application/json" ], "consumes": [ "application/json" ], "paths": { - "/subscriptions/{integer}/{int}/{long}/{number}/{float}/{double}/{string}/{enum}/{byte}/{boolean}/{date}/{dateTime}?invalues='{array}'": { + "/subscriptions/{integer}/{int}/{long}/{number}/{float}/{double}/{string}/{enum}/{byte}/{boolean}/{date}/{dateTime}/{base64url}?invalues='{array}'": { "get": { "operationId": "list", "summary": "Product Types", @@ -93,6 +93,12 @@ "type": "string", "format": "date-time" }, + { + "name": "base64url", + "in": "path", + "type": "string", + "format": "base64url" + }, { "name": "array", "in": "query", diff --git a/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs b/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs index 3e6043847f7a0..0aac57a71e45f 100644 --- a/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs +++ b/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs @@ -347,7 +347,8 @@ public void TestDataTypes() Assert.Equal("Boolean boolean", clientModel.Methods[0].Parameters[10].ToString()); Assert.Equal("Date date", clientModel.Methods[0].Parameters[11].ToString()); Assert.Equal("DateTime dateTime", clientModel.Methods[0].Parameters[12].ToString()); - Assert.Equal("IList array", clientModel.Methods[0].Parameters[13].ToString()); + Assert.Equal("Base64Url base64url", clientModel.Methods[0].Parameters[13].ToString()); + Assert.Equal("IList array", clientModel.Methods[0].Parameters[14].ToString()); var variableEnumInPath = clientModel.Methods.First(m => m.Name == "list" && m.Group == null).Parameters.First(p => p.Name == "color" && p.Location == ParameterLocation.Path).Type as EnumType; diff --git a/AutoRest/TestServer/server/routes/string.js b/AutoRest/TestServer/server/routes/string.js index 4717617a383ab..fb780b4148c10 100644 --- a/AutoRest/TestServer/server/routes/string.js +++ b/AutoRest/TestServer/server/routes/string.js @@ -5,8 +5,8 @@ var constants = require('../util/constants'); var utils = require('../util/utils') var string = function(coverage) { - var base64String = "YSBzdHJpbmcgdGhhdCBnZXRzIHBhZGRlZCB3aXRoIGJhc2U2NHVybA=="; - var base64UrlString = "YSBzdHJpbmcgdGhhdCBnZXRzIHBhZGRlZCB3aXRoIGJhc2U2NHVybA"; + var base64String = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw="; + var base64UrlString = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw"; router.put('/:scenario', function(req, res, next) { if (req.params.scenario === 'null') { if (req.body !== null) { @@ -37,7 +37,7 @@ var string = function(coverage) { res.status(200).end(); } } else if (req.params.scenario === 'base64UrlEncoding') { - if (req.body !== 'YSBzdHJpbmcgdGhhdCBnZXRzIHBhZGRlZCB3aXRoIGJhc2U2NHVybA') { + if (req.body !== 'YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw') { utils.send400(res, next, "Did not like base64url req '" + util.inspect(req.body) + "'"); } else { coverage['putStringBase64UrlEncoded']++; From 6ae67cc582dfaabecabe9af9ad53df6a13d29ce3 Mon Sep 17 00:00:00 2001 From: tbombach Date: Wed, 23 Mar 2016 01:51:20 -0700 Subject: [PATCH 17/99] Adding a test for handling a null value when it is expected to be base64url encoded --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 5 +- .../BodyString/IStringModel.cs | 10 ++ .../AcceptanceTests/BodyString/StringModel.cs | 119 +++++++++++++ .../BodyString/StringModelExtensions.cs | 28 +++ AutoRest/TestServer/server/app.js | 1 + AutoRest/TestServer/server/routes/string.js | 5 +- AutoRest/TestServer/swagger/body-string.json | 160 ++++++++++-------- 7 files changed, 257 insertions(+), 71 deletions(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 6cf4d4da107a9..7946b3e74cfb1 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -278,8 +278,9 @@ public void StringTests() var base64UrlEncodedString = client.StringModel.GetBase64UrlEncoded(); var base64EncodedString = client.StringModel.GetBase64Encoded(); Assert.Equal(Encoding.UTF8.GetString(base64UrlEncodedString), "a string that gets encoded with base64url"); - Assert.Equal(Encoding.UTF8.GetString(base64EncodedString), "a string that gets encoded with base64url"); - client.StringModel.PutBase64UrlEncoded(base64UrlEncodedString); + Assert.Equal(Encoding.UTF8.GetString(base64EncodedString), "a string that gets encoded with base64"); + Assert.Null(client.StringModel.GetNullBase64Encoded()); + client.StringModel.PutBase64UrlEncoded(Encoding.UTF8.GetBytes("a string that gets encoded with base64url")); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs index e76321744770f..4c9302911da2f 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs @@ -168,5 +168,15 @@ public partial interface IStringModel /// The cancellation token. /// Task PutBase64UrlEncodedWithHttpMessagesAsync(byte[] stringBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs index a4e2c74c7f3c9..0370d2fd1d00b 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs @@ -1444,5 +1444,124 @@ public StringModel(AutoRestSwaggerBATService client) return _result; } + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNullBase64Encoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/nullBase64UrlEncoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs index 515ce39f4ea70..c026f184f6b25 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs @@ -386,5 +386,33 @@ public static void PutBase64UrlEncoded(this IStringModel operations, byte[] stri await operations.PutBase64UrlEncodedWithHttpMessagesAsync(stringBody, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// The operations group for this extension method. + /// + public static byte[] GetNullBase64Encoded(this IStringModel operations) + { + return Task.Factory.StartNew(s => ((IStringModel)s).GetNullBase64EncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullBase64EncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullBase64EncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + } } diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index 5f69e690a193c..54c271aff2b77 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -198,6 +198,7 @@ var coverage = { "getStringBase64Encoded": 0, "getStringBase64UrlEncoded": 0, "putStringBase64UrlEncoded": 0, + "getStringNullBase64UrlEncoding": 0, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, diff --git a/AutoRest/TestServer/server/routes/string.js b/AutoRest/TestServer/server/routes/string.js index fb780b4148c10..439ac4e926234 100644 --- a/AutoRest/TestServer/server/routes/string.js +++ b/AutoRest/TestServer/server/routes/string.js @@ -5,7 +5,7 @@ var constants = require('../util/constants'); var utils = require('../util/utils') var string = function(coverage) { - var base64String = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw="; + var base64String = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjQ="; var base64UrlString = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw"; router.put('/:scenario', function(req, res, next) { if (req.params.scenario === 'null') { @@ -58,6 +58,9 @@ var string = function(coverage) { } else if (req.params.scenario === 'base64UrlEncoding') { coverage['getStringBase64UrlEncoded']++; res.status(200).end('"' + base64UrlString + '"'); + } else if (req.params.scenario === 'nullBase64UrlEncoding') { + coverage['getStringNullBase64UrlEncoding']++; + res.status(200).end(); } else if (req.params.scenario === 'notProvided') { coverage['getStringNotProvided']++; res.status(200).end(); diff --git a/AutoRest/TestServer/swagger/body-string.json b/AutoRest/TestServer/swagger/body-string.json index 0e2fd0969635e..2d6ce61e39243 100644 --- a/AutoRest/TestServer/swagger/body-string.json +++ b/AutoRest/TestServer/swagger/body-string.json @@ -302,81 +302,105 @@ } }, "/string/base64Encoding": { - "get": { - "operationId": "string_getBase64Encoded", - "description": "Get value that is base64 encoded", - "tags": [ - "String Operations" - ], - "responses": { - "200": { - "description": "The base64 encoded string value", - "schema": { - "type": "string", - "format": "base64url" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } + "get": { + "operationId": "string_getBase64Encoded", + "description": "Get value that is base64 encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The base64 encoded string value", + "schema": { + "type": "string", + "format": "base64url" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" } + } } + } }, "/string/base64UrlEncoding": { - "get": { - "operationId": "string_getBase64UrlEncoded", - "description": "Get value that is base64url encoded", - "tags": [ - "String Operations" - ], - "responses": { - "200": { - "description": "The base64url encoded string value", - "schema": { - "type": "string", - "format": "base64url" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } + "get": { + "operationId": "string_getBase64UrlEncoded", + "description": "Get value that is base64url encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The base64url encoded string value", + "schema": { + "type": "string", + "format": "base64url" } - }, - "put": { - "operationId": "string_putBase64UrlEncoded", - "description": "Put value that is base64url encoded", - "parameters": [ - { - "name": "stringBody", - "in": "body", - "schema": { - "type": "string", - "format": "base64url" - }, - "required": true - } - ], - "tags": [ - "String Operations" - ], - "responses": { - "200": { - "description": "Empty Response" - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" } + } } + }, + "put": { + "operationId": "string_putBase64UrlEncoded", + "description": "Put value that is base64url encoded", + "parameters": [ + { + "name": "stringBody", + "in": "body", + "schema": { + "type": "string", + "format": "base64url" + }, + "required": true + } + ], + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "Empty Response" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/string/nullBase64UrlEncoding": { + "get": { + "operationId": "string_getNullBase64Encoded", + "description": "Get null value that is expected to be base64url encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The null value", + "schema": { + "type": "string", + "format": "base64url" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } } }, "definitions": { From baefd44ef9da75081598edfe39a5aaa2dd7c335c Mon Sep 17 00:00:00 2001 From: matthchr Date: Tue, 22 Mar 2016 17:17:36 -0700 Subject: [PATCH 18/99] Fix nodejs server to correctly check optional body - Also fix Python, C#, and Ruby so that they pass the new tests. --- .../AzureBodyDuration/DurationOperations.cs | 9 +- .../ArrayOperations.cs | 18 +- .../AzureCompositeModel.cs | 18 +- .../BasicOperations.cs | 9 +- .../DictionaryOperations.cs | 18 +- .../InheritanceOperations.cs | 9 +- .../PolymorphicrecursiveOperations.cs | 9 +- .../PolymorphismOperations.cs | 18 +- .../PrimitiveOperations.cs | 99 ++++++--- .../ReadonlypropertyOperations.cs | 9 +- .../ParameterGroupingOperations.cs | 9 +- .../AutoRestResourceFlatteningTestService.cs | 27 ++- .../Lro/LRORetrysOperations.cs | 36 ++- .../AcceptanceTests/Lro/LROSADsOperations.cs | 153 ++++++++----- .../Lro/LROsCustomHeaderOperations.cs | 36 ++- .../AcceptanceTests/Lro/LROsOperations.cs | 207 ++++++++++++------ .../AcceptanceTests/BodyArray/Array.cs | 144 ++++++++---- .../AcceptanceTests/BodyBoolean/BoolModel.cs | 18 +- .../AcceptanceTests/BodyByte/ByteModel.cs | 9 +- .../AcceptanceTests/BodyComplex/Array.cs | 18 +- .../BodyComplex/BasicOperations.cs | 9 +- .../AcceptanceTests/BodyComplex/Dictionary.cs | 18 +- .../BodyComplex/Inheritance.cs | 9 +- .../BodyComplex/Polymorphicrecursive.cs | 9 +- .../BodyComplex/Polymorphism.cs | 18 +- .../AcceptanceTests/BodyComplex/Primitive.cs | 99 ++++++--- .../BodyComplex/Readonlyproperty.cs | 9 +- .../Expected/AcceptanceTests/BodyDate/Date.cs | 18 +- .../AcceptanceTests/BodyDateTime/Datetime.cs | 54 +++-- .../BodyDateTimeRfc1123/Datetimerfc1123.cs | 18 +- .../BodyDictionary/Dictionary.cs | 135 ++++++++---- .../AcceptanceTests/BodyDuration/Duration.cs | 9 +- .../AcceptanceTests/BodyInteger/IntModel.cs | 36 ++- .../AcceptanceTests/BodyNumber/Number.cs | 90 +++++--- .../AcceptanceTests/BodyString/EnumModel.cs | 9 +- .../AcceptanceTests/BodyString/StringModel.cs | 36 ++- .../CompositeBoolIntClient/BoolModel.cs | 18 +- .../CompositeBoolIntClient/IntModel.cs | 36 ++- .../AcceptanceTests/Http/HttpClientFailure.cs | 117 ++++++---- .../AcceptanceTests/Http/HttpRedirects.cs | 63 ++++-- .../AcceptanceTests/Http/HttpRetry.cs | 54 +++-- .../AcceptanceTests/Http/HttpServerFailure.cs | 18 +- .../AcceptanceTests/Http/HttpSuccess.cs | 126 +++++++---- .../AutoRestResourceFlatteningTestService.cs | 54 +++-- .../ParameterFlattening/AvailabilitySets.cs | 9 +- .../RequiredOptional/ExplicitModel.cs | 144 ++++++++---- .../RequiredOptional/ImplicitModel.cs | 9 +- .../Validation/AutoRestValidationTest.cs | 18 +- .../SwaggerDateTimeOffsetClient.cs | 36 ++- .../PolymorphicAnimalStore.cs | 9 +- .../SwaggerDataTypesClient.cs | 36 ++- .../RecursiveTypesAPI.cs | 9 +- .../SequenceRequestResponseTest.cs | 27 ++- .../Expected/PetstoreV2/SwaggerPetstoreV2.cs | 63 ++++-- .../CSharp/Templates/MethodTemplate.cshtml | 11 +- .../TemplateModels/MethodTemplateModel.cs | 2 +- AutoRest/TestServer/server/routes/reqopt.js | 6 +- AutoRest/TestServer/server/routes/string.js | 2 +- .../Python/msrest/msrest/pipeline.py | 2 +- .../Azure.CSharp/StorageAccountsOperations.cs | 36 ++- Samples/petstore/CSharp/SwaggerPetstore.cs | 72 ++++-- Samples/petstore/Java/SwaggerPetstore.java | 5 +- .../petstore/Java/SwaggerPetstoreImpl.java | 5 +- 63 files changed, 1618 insertions(+), 818 deletions(-) diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs index 0a81d725f40a0..1bb297f05c5be 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs @@ -262,9 +262,12 @@ internal DurationOperations(AutoRestDurationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(durationBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs index 1f102b7d253f8..084e2252f5c2f 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs @@ -267,9 +267,12 @@ internal ArrayOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -552,9 +555,12 @@ internal ArrayOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs index 1b85b132a8e1f..4a1b72d67ed36 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs @@ -598,9 +598,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -781,9 +784,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs index 971958b5cce24..48f31b747d153 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs @@ -273,9 +273,12 @@ internal BasicOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs index 7bff642eb2e8e..00abbb1a9f230 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs @@ -267,9 +267,12 @@ internal DictionaryOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -552,9 +555,12 @@ internal DictionaryOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs index e9259e72611d0..6fc88683f2532 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs @@ -270,9 +270,12 @@ internal InheritanceOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs index 2498f6ef1f370..62c2becc51e81 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs @@ -323,9 +323,12 @@ internal PolymorphicrecursiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs index 58c94cd664148..e731fe36e914a 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs @@ -304,9 +304,12 @@ internal PolymorphismOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -474,9 +477,12 @@ internal PolymorphismOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs index 973c9684fdf7a..6e66f9fa38195 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs @@ -267,9 +267,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -552,9 +555,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -837,9 +843,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1123,9 +1132,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1408,9 +1420,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1693,9 +1708,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1978,9 +1996,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2263,9 +2284,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2549,9 +2573,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2831,9 +2858,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3116,9 +3146,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs index 56feb12b1ce51..70e1a11d28b4b 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs @@ -266,9 +266,12 @@ internal ReadonlypropertyOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs index 9a2bf74564bac..7fe382cfcdee6 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs @@ -161,9 +161,12 @@ internal ParameterGroupingOperations(AutoRestParameterGroupingTestService client // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs index ce1bd46bdd5d8..a922764f2b369 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs @@ -347,9 +347,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceArray != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -628,9 +631,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceDictionary != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -909,9 +915,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceComplexObject != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs index 0717455b58c3c..9ed93a653fb58 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs @@ -145,9 +145,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -349,9 +352,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1083,9 +1089,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1262,9 +1271,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs index bf8e7415095a3..7b0662de0c29e 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs @@ -139,9 +139,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -339,9 +342,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -541,9 +547,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1225,9 +1234,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1398,9 +1410,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1575,9 +1590,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1752,9 +1770,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1954,9 +1975,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2151,9 +2175,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2663,9 +2690,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2840,9 +2870,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3017,9 +3050,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3201,9 +3237,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3398,9 +3437,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -4088,9 +4130,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -4265,9 +4310,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -4442,9 +4490,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs index ef38e4360dffc..a6475eba268d4 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs @@ -147,9 +147,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -348,9 +351,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -550,9 +556,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -731,9 +740,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs index 1ff59d6881ad5..b518b2963bc7e 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs @@ -141,9 +141,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -323,9 +326,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -507,9 +513,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -693,9 +702,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -897,9 +909,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1083,9 +1098,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1287,9 +1305,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1471,9 +1492,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1668,9 +1692,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1865,9 +1892,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2062,9 +2092,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2259,9 +2292,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2456,9 +2492,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2649,9 +2688,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(sku != null) + { + _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2829,9 +2871,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(sku != null) + { + _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3009,9 +3054,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3189,9 +3237,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -5698,9 +5749,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -5873,9 +5927,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6068,9 +6125,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6263,9 +6323,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6458,9 +6521,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6635,9 +6701,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs index 0b9d94dc699a5..dc36500493259 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs @@ -459,9 +459,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -689,9 +692,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1157,9 +1163,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1625,9 +1634,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2093,9 +2105,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2561,9 +2576,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3029,9 +3047,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3501,9 +3522,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3850,9 +3874,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4320,9 +4347,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4790,9 +4820,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5020,9 +5053,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5252,9 +5288,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -6082,9 +6121,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -6790,9 +6832,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -7504,9 +7549,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs index d287e6188c543..d78403311ec8c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs @@ -217,9 +217,12 @@ public BoolModel(AutoRestBoolTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -443,9 +446,12 @@ public BoolModel(AutoRestBoolTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs index 6faca5d0f82c5..6343dc98de5e5 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs @@ -460,9 +460,12 @@ public ByteModel(AutoRestSwaggerBATByteService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(byteBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(byteBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(byteBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs index f24a2d97284af..5009f9e28bcea 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs @@ -222,9 +222,12 @@ public Array(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -453,9 +456,12 @@ public Array(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs index a9dd0b484a555..39cc806a8c839 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs @@ -231,9 +231,12 @@ public BasicOperations(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs index 03d740e5eae86..d707e2106fd98 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs @@ -222,9 +222,12 @@ public Dictionary(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -453,9 +456,12 @@ public Dictionary(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs index d8b687fe82965..8884055cd84c5 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs @@ -225,9 +225,12 @@ public Inheritance(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs index 8a4753fa788be..9e3d47fc4a98a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs @@ -278,9 +278,12 @@ public Polymorphicrecursive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs index 62d9e5af2d7c7..e9f32ec1faccf 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs @@ -259,9 +259,12 @@ public Polymorphism(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -402,9 +405,12 @@ public Polymorphism(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs index caed868d0e270..334e0f205ddcf 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs @@ -222,9 +222,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -453,9 +456,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -684,9 +690,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -916,9 +925,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1147,9 +1159,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1378,9 +1393,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1609,9 +1627,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1840,9 +1861,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2072,9 +2096,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2300,9 +2327,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2531,9 +2561,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs index 15758e93c2836..57471567ee6da 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs @@ -221,9 +221,12 @@ public Readonlyproperty(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs index 509781fe382c5..0a4c07170740d 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs @@ -574,9 +574,12 @@ public Date(AutoRestDateTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(dateBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -800,9 +803,12 @@ public Date(AutoRestDateTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(dateBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs index a46a03a8ae9b4..2248d4263b000 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs @@ -574,9 +574,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -920,9 +923,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1268,9 +1274,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1615,9 +1624,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1841,9 +1853,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2067,9 +2082,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs index 2506c533d5633..068aced56df75 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs @@ -574,9 +574,12 @@ public Datetimerfc1123(AutoRestRFC1123DateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +922,12 @@ public Datetimerfc1123(AutoRestRFC1123DateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs index a370279790948..6ea18f6d785ae 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs @@ -340,9 +340,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1047,9 +1050,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1515,9 +1521,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1983,9 +1992,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2451,9 +2463,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2919,9 +2934,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3387,9 +3405,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3857,9 +3878,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4327,9 +4351,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4798,9 +4825,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5029,9 +5059,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5261,9 +5294,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -6092,9 +6128,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -6802,9 +6841,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -7517,9 +7559,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs index 7893ed1ee8506..42b50edf64d33 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs @@ -217,9 +217,12 @@ public Duration(AutoRestDurationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(durationBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs index 7c65575d05ed7..feb0d3013f373 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs @@ -812,9 +812,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +922,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1026,9 +1032,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1133,9 +1142,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs index dc98d33d86449..4b60b5582025a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs @@ -574,9 +574,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -800,9 +803,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1026,9 +1032,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1252,9 +1261,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1478,9 +1490,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1704,9 +1719,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1930,9 +1948,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2156,9 +2177,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2382,9 +2406,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2608,9 +2635,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs index c1701bfb31ad1..8861a350c04b9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs @@ -220,9 +220,12 @@ public EnumModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs index 61557a3917295..834b762156d3f 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs @@ -218,9 +218,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -449,9 +452,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -683,9 +689,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +928,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs index 9c761510fc304..22ff99e128385 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs @@ -217,9 +217,12 @@ public BoolModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -443,9 +446,12 @@ public BoolModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs index 6932d90778be5..1ed42f86ca54e 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs @@ -812,9 +812,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +922,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1026,9 +1032,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1133,9 +1142,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs index 60a652f2efb7e..3df1107bea40c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs @@ -329,9 +329,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -451,9 +454,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -573,9 +579,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -695,9 +704,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1162,9 +1174,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1284,9 +1299,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1406,9 +1424,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1528,9 +1549,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1650,9 +1674,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2117,9 +2144,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2239,9 +2269,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2361,9 +2394,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2598,9 +2634,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs index 7759c53c1e4d5..01747fbf1dd29 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs @@ -575,9 +575,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -926,9 +929,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1049,9 +1055,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1398,9 +1407,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1519,9 +1531,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1640,9 +1655,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1761,9 +1779,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs index ac964e2f0c42b..6fe19ef0d1e25 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs @@ -200,9 +200,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -308,9 +311,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -517,9 +523,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -625,9 +634,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -733,9 +745,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -841,9 +856,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs index a26c0148f8ec9..425c90bf3f141 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs @@ -329,9 +329,12 @@ public HttpServerFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -451,9 +454,12 @@ public HttpServerFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs index 550bfeb440a1e..9cef952542266 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs @@ -319,9 +319,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -427,9 +430,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -535,9 +541,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -643,9 +652,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -751,9 +763,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -859,9 +874,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -967,9 +985,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1075,9 +1096,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1183,9 +1207,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1291,9 +1318,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1500,9 +1530,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1608,9 +1641,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1716,9 +1752,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1824,9 +1863,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs index 111c67ef2ea6f..36bd84b559bd8 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs @@ -198,9 +198,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceArray != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -425,9 +428,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceDictionary != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -652,9 +658,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceComplexObject != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -883,9 +892,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(simpleBodyProduct != null) + { + _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1037,9 +1049,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(simpleBodyProduct != null) + { + _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1211,9 +1226,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(simpleBodyProduct != null) + { + _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs index a2ff4eb31d0f1..119563378110a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs @@ -132,9 +132,12 @@ public AvailabilitySets(AutoRestParameterFlattening client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(tags1, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(tags1 != null) + { + _requestContent = SafeJsonConvert.SerializeObject(tags1, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs index 6d1908994fb20..f0e42c1bf7fc9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs @@ -99,9 +99,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -220,9 +223,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -331,9 +337,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -456,9 +465,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -805,9 +817,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -926,9 +941,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1044,9 +1062,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1172,9 +1193,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1532,9 +1556,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1657,9 +1684,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1779,9 +1809,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1911,9 +1944,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2023,9 +2059,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2144,9 +2183,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2262,9 +2304,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2390,9 +2435,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs index e07c894c0febb..52a2bd5e9c8a0 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs @@ -446,9 +446,12 @@ public ImplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs index dd33131940bbd..73459ebb73386 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs @@ -461,9 +461,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -679,9 +682,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs index b59cf0b0fe805..3bd502e2cd4ac 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs @@ -208,9 +208,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -346,9 +349,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -484,9 +490,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -622,9 +631,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs index 9dbebd699667a..86bf0ccd5653a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs @@ -202,9 +202,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(animalCreateOrUpdateParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs index 30a57dd8f7f38..bc41c9c9bd812 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs @@ -208,9 +208,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -346,9 +349,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -484,9 +490,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -622,9 +631,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs index 68210edc4dab2..ae58814c3bdb7 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs @@ -227,9 +227,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs index e3e054da32ea1..8548cb8d729d7 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs @@ -211,9 +211,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(pets, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(pets != null) + { + _requestContent = SafeJsonConvert.SerializeObject(pets, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -341,9 +344,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(petStyle != null) + { + _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -471,9 +477,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(petStyle != null) + { + _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs index 9839ee82c0df4..9245c2c40a070 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs @@ -323,9 +323,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -451,9 +454,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1306,9 +1312,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1679,9 +1688,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1785,9 +1797,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1891,9 +1906,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -2379,9 +2397,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml b/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml index b81e369d21565..df038116b29cb 100644 --- a/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml @@ -161,11 +161,12 @@ else } else { - - _requestContent = SafeJsonConvert.SerializeObject(@(Model.RequestBody.Name), @(Model.GetSerializationSettingsReference(Model.RequestBody.Type))); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); - + @:if(@(Model.RequestBody.Name) != null) + @:{ + @:_requestContent = SafeJsonConvert.SerializeObject(@(Model.RequestBody.Name), @(Model.GetSerializationSettingsReference(Model.RequestBody.Type))); + @:_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + @:_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); + @:} } } else if (Model.LogicalParameters.Where(p => p.Location == ParameterLocation.FormData).Any()) diff --git a/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs index 405533fd14139..f66881e9294be 100644 --- a/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs @@ -280,7 +280,7 @@ public virtual string CreateSerializationString(string inputVariable, IType type builder.AppendLine(serializationLogic); // After that - generate JSON object after serializing each component. - return builder.AppendLine("{0} = JSON.generate({1}, quirks_mode: true)", outputVariable, inputVariable).ToString(); + return builder.AppendLine("{0} = {1} != nil ? JSON.generate({1}, quirks_mode: true) : nil", outputVariable, inputVariable).ToString(); } /// diff --git a/AutoRest/TestServer/server/routes/reqopt.js b/AutoRest/TestServer/server/routes/reqopt.js index 39d78407b9f0d..4e476f17e485f 100644 --- a/AutoRest/TestServer/server/routes/reqopt.js +++ b/AutoRest/TestServer/server/routes/reqopt.js @@ -44,7 +44,7 @@ var reqopt = function (coverage) { utils.send400(res, next, 'Please send a null to optional header.'); } } else if (req.params.scenario === 'body') { - if (!req.body || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { + if (req.body === undefined || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { coverage['OptionalImplicitBody']++; res.status(200).end(); } else { @@ -63,14 +63,14 @@ var reqopt = function (coverage) { var covered = "Optional" + utils.toPascalCase(req.params.type) + utils.toPascalCase(req.params.scenario); console.log('scenario: ' + covered + '\n'); if (req.params.scenario === 'parameter') { - if (!req.body || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { + if (req.body === undefined || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { coverage[covered]++; res.status(200).end(); } else { utils.send400(res, next, 'Please send a null to optional ' + req.params.type + ' body.'); } } else if (req.params.scenario === 'property') { - if (!req.body || (req.body && !req.body['value'])) { + if (req.body === undefined || (req.body && !req.body['value'])) { coverage[covered]++; res.status(200).end(); } else { diff --git a/AutoRest/TestServer/server/routes/string.js b/AutoRest/TestServer/server/routes/string.js index 400b9663f6cb7..25a38f4f4b306 100644 --- a/AutoRest/TestServer/server/routes/string.js +++ b/AutoRest/TestServer/server/routes/string.js @@ -7,7 +7,7 @@ var utils = require('../util/utils') var string = function (coverage) { router.put('/:scenario', function (req, res, next) { if (req.params.scenario === 'null') { - if (!req.body || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { + if (req.body === undefined || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { coverage['putStringNull']++; res.status(200).end(); } else { diff --git a/ClientRuntimes/Python/msrest/msrest/pipeline.py b/ClientRuntimes/Python/msrest/msrest/pipeline.py index a4996a20d7e48..a376139a22f1a 100644 --- a/ClientRuntimes/Python/msrest/msrest/pipeline.py +++ b/ClientRuntimes/Python/msrest/msrest/pipeline.py @@ -205,7 +205,7 @@ def add_content(self, data): :param data: Request body data, can be a json serializable object (e.g. dictionary) or a generator (e.g. file data). """ - if data is None and self.method == 'GET': + if data is None: return try: diff --git a/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs b/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs index 315e390de4e46..1b1c5f06a3e5c 100644 --- a/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs +++ b/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs @@ -133,9 +133,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(accountName, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(accountName != null) + { + _requestContent = SafeJsonConvert.SerializeObject(accountName, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -381,9 +384,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(parameters != null) + { + _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -960,9 +966,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(parameters != null) + { + _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1704,9 +1713,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(regenerateKey, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(regenerateKey != null) + { + _requestContent = SafeJsonConvert.SerializeObject(regenerateKey, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/Samples/petstore/CSharp/SwaggerPetstore.cs b/Samples/petstore/CSharp/SwaggerPetstore.cs index 89e8e3e8158f8..7d157b55636fc 100644 --- a/Samples/petstore/CSharp/SwaggerPetstore.cs +++ b/Samples/petstore/CSharp/SwaggerPetstore.cs @@ -194,9 +194,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -294,9 +297,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -394,9 +400,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1415,9 +1424,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1748,9 +1760,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1844,9 +1859,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1940,9 +1958,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2379,9 +2400,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/Samples/petstore/Java/SwaggerPetstore.java b/Samples/petstore/Java/SwaggerPetstore.java index 1b275e1d5217d..c69cde12b66ed 100644 --- a/Samples/petstore/Java/SwaggerPetstore.java +++ b/Samples/petstore/Java/SwaggerPetstore.java @@ -12,7 +12,6 @@ import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceException; import com.microsoft.rest.ServiceResponse; -import java.io.File; import java.io.InputStream; import java.io.IOException; import java.util.Map; @@ -405,7 +404,7 @@ public interface SwaggerPetstore { * @throws IOException exception thrown from serialization/deserialization * @return the {@link ServiceResponse} object if successful. */ - ServiceResponse uploadFile(long petId, String additionalMetadata, File file) throws ServiceException, IOException; + ServiceResponse uploadFile(long petId, String additionalMetadata, byte[] file) throws ServiceException, IOException; /** * uploads an image. @@ -417,7 +416,7 @@ public interface SwaggerPetstore { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall uploadFileAsync(long petId, String additionalMetadata, File file, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall uploadFileAsync(long petId, String additionalMetadata, byte[] file, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Returns pet inventories by status. diff --git a/Samples/petstore/Java/SwaggerPetstoreImpl.java b/Samples/petstore/Java/SwaggerPetstoreImpl.java index 654134d24740b..8965397e43e74 100644 --- a/Samples/petstore/Java/SwaggerPetstoreImpl.java +++ b/Samples/petstore/Java/SwaggerPetstoreImpl.java @@ -17,7 +17,6 @@ import com.microsoft.rest.ServiceResponseBuilder; import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; -import java.io.File; import java.io.InputStream; import java.io.IOException; import java.util.List; @@ -1018,7 +1017,7 @@ public void onResponse(Call call, Response response) * @throws IOException exception thrown from serialization/deserialization * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse uploadFile(long petId, String additionalMetadata, File file) throws ServiceException, IOException { + public ServiceResponse uploadFile(long petId, String additionalMetadata, byte[] file) throws ServiceException, IOException { Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); return uploadFileDelegate(call.execute()); } @@ -1033,7 +1032,7 @@ public ServiceResponse uploadFile(long petId, String additionalMetadata, F * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall uploadFileAsync(long petId, String additionalMetadata, File file, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall uploadFileAsync(long petId, String additionalMetadata, byte[] file, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } From 53693bcd6bc511ee80845581cf7e66eea0a96d8e Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 11:21:13 -0700 Subject: [PATCH 19/99] Move primary type normalization to JavaPrimaryType --- .../Java/Java/AutoRest.Generator.Java.csproj | 6 + .../Generators/Java/Java/JavaCodeNamer.cs | 85 +------- .../Generators/Java/Java/Types/IJavaType.cs | 18 ++ .../Java/Java/Types/JavaCompositeType.cs | 30 +++ .../Java/Java/Types/JavaDictionaryType.cs | 24 +++ .../Java/Java/Types/JavaEnumType.cs | 24 +++ .../Java/Java/Types/JavaPrimaryType.cs | 193 ++++++++++++++++++ .../Java/Java/Types/JavaSequenceType.cs | 24 +++ 8 files changed, 326 insertions(+), 78 deletions(-) create mode 100644 AutoRest/Generators/Java/Java/Types/IJavaType.cs create mode 100644 AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs create mode 100644 AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs create mode 100644 AutoRest/Generators/Java/Java/Types/JavaEnumType.cs create mode 100644 AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs create mode 100644 AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs diff --git a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj index 53febfee98847..ff5d22547a176 100644 --- a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj +++ b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj @@ -32,6 +32,12 @@ Resources.resx + + + + + + diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index 00dc938d2965c..fade944ffd6e4 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -14,8 +14,6 @@ namespace Microsoft.Rest.Generator.Java { public class JavaCodeNamer : CodeNamer { - private readonly HashSet _normalizedTypes; - public const string ExternalExtension = "x-ms-external"; public static HashSet PrimaryTypes { get; private set; } @@ -47,7 +45,6 @@ public JavaCodeNamer() "period", "stream", "string", "object", "header" }.ForEach(s => ReservedWords.Add(s)); - _normalizedTypes = new HashSet(); PrimaryTypes = new HashSet(); new HashSet { @@ -259,16 +256,9 @@ public override IType NormalizeTypeReference(IType type) var enumType = type as EnumType; if (enumType != null && enumType.ModelAsString) { - type = new PrimaryType(KnownPrimaryType.String); + type = new JavaPrimaryType(KnownPrimaryType.String); } - // Using Any instead of Contains since object hash is bound to a property which is modified during normalization - if (_normalizedTypes.Any(item => type.Equals(item))) - { - return _normalizedTypes.First(item => type.Equals(item)); - } - - _normalizedTypes.Add(type); if (type is PrimaryType) { return NormalizePrimaryType(type as PrimaryType); @@ -310,7 +300,7 @@ private IType NormalizeEnumType(EnumType enumType) { enumType.Values[i].Name = GetEnumMemberName(enumType.Values[i].Name); } - return enumType; + return new JavaEnumType(enumType); } private IType NormalizeCompositeType(CompositeType compositeType) @@ -327,92 +317,31 @@ private IType NormalizeCompositeType(CompositeType compositeType) } } - return compositeType; + return new JavaCompositeType(compositeType); } - public static PrimaryType NormalizePrimaryType(PrimaryType primaryType) + public static JavaPrimaryType NormalizePrimaryType(PrimaryType primaryType) { if (primaryType == null) { throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) - { - primaryType.Name = "boolean"; - } - else if (primaryType.Type == KnownPrimaryType.ByteArray) - { - primaryType.Name = "byte[]"; - } - else if (primaryType.Type == KnownPrimaryType.Date) - { - primaryType.Name = "LocalDate"; - } - else if (primaryType.Type == KnownPrimaryType.DateTime) - { - primaryType.Name = "DateTime"; - } - else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123) - { - primaryType.Name = "DateTimeRfc1123"; - } - else if (primaryType.Type == KnownPrimaryType.Double) - { - primaryType.Name = "double"; - } - else if (primaryType.Type == KnownPrimaryType.Decimal) - { - primaryType.Name = "BigDecimal"; - } - else if (primaryType.Type == KnownPrimaryType.Int) - { - primaryType.Name = "int"; - } - else if (primaryType.Type == KnownPrimaryType.Long) - { - primaryType.Name = "long"; - } - else if (primaryType.Type == KnownPrimaryType.Stream) - { - primaryType.Name = "InputStream"; - } - else if (primaryType.Type == KnownPrimaryType.String) - { - primaryType.Name = "String"; - } - else if (primaryType.Type == KnownPrimaryType.TimeSpan) - { - primaryType.Name = "Period"; - } - else if (primaryType.Type == KnownPrimaryType.Uuid) - { - primaryType.Name = "UUID"; - } - else if (primaryType.Type == KnownPrimaryType.Object) - { - primaryType.Name = "Object"; - } - else if (primaryType.Type == KnownPrimaryType.Credentials) - { - primaryType.Name = "ServiceClientCredentials"; - } - - return primaryType; + return new JavaPrimaryType(primaryType); } private IType NormalizeSequenceType(SequenceType sequenceType) { sequenceType.ElementType = WrapPrimitiveType(NormalizeTypeReference(sequenceType.ElementType)); sequenceType.NameFormat = "List<{0}>"; - return sequenceType; + return new JavaSequenceType(sequenceType); } private IType NormalizeDictionaryType(DictionaryType dictionaryType) { dictionaryType.ValueType = WrapPrimitiveType(NormalizeTypeReference(dictionaryType.ValueType)); dictionaryType.NameFormat = "Map"; - return dictionaryType; + return new JavaDictionaryType(dictionaryType); } #endregion diff --git a/AutoRest/Generators/Java/Java/Types/IJavaType.cs b/AutoRest/Generators/Java/Java/Types/IJavaType.cs new file mode 100644 index 0000000000000..446171891c172 --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/IJavaType.cs @@ -0,0 +1,18 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public interface IJavaType : IType + { + List InterfaceImports { get; } + + List ImplImports { get; } + } +} diff --git a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs new file mode 100644 index 0000000000000..85d77afd045fd --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs @@ -0,0 +1,30 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public class JavaCompositeType : CompositeType, IJavaType + { + public JavaCompositeType(CompositeType compositeType) + : base() + { + this.LoadFrom(compositeType); + } + + public PrimaryType ParameterType { get; private set; } + + public PrimaryType InternalType { get; private set; } + + public PrimaryType ResponseType { get; private set; } + + public List InterfaceImports { get; private set; } + + public List ImplImports { get; private set; } + } +} diff --git a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs new file mode 100644 index 0000000000000..61117bd9be5b1 --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs @@ -0,0 +1,24 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public class JavaDictionaryType : DictionaryType, IJavaType + { + public JavaDictionaryType(DictionaryType dictionaryType) + : base() + { + this.LoadFrom(dictionaryType); + } + + public List InterfaceImports { get; private set; } + + public List ImplImports { get; private set; } + } +} diff --git a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs new file mode 100644 index 0000000000000..1348784956ea0 --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs @@ -0,0 +1,24 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public class JavaEnumType : EnumType, IJavaType + { + public JavaEnumType(EnumType sequenceType) + : base() + { + this.LoadFrom(sequenceType); + } + + public List InterfaceImports { get; private set; } + + public List ImplImports { get; private set; } + } +} diff --git a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs new file mode 100644 index 0000000000000..3e032f11c5e2e --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs @@ -0,0 +1,193 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class JavaPrimaryType : PrimaryType, IJavaType + { + private List _commonImports; + + public JavaPrimaryType(KnownPrimaryType knownPrimaryType) + : this (new PrimaryType(knownPrimaryType)) + { + } + + public JavaPrimaryType(PrimaryType primaryType) + : base (primaryType != null ? primaryType.Type : KnownPrimaryType.None) + { + if (primaryType == null) + { + throw new ArgumentNullException("primaryType"); + } + + this.LoadFrom(primaryType); + _commonImports = new List(); + _bodyFormat = "{0}"; + _headerFormat = "{0}"; + Initialize(primaryType); + } + + public string ParameterType + { + get + { + if (Type == KnownPrimaryType.DateTimeRfc1123) + { + return "DateTime"; + } + else if (Type == KnownPrimaryType.Stream) + { + return "byte[]"; + } + else + { + return Name; + } + } + } + + public string ResponseType + { + get + { + if (Type == KnownPrimaryType.DateTimeRfc1123) + { + return "DateTime"; + } + else + { + return Name; + } + } + } + + private string _bodyFormat; + + public string BodyValue(string reference) + { + return string.Format(CultureInfo.InvariantCulture, _bodyFormat, reference); + } + + public string _headerFormat; + + public string HeaderValue(string reference) + { + return string.Format(CultureInfo.InvariantCulture, _headerFormat, reference); + } + + public List InterfaceImports { get; private set; } + + public List ImplImports { get; private set; } + + public JavaPrimaryType IntanceType() + { + JavaPrimaryType instanceType = new JavaPrimaryType(this); + if (Name == "boolean") + { + instanceType.Name = "Boolean"; + } + else if (Name == "double") + { + instanceType.Name = "Double"; + } + else if (Name == "int") + { + instanceType.Name = "Integer"; + } + else if (Name == "long") + { + instanceType.Name = "Long"; + } + else if (Name == "void") + { + instanceType.Name = "Void"; + } + return instanceType; + } + + private void Initialize(PrimaryType primaryType) + { + if (primaryType.Type == KnownPrimaryType.None) + { + Name = "void"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) + { + Name = "boolean"; + } + else if (primaryType.Type == KnownPrimaryType.ByteArray) + { + Name = "byte[]"; + _headerFormat = "Base64.encodeBase64String({0})"; + } + else if (primaryType.Type == KnownPrimaryType.Date) + { + Name = "LocalDate"; + _commonImports.Add("org.joda.time.LocalDate"); + } + else if (primaryType.Type == KnownPrimaryType.DateTime) + { + Name = "DateTime"; + _commonImports.Add("org.joda.time.DateTime"); + } + else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123) + { + Name = "DateTimeRfc1123"; + _commonImports.Add("com.microsoft.rest.DateTimeRfc1123"); + _commonImports.Add("org.joda.time.DateTime"); + } + else if (primaryType.Type == KnownPrimaryType.Double) + { + Name = "double"; + } + else if (primaryType.Type == KnownPrimaryType.Decimal) + { + Name = "BigDecimal"; + _commonImports.Add("java.math.BigDecimal"); + } + else if (primaryType.Type == KnownPrimaryType.Int) + { + Name = "int"; + } + else if (primaryType.Type == KnownPrimaryType.Long) + { + Name = "long"; + } + else if (primaryType.Type == KnownPrimaryType.Stream) + { + Name = "InputStream"; + _commonImports.Add("java.io.InputStream"); + } + else if (primaryType.Type == KnownPrimaryType.String) + { + Name = "String"; + } + else if (primaryType.Type == KnownPrimaryType.TimeSpan) + { + Name = "Period"; + _commonImports.Add("org.joda.time.Period"); + } + else if (primaryType.Type == KnownPrimaryType.Uuid) + { + Name = "UUID"; + _commonImports.Add("java.util.UUID"); + } + else if (primaryType.Type == KnownPrimaryType.Object) + { + Name = "Object"; + } + else if (primaryType.Type == KnownPrimaryType.Credentials) + { + Name = "ServiceClientCredentials"; + _commonImports.Add("com.microsoft.rest.ServiceClientCredentials"); + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs new file mode 100644 index 0000000000000..6a94d0ea5506d --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs @@ -0,0 +1,24 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public class JavaSequenceType : SequenceType, IJavaType + { + public JavaSequenceType(SequenceType sequenceType) + : base() + { + this.LoadFrom(sequenceType); + } + + public List InterfaceImports { get; private set; } + + public List ImplImports { get; private set; } + } +} From fe85341597212e569393e5079a3c13a9fd5a54ee Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 12:50:01 -0700 Subject: [PATCH 20/99] Add JavaParameter --- .../Extensions.Tests/ExtensionsTests.cs | 2 +- .../Java/Azure.Java/AzureJavaCodeGenerator.cs | 2 +- .../Java/Azure.Java/AzureJavaCodeNamer.cs | 5 ++ .../AzureMethodTemplateModel.cs | 2 +- .../TemplateModels/AzureModelTemplateModel.cs | 2 +- .../Templates/AzureMethodTemplate.cshtml | 8 +-- .../Java/Java/AutoRest.Generator.Java.csproj | 1 + .../Generators/Java/Java/JavaCodeGenerator.cs | 2 +- .../Generators/Java/Java/JavaCodeNamer.cs | 9 ++- .../TemplateModels/MethodTemplateModel.cs | 22 +++--- .../Java/TemplateModels/ModelTemplateModel.cs | 2 +- .../Java/Java/Templates/MethodTemplate.cshtml | 8 +-- .../Generators/Java/Java/Types/IJavaType.cs | 4 +- .../Java/Java/Types/JavaCompositeType.cs | 21 +++++- .../Java/Java/Types/JavaDictionaryType.cs | 17 ++++- .../Java/Java/Types/JavaEnumType.cs | 23 +++++-- .../Java/Java/Types/JavaPrimaryType.cs | 69 +++++++++++-------- .../Java/Java/Types/JavaSequenceType.cs | 17 ++++- 18 files changed, 146 insertions(+), 70 deletions(-) diff --git a/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs b/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs index dc5dc9154620d..7c11fadab6eae 100644 --- a/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs +++ b/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs @@ -193,7 +193,7 @@ public void TestClientNameJavaNormalization() var modeler = new SwaggerModeler(setting); var clientModel = modeler.Build(); Extensions.NormalizeClientModel(clientModel, setting); - var namer = new Microsoft.Rest.Generator.Java.JavaCodeNamer(); + var namer = new Microsoft.Rest.Generator.Java.JavaCodeNamer(setting.Namespace); namer.NormalizeClientModel(clientModel); Assert.NotNull(clientModel); diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs index b4d8972515fd8..d17290e7a1b97 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs @@ -26,7 +26,7 @@ public class AzureJavaCodeGenerator : JavaCodeGenerator public AzureJavaCodeGenerator(Settings settings) : base(settings) { - _namer = new AzureJavaCodeNamer(); + _namer = new AzureJavaCodeNamer(settings.Namespace); IsSingleFileGenerationSupported = true; pageClasses = new Dictionary, string>(); } diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs index 66572a9409c37..9c95127a1fda1 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs @@ -13,6 +13,11 @@ namespace Microsoft.Rest.Generator.Java.Azure { public class AzureJavaCodeNamer : JavaCodeNamer { + public AzureJavaCodeNamer(string nameSpace) + : base(nameSpace) + { + } + #region normalization private static string GetPagingSetting(Dictionary extensions, IDictionary, string> pageClasses, out string nextLinkName) diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 32ec961c47898..0f6de78949375 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -27,7 +27,7 @@ public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source); this.RequestIdString = AzureExtensions.GetRequestIdString(source); - this._namer = new AzureJavaCodeNamer(); + this._namer = new AzureJavaCodeNamer(serviceClient.Namespace); } protected override JavaCodeNamer Namer diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs index e1c9e3e514e45..b1599747f1d74 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs @@ -18,7 +18,7 @@ public class AzureModelTemplateModel : ModelTemplateModel public AzureModelTemplateModel(CompositeType source, ServiceClient serviceClient) : base(source, serviceClient) { - _namer = new AzureJavaCodeNamer(); + _namer = new AzureJavaCodeNamer(serviceClient.Namespace); } protected override JavaCodeNamer Namer diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index c35f3214704c2..bc0f46d6748f9 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -56,7 +56,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -106,7 +106,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -176,7 +176,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParam @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -222,7 +222,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (parameter.IsConstant) { diff --git a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj index ff5d22547a176..dd91747fe86d9 100644 --- a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj +++ b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj @@ -32,6 +32,7 @@ Resources.resx + diff --git a/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs b/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs index a40e506870426..275c4b16eb4e3 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs @@ -21,7 +21,7 @@ public class JavaCodeGenerator : CodeGenerator public JavaCodeGenerator(Settings settings) : base(settings) { - Namer = new JavaCodeNamer(); + Namer = new JavaCodeNamer(settings.Namespace); } public override string Name diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index fade944ffd6e4..9e49475170752 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -20,15 +20,18 @@ public class JavaCodeNamer : CodeNamer public static HashSet JavaBuiltInTypes { get; private set; } + protected string _package; + #region constructor /// /// Initializes a new instance of CSharpCodeNamingFramework. /// - public JavaCodeNamer() + public JavaCodeNamer(string nameSpace) { // List retrieved from // http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html + _package = nameSpace.ToLower(CultureInfo.InvariantCulture); new HashSet { "abstract", "assert", "boolean", "break", "byte", @@ -300,7 +303,7 @@ private IType NormalizeEnumType(EnumType enumType) { enumType.Values[i].Name = GetEnumMemberName(enumType.Values[i].Name); } - return new JavaEnumType(enumType); + return new JavaEnumType(enumType, _package); } private IType NormalizeCompositeType(CompositeType compositeType) @@ -317,7 +320,7 @@ private IType NormalizeCompositeType(CompositeType compositeType) } } - return new JavaCompositeType(compositeType); + return new JavaCompositeType(compositeType, _package); } public static JavaPrimaryType NormalizePrimaryType(PrimaryType primaryType) diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 3d7b0e5644766..68d50170957e2 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -19,9 +19,9 @@ public class MethodTemplateModel : Method public MethodTemplateModel(Method source, ServiceClient serviceClient) { this.LoadFrom(source); - ParameterTemplateModels = new List(); - source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p))); - source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p))); + JavaParameters = new List(); + source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p))); + source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p))); ServiceClient = serviceClient; if (source.Group != null) { @@ -33,7 +33,7 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) OperationName = serviceClient.Name; ClientReference = "this"; } - _namer = new JavaCodeNamer(); + _namer = new JavaCodeNamer(serviceClient.Namespace); } protected virtual JavaCodeNamer Namer @@ -50,7 +50,7 @@ protected virtual JavaCodeNamer Namer public ServiceClient ServiceClient { get; set; } - public List ParameterTemplateModels { get; private set; } + public List JavaParameters { get; private set; } public IEnumerable RetrofitParameters { @@ -336,11 +336,11 @@ private static string BuildNullCheckExpression(ParameterTransformation transform .Select(m => m.InputParameter.Name + " != null")); } - public IEnumerable RequiredNullableParameters + public IEnumerable RequiredNullableParameters { get { - foreach (var param in ParameterTemplateModels) + foreach (var param in JavaParameters) { if (!param.Type.IsPrimaryType(KnownPrimaryType.Int) && !param.Type.IsPrimaryType(KnownPrimaryType.Double) && @@ -354,11 +354,11 @@ public IEnumerable RequiredNullableParameters } } - public IEnumerable ParametersToValidate + public IEnumerable ParametersToValidate { get { - foreach (var param in ParameterTemplateModels) + foreach (var param in JavaParameters) { if (param.Type is PrimaryType || param.Type is EnumType || @@ -447,12 +447,12 @@ public virtual string MethodParameterInvocationWithCallback /// Get the parameters that are actually method parameters in the order they appear in the method signature /// exclude global parameters /// - public IEnumerable LocalParameters + public IEnumerable LocalParameters { get { //Omit parameter-group properties for now since Java doesn't support them yet - return ParameterTemplateModels.Where( + return JavaParameters.Where( p => p != null && p.ClientProperty == null && !string.IsNullOrWhiteSpace(p.Name)) .OrderBy(item => !item.IsRequired); } diff --git a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs index 715171fac30c8..74e13623f1416 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs @@ -25,7 +25,7 @@ public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) { _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } - _namer = new JavaCodeNamer(); + _namer = new JavaCodeNamer(serviceClient.Namespace); } protected virtual JavaCodeNamer Namer diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index e3a722c848842..de5ccb0673faa 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -45,7 +45,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi { @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -105,7 +105,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -180,7 +180,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParam { @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -235,7 +235,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (JavaParameter parameter in Model.LocalParameters) { if (parameter.IsConstant) { diff --git a/AutoRest/Generators/Java/Java/Types/IJavaType.cs b/AutoRest/Generators/Java/Java/Types/IJavaType.cs index 446171891c172..5efcba17751d9 100644 --- a/AutoRest/Generators/Java/Java/Types/IJavaType.cs +++ b/AutoRest/Generators/Java/Java/Types/IJavaType.cs @@ -11,8 +11,8 @@ namespace Microsoft.Rest.Generator.Java { public interface IJavaType : IType { - List InterfaceImports { get; } + string DefaultValue { get; } - List ImplImports { get; } + IEnumerable Imports { get; } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs index 85d77afd045fd..ddbe3761146e2 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs @@ -11,10 +11,13 @@ namespace Microsoft.Rest.Generator.Java { public class JavaCompositeType : CompositeType, IJavaType { - public JavaCompositeType(CompositeType compositeType) + private string _package; + + public JavaCompositeType(CompositeType compositeType, string package) : base() { this.LoadFrom(compositeType); + this._package = package; } public PrimaryType ParameterType { get; private set; } @@ -23,8 +26,20 @@ public JavaCompositeType(CompositeType compositeType) public PrimaryType ResponseType { get; private set; } - public List InterfaceImports { get; private set; } + public string DefaultValue + { + get + { + return "null"; + } + } - public List ImplImports { get; private set; } + public IEnumerable Imports + { + get + { + yield return string.Join(".", _package, Name); + } + } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs index 61117bd9be5b1..2469f9b1fb74e 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs @@ -17,8 +17,21 @@ public JavaDictionaryType(DictionaryType dictionaryType) this.LoadFrom(dictionaryType); } - public List InterfaceImports { get; private set; } + public string DefaultValue + { + get + { + return "null"; + } + } - public List ImplImports { get; private set; } + public IEnumerable Imports + { + get + { + List imports = new List { "java.util.Map" }; + return imports.Concat(((IJavaType) this.ValueType).Imports); + } + } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs index 1348784956ea0..7b11c6a4f174e 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs @@ -11,14 +11,29 @@ namespace Microsoft.Rest.Generator.Java { public class JavaEnumType : EnumType, IJavaType { - public JavaEnumType(EnumType sequenceType) + private string _package; + + public JavaEnumType(EnumType enumType, string package) : base() { - this.LoadFrom(sequenceType); + this.LoadFrom(enumType); + this._package = package; } - public List InterfaceImports { get; private set; } + public string DefaultValue + { + get + { + return "null"; + } + } - public List ImplImports { get; private set; } + public IEnumerable Imports + { + get + { + yield return string.Join(".", _package, Name); + } + } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs index 3e032f11c5e2e..3af2f72e8e53e 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs @@ -12,7 +12,7 @@ namespace Microsoft.Rest.Generator.Java { public class JavaPrimaryType : PrimaryType, IJavaType { - private List _commonImports; + private List _imports; public JavaPrimaryType(KnownPrimaryType knownPrimaryType) : this (new PrimaryType(knownPrimaryType)) @@ -28,12 +28,34 @@ public JavaPrimaryType(PrimaryType primaryType) } this.LoadFrom(primaryType); - _commonImports = new List(); - _bodyFormat = "{0}"; - _headerFormat = "{0}"; + _imports = new List(); Initialize(primaryType); } + public string DefaultValue + { + get + { + if (this.Name == "byte[]") + { + return "new byte[0]"; + } + else if (this.Name == "Byte[]") + { + return "new Byte[]"; + } + else if (this.Name[0] >= 'A' && this.Name[0] <= 'Z') + // instance type + { + return "null"; + } + else + { + throw new NotSupportedException(this.Name + " does not have default value!"); + } + } + } + public string ParameterType { get @@ -68,24 +90,14 @@ public string ResponseType } } - private string _bodyFormat; - - public string BodyValue(string reference) - { - return string.Format(CultureInfo.InvariantCulture, _bodyFormat, reference); - } - - public string _headerFormat; - - public string HeaderValue(string reference) + public IEnumerable Imports { - return string.Format(CultureInfo.InvariantCulture, _headerFormat, reference); + get + { + return _imports; + } } - public List InterfaceImports { get; private set; } - - public List ImplImports { get; private set; } - public JavaPrimaryType IntanceType() { JavaPrimaryType instanceType = new JavaPrimaryType(this); @@ -125,23 +137,22 @@ private void Initialize(PrimaryType primaryType) else if (primaryType.Type == KnownPrimaryType.ByteArray) { Name = "byte[]"; - _headerFormat = "Base64.encodeBase64String({0})"; } else if (primaryType.Type == KnownPrimaryType.Date) { Name = "LocalDate"; - _commonImports.Add("org.joda.time.LocalDate"); + _imports.Add("org.joda.time.LocalDate"); } else if (primaryType.Type == KnownPrimaryType.DateTime) { Name = "DateTime"; - _commonImports.Add("org.joda.time.DateTime"); + _imports.Add("org.joda.time.DateTime"); } else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123) { Name = "DateTimeRfc1123"; - _commonImports.Add("com.microsoft.rest.DateTimeRfc1123"); - _commonImports.Add("org.joda.time.DateTime"); + _imports.Add("com.microsoft.rest.DateTimeRfc1123"); + _imports.Add("org.joda.time.DateTime"); } else if (primaryType.Type == KnownPrimaryType.Double) { @@ -150,7 +161,7 @@ private void Initialize(PrimaryType primaryType) else if (primaryType.Type == KnownPrimaryType.Decimal) { Name = "BigDecimal"; - _commonImports.Add("java.math.BigDecimal"); + _imports.Add("java.math.BigDecimal"); } else if (primaryType.Type == KnownPrimaryType.Int) { @@ -163,7 +174,7 @@ private void Initialize(PrimaryType primaryType) else if (primaryType.Type == KnownPrimaryType.Stream) { Name = "InputStream"; - _commonImports.Add("java.io.InputStream"); + _imports.Add("java.io.InputStream"); } else if (primaryType.Type == KnownPrimaryType.String) { @@ -172,12 +183,12 @@ private void Initialize(PrimaryType primaryType) else if (primaryType.Type == KnownPrimaryType.TimeSpan) { Name = "Period"; - _commonImports.Add("org.joda.time.Period"); + _imports.Add("org.joda.time.Period"); } else if (primaryType.Type == KnownPrimaryType.Uuid) { Name = "UUID"; - _commonImports.Add("java.util.UUID"); + _imports.Add("java.util.UUID"); } else if (primaryType.Type == KnownPrimaryType.Object) { @@ -186,7 +197,7 @@ private void Initialize(PrimaryType primaryType) else if (primaryType.Type == KnownPrimaryType.Credentials) { Name = "ServiceClientCredentials"; - _commonImports.Add("com.microsoft.rest.ServiceClientCredentials"); + _imports.Add("com.microsoft.rest.ServiceClientCredentials"); } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs index 6a94d0ea5506d..8a8b7255e145e 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs @@ -17,8 +17,21 @@ public JavaSequenceType(SequenceType sequenceType) this.LoadFrom(sequenceType); } - public List InterfaceImports { get; private set; } + public string DefaultValue + { + get + { + return "null"; + } + } - public List ImplImports { get; private set; } + public IEnumerable Imports + { + get + { + List imports = new List { "java.util.List" }; + return imports.Concat(((IJavaType) this.ElementType).Imports); + } + } } } From b74a6549a34ba2f07c6670fb35845878b84a64a3 Mon Sep 17 00:00:00 2001 From: tbombach Date: Wed, 23 Mar 2016 12:51:45 -0700 Subject: [PATCH 21/99] Updating nodejs coverage test to exclude base64url tests that haven't yet been implemented in the language --- .../CSharp.Tests/Expected/AcceptanceTests/BodyFile/Files.cs | 6 +++--- .../Expected/AcceptanceTests/BodyFormData/Formdata.cs | 4 ++-- .../NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts | 4 ++++ 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFile/Files.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFile/Files.cs index ea4a96a03e8a7..a2d36ef61ee24 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFile/Files.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFile/Files.cs @@ -101,7 +101,7 @@ public Files(AutoRestSwaggerBATFileService client) ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); @@ -207,7 +207,7 @@ public Files(AutoRestSwaggerBATFileService client) ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); @@ -313,7 +313,7 @@ public Files(AutoRestSwaggerBATFileService client) ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFormData/Formdata.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFormData/Formdata.cs index 175b7baab57de..1880317e4a195 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFormData/Formdata.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyFormData/Formdata.cs @@ -138,7 +138,7 @@ public Formdata(AutoRestSwaggerBATFormDataService client) ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); @@ -255,7 +255,7 @@ public Formdata(AutoRestSwaggerBATFormDataService client) ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); - _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts index cbf8c0bfbd269..ed403ebe66cc0 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts @@ -17,6 +17,8 @@ var credentials = new msRest.TokenCredentials(dummyToken); var clientOptions = {}; var baseUri = 'http://localhost:3000'; +/* TODO: nodejs generator doesn't yet support the base64url format. Exclude these tests from code coverage until it is implemented */ +var unimplementedTests = ["getStringBase64Encoded", "getStringBase64UrlEncoded", "putStringBase64UrlEncoded", "getStringNullBase64UrlEncoding"]; describe('nodejs', function () { @@ -30,6 +32,8 @@ describe('nodejs', function () { _.keys(result).forEach(function(item: string) { if (result[item] > 0) { passed++; + } else if (unimplementedTests.indexOf(item) != -1) { + total--; } else { console.log('No coverage for scenario: ' + item + '\n'); } From 285b4321a18ff766b24ac00fa526f718d1aacf60 Mon Sep 17 00:00:00 2001 From: tbombach Date: Wed, 23 Mar 2016 14:25:23 -0700 Subject: [PATCH 22/99] Adding the code coverage exception for base64url format for all languages until they implement the serialization for the type --- .../NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts | 4 ---- AutoRest/TestServer/server/app.js | 9 +++++---- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts index ed403ebe66cc0..cbf8c0bfbd269 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/coverageTest.ts @@ -17,8 +17,6 @@ var credentials = new msRest.TokenCredentials(dummyToken); var clientOptions = {}; var baseUri = 'http://localhost:3000'; -/* TODO: nodejs generator doesn't yet support the base64url format. Exclude these tests from code coverage until it is implemented */ -var unimplementedTests = ["getStringBase64Encoded", "getStringBase64UrlEncoded", "putStringBase64UrlEncoded", "getStringNullBase64UrlEncoding"]; describe('nodejs', function () { @@ -32,8 +30,6 @@ describe('nodejs', function () { _.keys(result).forEach(function(item: string) { if (result[item] > 0) { passed++; - } else if (unimplementedTests.indexOf(item) != -1) { - total--; } else { console.log('No coverage for scenario: ' + item + '\n'); } diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index 54c271aff2b77..e77c80709f313 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -195,10 +195,11 @@ var coverage = { "getStringWithLeadingAndTrailingWhitespace" : 0, "putStringWithLeadingAndTrailingWhitespace" : 0, "getStringNotProvided": 0, - "getStringBase64Encoded": 0, - "getStringBase64UrlEncoded": 0, - "putStringBase64UrlEncoded": 0, - "getStringNullBase64UrlEncoding": 0, + /* TODO: only C# supports the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */ + "getStringBase64Encoded": 1, + "getStringBase64UrlEncoded": 1, + "putStringBase64UrlEncoded": 1, + "getStringNullBase64UrlEncoding": 1, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, From 8466b633384530c504fd18bcd3b7cb032a7267c2 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 15:01:51 -0700 Subject: [PATCH 23/99] Generate import list from JavaParameter --- .../AzureMethodTemplateModel.cs | 12 +-- .../fixtures/bodyarray/ArrayOperations.java | 1 - .../bodyarray/ArrayOperationsImpl.java | 1 - .../bodydictionary/DictionaryOperations.java | 1 - .../DictionaryOperationsImpl.java | 1 - .../HeaderResponseDatetimeRfc1123Headers.java | 1 - .../Java/Java/ClientModelExtensions.cs | 8 +- .../TemplateModels/MethodTemplateModel.cs | 59 ++++++------ .../Java/TemplateModels/ModelTemplateModel.cs | 2 +- .../Java/Java/Types/JavaCompositeType.cs | 9 +- .../Java/Java/Types/JavaEnumType.cs | 2 +- .../Java/Java/Types/JavaParameter.cs | 93 +++++++++++++++++++ .../Java/Java/Types/JavaPrimaryType.cs | 1 - 13 files changed, 141 insertions(+), 50 deletions(-) create mode 100644 AutoRest/Generators/Java/Java/Types/JavaParameter.cs diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 0f6de78949375..d9f7d48880c35 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -588,7 +588,7 @@ public override List InterfaceImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.PagedList"); imports.Remove("java.util.List"); - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportFrom()); } return imports; } @@ -606,11 +606,11 @@ public override List ImplImports imports.Remove("com.microsoft.azure.AzureServiceResponseBuilder"); imports.Add("retrofit2.Callback"); this.Responses.Select(r => r.Value.Body).Concat(new IType[]{ DefaultResponse.Body }) - .SelectMany(t => t.ImportFrom(ServiceClient.Namespace, Namer)) - .Where(i => !this.Parameters.Any(p => p.Type.ImportFrom(ServiceClient.Namespace, Namer).Contains(i))) + .SelectMany(t => t.ImportFrom()) + .Where(i => !this.Parameters.Any(p => p.Type.ImportFrom().Contains(i))) .ForEach(i => imports.Remove(i)); // return type may have been removed as a side effect - imports.AddRange(this.ReturnType.Body.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(this.ReturnType.Body.ImportFrom()); } if (this.IsPagingOperation || this.IsPagingNextOperation) { @@ -618,7 +618,7 @@ public override List ImplImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.Page"); imports.Add("com.microsoft.azure.PagedList"); - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportFrom()); } if (this.IsPagingNextOperation) { @@ -627,7 +627,7 @@ public override List ImplImports } if (this.IsPagingNonPollingOperation) { - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom()); } return imports; } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java index 31770e6ff4800..d781da1d96839 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java @@ -10,7 +10,6 @@ package fixtures.bodyarray; -import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java index 3833b47176fab..45b10b52164d4 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java @@ -11,7 +11,6 @@ package fixtures.bodyarray; import com.google.common.reflect.TypeToken; -import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java index e97d98320d4e8..e6c01f856a4b0 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java @@ -10,7 +10,6 @@ package fixtures.bodydictionary; -import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java index 7e1d89fe32734..d350ead94103b 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java @@ -11,7 +11,6 @@ package fixtures.bodydictionary; import com.google.common.reflect.TypeToken; -import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java index 627af266e6942..22c7e760a3ee1 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java @@ -10,7 +10,6 @@ package fixtures.header.models; -import com.microsoft.rest.DateTimeRfc1123; import org.joda.time.DateTime; /** diff --git a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs index e89a151cf9897..21f6a8a9c9b9e 100644 --- a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs +++ b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs @@ -150,13 +150,13 @@ public static IType UserHandledType(this IType type) } } - public static List ImportFrom(this IType type, string ns, JavaCodeNamer namer) + public static IEnumerable ImportFrom(this IType type) { - if (namer == null) + if (type == null) { - return null; + return new List(); } - return namer.ImportType(type, ns); + return ((IJavaType) type).Imports; } public static List ImportFrom(this Parameter parameter) diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 68d50170957e2..70ef866907901 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -20,8 +20,10 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) { this.LoadFrom(source); JavaParameters = new List(); + JavaLogicalParameters = new List(); source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p))); source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p))); + source.LogicalParameters.ForEach(p => JavaLogicalParameters.Add(new JavaParameter(p))); ServiceClient = serviceClient; if (source.Group != null) { @@ -52,16 +54,18 @@ protected virtual JavaCodeNamer Namer public List JavaParameters { get; private set; } - public IEnumerable RetrofitParameters + public List JavaLogicalParameters { get; private set; } + + public IEnumerable RetrofitParameters { get { - return LogicalParameters.Where(p => p.Location != ParameterLocation.None) + return JavaLogicalParameters.Where(p => p.Location != ParameterLocation.None) .Where(p => !p.Extensions.ContainsKey("hostParameter")); } } - public IEnumerable OrderedRetrofitParameters + public IEnumerable OrderedRetrofitParameters { get { @@ -744,17 +748,11 @@ public virtual List InterfaceImports imports.Add("com.microsoft.rest." + OperationResponseType); imports.Add("com.microsoft.rest.ServiceCallback"); // parameter types - this.Parameters.ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); + this.JavaParameters.ForEach(p => imports.AddRange(p.InterfaceImports)); // return type - imports.AddRange(this.ReturnType.Body.ImportFrom(ServiceClient.Namespace, Namer)); - if (Parameters.Any(p => p.Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - || ReturnType.Body.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123) - || ReturnType.Headers.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - imports.Remove("com.microsoft.rest.DateTimeRfc1123"); - } + imports.AddRange(this.ReturnType.Body.ImportFrom()); // Header type - imports.AddRange(this.ReturnType.Headers.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(this.ReturnType.Headers.ImportFrom()); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => { @@ -790,20 +788,21 @@ public virtual List ImplImports imports.Add("com.microsoft.rest." + OperationResponseType); imports.Add(RuntimeBasePackage + "." + ResponseBuilder); imports.Add("com.microsoft.rest.ServiceCallback"); - // API parameters - this.RetrofitParameters - .Where(p => p.Location == ParameterLocation.Body - || !p.Type.NeedsSpecialSerialization()) - .ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); - // parameter locations - this.RetrofitParameters.ForEach(p => - { - string locationImport = p.Location.ImportFrom(); - if (!string.IsNullOrEmpty(locationImport)) - { - imports.Add(p.Location.ImportFrom()); - } - }); + //// API parameters + //this.RetrofitParameters + // .Where(p => p.Location == ParameterLocation.Body + // || !p.Type.NeedsSpecialSerialization()) + // .ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); + //// parameter locations + //this.RetrofitParameters.ForEach(p => + //{ + // string locationImport = p.Location.ImportFrom(); + // if (!string.IsNullOrEmpty(locationImport)) + // { + // imports.Add(p.Location.ImportFrom()); + // } + //}); + this.RetrofitParameters.ForEach(p => imports.AddRange(p.ImplImports)); // Http verb annotations imports.Add(this.HttpMethod.ImportFrom()); // response type conversion @@ -827,20 +826,20 @@ public virtual List ImplImports } // parameter types this.LocalParameters.Concat(this.LogicalParameters) - .ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); + .ForEach(p => imports.AddRange(p.Type.ImportFrom())); // parameter utils this.LocalParameters.Concat(this.LogicalParameters) .ForEach(p => imports.AddRange(p.ImportFrom())); // return type - imports.AddRange(this.ReturnType.Body.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(this.ReturnType.Body.ImportFrom()); if (ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) { imports.Add("retrofit2.http.Streaming"); } // response type (can be different from return type) - this.Responses.ForEach(r => imports.AddRange(r.Value.Body.ImportFrom(ServiceClient.Namespace, Namer))); + this.Responses.ForEach(r => imports.AddRange(r.Value.Body.ImportFrom())); // Header type - imports.AddRange(this.ReturnType.Headers.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(this.ReturnType.Headers.ImportFrom()); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => diff --git a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs index 74e13623f1416..da6db86b9a92a 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs @@ -142,7 +142,7 @@ public virtual IEnumerable ImportList { HashSet classes = new HashSet(); foreach (var property in this.Properties) { - classes.AddRange(property.Type.ImportFrom(ServiceClient.Namespace, Namer) + classes.AddRange(property.Type.ImportFrom() .Where(c => !c.StartsWith( string.Join(".", ServiceClient.Namespace, "models"), StringComparison.OrdinalIgnoreCase))); diff --git a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs index ddbe3761146e2..9f9acd05651d1 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs @@ -14,9 +14,14 @@ public class JavaCompositeType : CompositeType, IJavaType private string _package; public JavaCompositeType(CompositeType compositeType, string package) - : base() + : this(package) { this.LoadFrom(compositeType); + } + + public JavaCompositeType(string package) + : base() + { this._package = package; } @@ -38,7 +43,7 @@ public IEnumerable Imports { get { - yield return string.Join(".", _package, Name); + yield return string.Join(".", _package, "models", Name); } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs index 7b11c6a4f174e..7aee5b56eae8b 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs @@ -32,7 +32,7 @@ public IEnumerable Imports { get { - yield return string.Join(".", _package, Name); + yield return string.Join(".", _package, "models", Name); } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaParameter.cs b/AutoRest/Generators/Java/Java/Types/JavaParameter.cs new file mode 100644 index 0000000000000..1fc5d74c09362 --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/JavaParameter.cs @@ -0,0 +1,93 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public class JavaParameter : Parameter + { + public JavaParameter(Parameter parameter) + : base() + { + this.LoadFrom(parameter); + } + + //public string TypeString + //{ + // get + // { + // return ((IJavaType)Type).ParameterType; + // } + //} + + public IEnumerable InterfaceImports + { + get + { + return ((IJavaType) Type).Imports; + } + } + + public IEnumerable RetrofitImports + { + get + { + // type imports + var imports = new List(((IJavaType)Type).Imports); + if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + imports.Add("com.microsoft.rest.DateTimeRfc1123"); + } + // parameter location + imports.Add(LocationImport(this.Location)); + return imports; + } + } + + public IEnumerable ImplImports + { + get + { + var imports = RetrofitImports.ToList(); + if (Location == ParameterLocation.Header) + { + if (this.Type.IsPrimaryType(KnownPrimaryType.ByteArray)) + { + imports.Add("org.apache.commons.codec.binary.Base64"); + } + else if (this.Type is SequenceType) + { + imports.Add("com.microsoft.rest.serializer.CollectionFormat"); + } + } + if (Type.IsPrimaryType(KnownPrimaryType.Stream) && Location == ParameterLocation.Body) + { + imports.Add("okhttp3.RequestBody"); + imports.Add("okhttp3.MediaType"); + } + return imports; + } + } + + private string LocationImport(ParameterLocation parameterLocation) + { + if (parameterLocation == ParameterLocation.FormData) + { + return "retrofit2.http.Part"; + } + else if (parameterLocation != ParameterLocation.None) + { + return "retrofit2.http." + parameterLocation.ToString(); + } + else + { + return null; + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs index 3af2f72e8e53e..0fa0bfb7d79af 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs @@ -151,7 +151,6 @@ private void Initialize(PrimaryType primaryType) else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123) { Name = "DateTimeRfc1123"; - _imports.Add("com.microsoft.rest.DateTimeRfc1123"); _imports.Add("org.joda.time.DateTime"); } else if (primaryType.Type == KnownPrimaryType.Double) From 3e4df712343c7f3f0614d66133910efb65d319e0 Mon Sep 17 00:00:00 2001 From: tbombach Date: Wed, 23 Mar 2016 16:11:37 -0700 Subject: [PATCH 24/99] Adding tests to ensure base64url format works in a dictionary and an array --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 14 +- .../AcceptanceTests/BodyArray/Array.cs | 120 ++++++++++++++++++ .../BodyArray/ArrayExtensions.cs | 30 +++++ .../AcceptanceTests/BodyArray/IArray.cs | 11 ++ .../BodyDictionary/Dictionary.cs | 120 ++++++++++++++++++ .../BodyDictionary/DictionaryExtensions.cs | 30 +++++ .../BodyDictionary/IDictionary.cs | 11 ++ .../BodyString/IStringModel.cs | 2 +- .../AcceptanceTests/BodyString/StringModel.cs | 4 +- .../BodyString/StringModelExtensions.cs | 8 +- AutoRest/TestServer/server/app.js | 2 + AutoRest/TestServer/server/routes/array.js | 9 +- .../TestServer/server/routes/dictionary.js | 9 +- AutoRest/TestServer/swagger/body-array.json | 30 ++++- .../TestServer/swagger/body-dictionary.json | 28 ++++ AutoRest/TestServer/swagger/body-string.json | 2 +- 16 files changed, 418 insertions(+), 12 deletions(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index bd82017ede193..3b7b3cfba0867 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -279,7 +279,7 @@ public void StringTests() var base64EncodedString = client.StringModel.GetBase64Encoded(); Assert.Equal(Encoding.UTF8.GetString(base64UrlEncodedString), "a string that gets encoded with base64url"); Assert.Equal(Encoding.UTF8.GetString(base64EncodedString), "a string that gets encoded with base64"); - Assert.Null(client.StringModel.GetNullBase64Encoded()); + Assert.Null(client.StringModel.GetNullBase64UrlEncoded()); client.StringModel.PutBase64UrlEncoded(Encoding.UTF8.GetBytes("a string that gets encoded with base64url")); } } @@ -658,6 +658,11 @@ public void ArrayTests() Assert.Equal(new List { guid1, guid2, guid3 }, client.Array.GetUuidValid()); client.Array.PutUuidValid(new List { guid1, guid2, guid3 }); Assert.Throws(() => client.Array.GetUuidInvalidChars()); + + var base64Url1 = Encoding.UTF8.GetBytes("a string that gets encoded with base64url"); + var base64Url2 = Encoding.UTF8.GetBytes("test string"); + var base64Url3 = Encoding.UTF8.GetBytes("Lorem ipsum"); + Assert.Equal(new List { base64Url1, base64Url2, base64Url3 }, client.Array.GetBase64Url()); } } @@ -967,6 +972,13 @@ private static void TestDictionaryPrimitiveTypes(AutoRestSwaggerBATdictionarySer Assert.True(bytesResult.ContainsKey(key)); Assert.Equal(bytesNull[key], bytesResult[key], new ByteArrayEqualityComparer()); } + // GET prim/base64url/valid + var base64UrlString1 = Encoding.UTF8.GetBytes("a string that gets encoded with base64url"); + var base64UrlString2 = Encoding.UTF8.GetBytes("test string"); + var base64UrlString3 = Encoding.UTF8.GetBytes("Lorem ipsum"); + var base64UrlStringValid = new Dictionary {{"0", base64UrlString1}, {"1", base64UrlString2}, {"2", base64UrlString3}}; + var base64UrlStringResult = client.Dictionary.GetBase64Url(); + Assert.Equal(base64UrlStringValid, base64UrlStringResult); } private static void TestBasicDictionaryParsing(AutoRestSwaggerBATdictionaryService client) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs index 0b9d94dc699a5..ced22714ec458 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs @@ -5429,6 +5429,126 @@ public Array(AutoRestSwaggerBATArrayService client) return _result; } + /// + /// Get array value ['a string that gets encoded with base64url', 'test + /// string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64Url", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "array/prim/base64url/valid").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + /// /// Get array of complex type null value /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs index 283d2324b9961..1b1f220f613eb 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs @@ -1344,6 +1344,36 @@ public static IList GetByteInvalidNull(this IArray operations) } } + /// + /// Get array value ['a string that gets encoded with base64url', 'test + /// string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// The operations group for this extension method. + /// + public static IList GetBase64Url(this IArray operations) + { + return Task.Factory.StartNew(s => ((IArray)s).GetBase64UrlAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get array value ['a string that gets encoded with base64url', 'test + /// string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> GetBase64UrlAsync(this IArray operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64UrlWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + /// /// Get array of complex type null value /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs index 51288d0a84660..65f46721b9268 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs @@ -520,6 +520,17 @@ public partial interface IArray /// Task>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// + /// Get array value ['a string that gets encoded with base64url', + /// 'test string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// /// Get array of complex type null value /// /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs index a370279790948..898020ed6bf1f 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs @@ -5438,6 +5438,126 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) return _result; } + /// + /// Get base64url dictionary value {"0": "a string that gets encoded with + /// base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64Url", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "dictionary/prim/base64url/valid").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + /// /// Get dictionary of complex type null value /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs index 890eea653ece8..081c30c09bcb2 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs @@ -1345,6 +1345,36 @@ public static IDictionary GetByteInvalidNull(this IDictionary op } } + /// + /// Get base64url dictionary value {"0": "a string that gets encoded with + /// base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// The operations group for this extension method. + /// + public static IDictionary GetBase64Url(this IDictionary operations) + { + return Task.Factory.StartNew(s => ((IDictionary)s).GetBase64UrlAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get base64url dictionary value {"0": "a string that gets encoded with + /// base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> GetBase64UrlAsync(this IDictionary operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64UrlWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + /// /// Get dictionary of complex type null value /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs index 53da3621b1eb1..8c5451a26f103 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs @@ -524,6 +524,17 @@ public partial interface IDictionary /// Task>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// + /// Get base64url dictionary value {"0": "a string that gets encoded + /// with base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// /// Get dictionary of complex type null value /// /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs index 4c9302911da2f..e1823d0463b87 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs @@ -177,6 +177,6 @@ public partial interface IStringModel /// /// The cancellation token. /// - Task> GetNullBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + Task> GetNullBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs index 0370d2fd1d00b..c55de67b0531c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs @@ -1456,7 +1456,7 @@ public StringModel(AutoRestSwaggerBATService client) /// /// A response object containing the response body and response headers. /// - public async Task> GetNullBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetNullBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; @@ -1466,7 +1466,7 @@ public StringModel(AutoRestSwaggerBATService client) _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary tracingParameters = new Dictionary(); tracingParameters.Add("cancellationToken", cancellationToken); - ServiceClientTracing.Enter(_invocationId, this, "GetNullBase64Encoded", tracingParameters); + ServiceClientTracing.Enter(_invocationId, this, "GetNullBase64UrlEncoded", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs index c026f184f6b25..7e028f2034390 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs @@ -392,9 +392,9 @@ public static void PutBase64UrlEncoded(this IStringModel operations, byte[] stri /// /// The operations group for this extension method. /// - public static byte[] GetNullBase64Encoded(this IStringModel operations) + public static byte[] GetNullBase64UrlEncoded(this IStringModel operations) { - return Task.Factory.StartNew(s => ((IStringModel)s).GetNullBase64EncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + return Task.Factory.StartNew(s => ((IStringModel)s).GetNullBase64UrlEncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// @@ -406,9 +406,9 @@ public static byte[] GetNullBase64Encoded(this IStringModel operations) /// /// The cancellation token. /// - public static async Task GetNullBase64EncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) + public static async Task GetNullBase64UrlEncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) { - using (var _result = await operations.GetNullBase64EncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + using (var _result = await operations.GetNullBase64UrlEncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index e77c80709f313..c82f6f4d90dc9 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -200,6 +200,8 @@ var coverage = { "getStringBase64UrlEncoded": 1, "putStringBase64UrlEncoded": 1, "getStringNullBase64UrlEncoding": 1, + "getArrayBase64Url": 1, + "getDictionaryBase64Url": 1, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, diff --git a/AutoRest/TestServer/server/routes/array.js b/AutoRest/TestServer/server/routes/array.js index ca02fa94ecd6e..96bfc6217b924 100644 --- a/AutoRest/TestServer/server/routes/array.js +++ b/AutoRest/TestServer/server/routes/array.js @@ -177,8 +177,15 @@ var array = function (coverage) { } else { res.status(400).send('Request scenario for byte primitive type must contain valid or invalidnull'); } + } else if (req.params.type == 'base64url') { + if (req.params.scenario === 'valid') { + coverage['getArrayBase64Url']++; + res.status(200).end('[\"YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw\", \"dGVzdCBzdHJpbmc\", \"TG9yZW0gaXBzdW0\"]'); + } else { + res.status(400).send('Request scenario for base64url type must contain valid'); + } } else { - res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte'); + res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte or base64url'); } }); diff --git a/AutoRest/TestServer/server/routes/dictionary.js b/AutoRest/TestServer/server/routes/dictionary.js index f9b9a50635021..53a47c79d6fad 100644 --- a/AutoRest/TestServer/server/routes/dictionary.js +++ b/AutoRest/TestServer/server/routes/dictionary.js @@ -176,8 +176,15 @@ var dictionary = function(coverage) { } else { res.status(400).send('Request scenario for byte primitive type must contain valid or invalidnull'); } + } else if (req.params.type == 'base64url') { + if (req.params.scenario === 'valid') { + coverage['getDictionaryBase64Url']++; + res.status(200).end('{"0": "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw", "1": "dGVzdCBzdHJpbmc", "2": "TG9yZW0gaXBzdW0"}'); + } else { + res.status(400).send('Request scenario for base64url type must contain valid'); + } } else { - res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte'); + res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte or base64url'); } }); diff --git a/AutoRest/TestServer/swagger/body-array.json b/AutoRest/TestServer/swagger/body-array.json index fb015f5496264..c200959da3d6b 100644 --- a/AutoRest/TestServer/swagger/body-array.json +++ b/AutoRest/TestServer/swagger/body-array.json @@ -901,7 +901,7 @@ } } } - }, + } }, "/array/prim/date/valid": { "get": { @@ -1348,6 +1348,34 @@ } } }, + "/array/prim/base64url/valid": { + "get": { + "operationId": "array_getBase64Url", + "description": "Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded", + "tags": [ + "Array Operations" + ], + "responses": { + "200": { + "description": "Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded", + "schema": { + "description": "Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded", + "type": "array", + "items": { + "type": "string", + "format": "base64url" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/array/complex/null": { "get": { "operationId": "array_getComplexNull", diff --git a/AutoRest/TestServer/swagger/body-dictionary.json b/AutoRest/TestServer/swagger/body-dictionary.json index e7a43e1755eef..b1065fc120df1 100644 --- a/AutoRest/TestServer/swagger/body-dictionary.json +++ b/AutoRest/TestServer/swagger/body-dictionary.json @@ -1325,6 +1325,34 @@ } } }, + "/dictionary/prim/base64url/valid": { + "get": { + "operationId": "dictionary_getBase64Url", + "description": "Get base64url dictionary value {\"0\": \"a string that gets encoded with base64url\", \"1\": \"test string\", \"2\": \"Lorem ipsum\"}", + "tags": [ + "Dictionary operations" + ], + "responses": { + "200": { + "description": "The base64url dictionary value {\"0\": \"a string that gets encoded with base64url\", \"1\": \"test string\", \"2\": \"Lorem ipsum\"}", + "schema": { + "description": "The base64url dictionary value {\"0\": \"a string that gets encoded with base64url\", \"1\": \"test string\", \"2\": \"Lorem ipsum\"}", + "type": "object", + "additionalProperties": { + "type": "string", + "format": "base64url" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/dictionary/complex/null": { "get": { "operationId": "dictionary_getComplexNull", diff --git a/AutoRest/TestServer/swagger/body-string.json b/AutoRest/TestServer/swagger/body-string.json index 2d6ce61e39243..8f0afaebf0074 100644 --- a/AutoRest/TestServer/swagger/body-string.json +++ b/AutoRest/TestServer/swagger/body-string.json @@ -380,7 +380,7 @@ }, "/string/nullBase64UrlEncoding": { "get": { - "operationId": "string_getNullBase64Encoded", + "operationId": "string_getNullBase64UrlEncoded", "description": "Get null value that is expected to be base64url encoded", "tags": [ "String Operations" From b48d9060cb8c5f32dcb5e0fa77b31d1084317aff Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 16:48:24 -0700 Subject: [PATCH 25/99] Let JavaParameter handle invoke --- .../AutoRest.Generator.Azure.Java.csproj | 1 + .../Java/Azure.Java/AzureJavaCodeNamer.cs | 64 +++----------- .../AzureMethodTemplateModel.cs | 11 +-- .../Types/AzureJavaCompositeType.cs | 59 +++++++++++++ .../Java/Java/ClientModelExtensions.cs | 77 ++--------------- .../Generators/Java/Java/JavaCodeNamer.cs | 61 +------------ .../TemplateModels/MethodTemplateModel.cs | 66 +++----------- .../Java/Java/Templates/MethodTemplate.cshtml | 8 +- .../Generators/Java/Java/Types/IJavaType.cs | 4 + .../Java/Java/Types/JavaCompositeType.cs | 65 ++++++++++++-- .../Java/Java/Types/JavaDictionaryType.cs | 16 ++++ .../Java/Java/Types/JavaEnumType.cs | 19 +++- .../Java/Java/Types/JavaParameter.cs | 86 ++++++++++++++++--- .../Java/Java/Types/JavaPrimaryType.cs | 4 +- .../Java/Java/Types/JavaSequenceType.cs | 21 +++++ 15 files changed, 292 insertions(+), 270 deletions(-) create mode 100644 AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs diff --git a/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj b/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj index cdd38079878f5..2e000f6631f02 100644 --- a/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj +++ b/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj @@ -66,6 +66,7 @@ AzureServiceClientRetrofitTemplate.cshtml + diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs index 9c95127a1fda1..ae02381cbb9f3 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs @@ -66,7 +66,7 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict throw new ArgumentNullException("serviceClient"); } - var convertedTypes = new Dictionary(); + var convertedTypes = new Dictionary(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { @@ -81,76 +81,40 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict method.Extensions[AzureExtensions.PageableExtension] = null; } - foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray()) + foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is JavaCompositeType).Select(s => s.Key).ToArray()) { - var compositType = (CompositeType)method.Responses[responseStatus].Body; - var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; + var compositType = (JavaCompositeType)method.Responses[responseStatus].Body; + var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is JavaSequenceType) as JavaSequenceType; // if the type is a wrapper over page-able response if (sequenceType != null) { - IType pagedResult; - pagedResult = new SequenceType + IJavaType pagedResult; + pagedResult = new JavaSequenceType { ElementType = sequenceType.ElementType, NameFormat = "List<{0}>" }; - convertedTypes[method.Responses[responseStatus].Body] = pagedResult; + convertedTypes[(IJavaType)method.Responses[responseStatus].Body] = pagedResult; method.Responses[responseStatus] = new Response(pagedResult, method.Responses[responseStatus].Headers); } } - if (convertedTypes.ContainsKey(method.ReturnType.Body)) + if (convertedTypes.ContainsKey((IJavaType) method.ReturnType.Body)) { - method.ReturnType = new Response(convertedTypes[method.ReturnType.Body], method.ReturnType.Headers); + method.ReturnType = new Response(convertedTypes[(IJavaType)method.ReturnType.Body], method.ReturnType.Headers); } } - Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet(convertedTypes.Keys.Cast().Select(t => t.Name))); + Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet(convertedTypes.Keys.Cast().Select(t => t.Name))); } - #endregion - - public override List ImportType(IType type, string ns) + protected override IType NormalizeCompositeType(CompositeType compositeType) { - List imports = new List(); - var compositeType = type as CompositeType; - if (compositeType != null && ns != null) - { - if (type.Name.Contains('<')) - { - imports.AddRange(compositeType.ParseGenericType().SelectMany(t => ImportType(t, ns))); - } - else if (compositeType.Extensions.ContainsKey(ExternalExtension) && - (bool)compositeType.Extensions[ExternalExtension]) - { - imports.Add(string.Join( - ".", - "com.microsoft.rest", - type.Name)); - } - else if (compositeType.IsResource()) - { - imports.Add(string.Join( - ".", - "com.microsoft.azure", - type.Name)); - } - else - { - imports.Add(string.Join( - ".", - ns.ToLower(CultureInfo.InvariantCulture), - "models", - type.Name)); - } - } - else - { - imports.AddRange(base.ImportType(type, ns)); - } - return imports; + return new AzureJavaCompositeType((JavaCompositeType) base.NormalizeCompositeType(compositeType)); } + + #endregion } } \ No newline at end of file diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index d9f7d48880c35..7138b3125b854 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -112,14 +112,7 @@ public override string MethodParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant)) { - if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarations.Add("final byte[] " + parameter.Name); - } - else - { - declarations.Add("final " + parameter.Type.ParameterType().Name + " " + parameter.Name); - } + declarations.Add("final " + parameter.JavaType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -138,7 +131,7 @@ public override string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add("final " + parameter.Type.ParameterType().Name + " " + parameter.Name); + declarations.Add("final " + parameter.JavaType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); diff --git a/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs b/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs new file mode 100644 index 0000000000000..3235473d46599 --- /dev/null +++ b/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs @@ -0,0 +1,59 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using Microsoft.Rest.Generator.Azure; + +namespace Microsoft.Rest.Generator.Java +{ + public class AzureJavaCompositeType : JavaCompositeType + { + protected string _azureRuntimePackage = "com.microsoft.azure"; + + public AzureJavaCompositeType(JavaCompositeType javaCompositeType) + : this(javaCompositeType.Package.Replace(".models", "")) + { + this.LoadFrom(javaCompositeType); + } + + public AzureJavaCompositeType(CompositeType compositeType, string package) + : this(package) + { + this.LoadFrom(compositeType); + } + + public AzureJavaCompositeType(string package) + : base(package) + { + this._package = package; + } + + public override string Package + { + get + { + if (this.IsResource) { + return _azureRuntimePackage; + } + else + { + return base.Package; + } + } + } + + public bool IsResource + { + get + { + return (Name == "Resource" || Name == "SubResource") && + Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) && + (bool)Extensions[AzureExtensions.AzureResourceExtension]; + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs index 21f6a8a9c9b9e..826d22e0c0bec 100644 --- a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs +++ b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs @@ -124,19 +124,6 @@ public static void AddRange(this HashSet hashSet, IEnumerable range) } } - public static IType ParameterType(this IType type) - { - PrimaryType primaryType = type as PrimaryType; - if (primaryType.IsPrimaryType(KnownPrimaryType.Stream)) - { - return JavaCodeNamer.NormalizePrimaryType(new PrimaryType(KnownPrimaryType.ByteArray)); - } - else - { - return type.UserHandledType(); - } - } - public static IType UserHandledType(this IType type) { PrimaryType primaryType = type as PrimaryType; @@ -150,6 +137,11 @@ public static IType UserHandledType(this IType type) } } + /// + /// A null friendly wrapper around type imports. + /// + /// an instance of IJavaType + /// a list of imports to append public static IEnumerable ImportFrom(this IType type) { if (type == null) @@ -159,38 +151,6 @@ public static IEnumerable ImportFrom(this IType type) return ((IJavaType) type).Imports; } - public static List ImportFrom(this Parameter parameter) - { - List imports = new List(); - if (parameter == null) - { - return imports; - } - var type = parameter.Type; - - SequenceType sequenceType = type as SequenceType; - if (type.IsPrimaryType(KnownPrimaryType.Stream)) - { - imports.Add("okhttp3.RequestBody"); - imports.Add("okhttp3.MediaType"); - } - if (parameter.Location != ParameterLocation.Body - && parameter.Location != ParameterLocation.None) - { - if (type.IsPrimaryType(KnownPrimaryType.ByteArray) || - type.Name == "ByteArray") - { - imports.Add("org.apache.commons.codec.binary.Base64"); - } - if (sequenceType != null) - { - imports.Add("com.microsoft.rest.serializer.CollectionFormat"); - } - } - - return imports; - } - public static string ImportFrom(this HttpMethod httpMethod) { string package = "retrofit2.http."; @@ -203,32 +163,5 @@ public static string ImportFrom(this HttpMethod httpMethod) return package + httpMethod.ToString().ToUpper(CultureInfo.InvariantCulture); } } - - public static string ImportFrom(this ParameterLocation parameterLocation) - { - if (parameterLocation == ParameterLocation.FormData) - { - return "retrofit2.http.Part"; - } - else if (parameterLocation != ParameterLocation.None) - { - return "retrofit2.http." + parameterLocation.ToString(); - } - else - { - return null; - } - } - - public static IEnumerable ParseGenericType(this CompositeType type) - { - string name = type.Name; - string[] types = type.Name.Split(new String[]{"<", ">", ",", ", "}, StringSplitOptions.RemoveEmptyEntries); - foreach (var innerType in types.Where(t => !string.IsNullOrWhiteSpace(t))) { - if (!JavaCodeNamer.PrimaryTypes.Contains(innerType.Trim())) { - yield return new CompositeType() { Name = innerType.Trim() }; - } - } - } } } diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index 9e49475170752..df014255d5b91 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -306,7 +306,7 @@ private IType NormalizeEnumType(EnumType enumType) return new JavaEnumType(enumType, _package); } - private IType NormalizeCompositeType(CompositeType compositeType) + protected virtual IType NormalizeCompositeType(CompositeType compositeType) { compositeType.Name = GetTypeName(compositeType.Name); @@ -436,65 +436,6 @@ public static IEnumerable ImportPrimaryType(PrimaryType primaryType) } } - public virtual List ImportType(IType type, string ns) - { - List imports = new List(); - var sequenceType = type as SequenceType; - var dictionaryType = type as DictionaryType; - var primaryType = type as PrimaryType; - var compositeType = type as CompositeType; - if (sequenceType != null) - { - imports.Add("java.util.List"); - imports.AddRange(ImportType(sequenceType.ElementType, ns)); - } - else if (dictionaryType != null) - { - imports.Add("java.util.Map"); - imports.AddRange(ImportType(dictionaryType.ValueType, ns)); - } - else if (compositeType != null && ns != null) - { - if (type.Name.Contains('<')) - { - imports.AddRange(compositeType.ParseGenericType().SelectMany(t => ImportType(t, ns))); - } - else if (compositeType.Extensions.ContainsKey(ExternalExtension) && - (bool)compositeType.Extensions[ExternalExtension]) - { - imports.Add(string.Join( - ".", - "com.microsoft.rest", - type.Name)); - } - else - { - imports.Add(string.Join( - ".", - ns.ToLower(CultureInfo.InvariantCulture), - "models", - type.Name)); - } - } - else if (type is EnumType && ns != null) - { - imports.Add(string.Join( - ".", - ns.ToLower(CultureInfo.InvariantCulture), - "models", - type.Name)); - } - else if (primaryType != null) - { - var importedFrom = JavaCodeNamer.ImportPrimaryType(primaryType); - if (importedFrom != null) - { - imports.AddRange(importedFrom); - } - } - return imports; - } - public static string GetJavaException(string exception, ServiceClient serviceClient) { switch (exception) { diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 70ef866907901..aedaddd87baf2 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -21,9 +21,9 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) this.LoadFrom(source); JavaParameters = new List(); JavaLogicalParameters = new List(); - source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p))); - source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p))); - source.LogicalParameters.ForEach(p => JavaLogicalParameters.Add(new JavaParameter(p))); + source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p, this))); + source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p, this))); + source.LogicalParameters.ForEach(p => JavaLogicalParameters.Add(new JavaParameter(p, this))); ServiceClient = serviceClient; if (source.Group != null) { @@ -145,14 +145,7 @@ public virtual string MethodParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant)) { - if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarations.Add("byte[] " + parameter.Name); - } - else - { - declarations.Add(parameter.Type.ParameterType().Name + " " + parameter.Name); - } + declarations.Add(parameter.JavaType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -167,7 +160,7 @@ public virtual string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add(parameter.Type.ParameterType().Name + " " + parameter.Name); + declarations.Add(parameter.JavaType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -197,25 +190,7 @@ public string MethodParameterApiInvocation List declarations = new List(); foreach (var parameter in OrderedRetrofitParameters) { - if ((parameter.Location != ParameterLocation.Body) - && parameter.Type.NeedsSpecialSerialization()) - { - declarations.Add(parameter.ToString(parameter.Name, ClientReference)); - } - else if (parameter.Type.UserHandledType() != parameter.Type) - { - declarations.Add(string.Format(CultureInfo.InvariantCulture, "new {0}({1})", parameter.Type.Name, parameter.Name)); - } - else if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarations.Add(string.Format(CultureInfo.InvariantCulture, - "RequestBody.create(MediaType.parse(\"{0}\"), {1})", - RequestContentType, parameter.Name)); - } - else - { - declarations.Add(parameter.Name); - } + declarations.Add(parameter.Invoke(parameter.Name, ClientReference)); } var declaration = string.Join(", ", declarations); @@ -274,7 +249,7 @@ public virtual string BuildInputMappings() if (conditionalAssignment) { builder.AppendLine("{0} {1} = null;", - JavaCodeNamer.WrapPrimitiveType(transformation.OutputParameter.Type.ParameterType()).Name, + ((IJavaType) transformation.OutputParameter.Type).ParameterVariant, transformation.OutputParameter.Name); builder.AppendLine("if ({0}) {{", nullCheck).Indent(); } @@ -283,7 +258,7 @@ public virtual string BuildInputMappings() transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0}{1} = new {2}();", - !conditionalAssignment ? transformation.OutputParameter.Type.ParameterType().Name + " " : "", + !conditionalAssignment ? ((IJavaType) transformation.OutputParameter.Type).ParameterVariant + " " : "", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } @@ -292,7 +267,7 @@ public virtual string BuildInputMappings() { builder.AppendLine("{0}{1}{2};", !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? - transformation.OutputParameter.Type.ParameterType().Name + " " : "", + ((IJavaType) transformation.OutputParameter.Type).ParameterVariant + " " : "", transformation.OutputParameter.Name, GetMapping(mapping)); } @@ -788,21 +763,7 @@ public virtual List ImplImports imports.Add("com.microsoft.rest." + OperationResponseType); imports.Add(RuntimeBasePackage + "." + ResponseBuilder); imports.Add("com.microsoft.rest.ServiceCallback"); - //// API parameters - //this.RetrofitParameters - // .Where(p => p.Location == ParameterLocation.Body - // || !p.Type.NeedsSpecialSerialization()) - // .ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); - //// parameter locations - //this.RetrofitParameters.ForEach(p => - //{ - // string locationImport = p.Location.ImportFrom(); - // if (!string.IsNullOrEmpty(locationImport)) - // { - // imports.Add(p.Location.ImportFrom()); - // } - //}); - this.RetrofitParameters.ForEach(p => imports.AddRange(p.ImplImports)); + this.RetrofitParameters.ForEach(p => imports.AddRange(p.RetrofitImports)); // Http verb annotations imports.Add(this.HttpMethod.ImportFrom()); // response type conversion @@ -824,12 +785,9 @@ public virtual List ImplImports { imports.Add("com.microsoft.rest.ServiceResponseCallback"); } - // parameter types - this.LocalParameters.Concat(this.LogicalParameters) - .ForEach(p => imports.AddRange(p.Type.ImportFrom())); // parameter utils - this.LocalParameters.Concat(this.LogicalParameters) - .ForEach(p => imports.AddRange(p.ImportFrom())); + this.LocalParameters.Concat(this.JavaLogicalParameters) + .ForEach(p => imports.AddRange(p.ImplImports)); // return type imports.AddRange(this.ReturnType.Body.ImportFrom()); if (ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index de5ccb0673faa..1d72e94b02212 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -49,11 +49,11 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi { if (!parameter.IsRequired) { -@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = null; +@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = null; } if (parameter.IsConstant) { -@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } @@ -109,11 +109,11 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW { if (!parameter.IsRequired) { -@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = null; +@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = null; } if (parameter.IsConstant) { -@: final @(parameter.Type.ParameterType().Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } @Model.BuildInputMappings() diff --git a/AutoRest/Generators/Java/Java/Types/IJavaType.cs b/AutoRest/Generators/Java/Java/Types/IJavaType.cs index 5efcba17751d9..16d32abfafbff 100644 --- a/AutoRest/Generators/Java/Java/Types/IJavaType.cs +++ b/AutoRest/Generators/Java/Java/Types/IJavaType.cs @@ -13,6 +13,10 @@ public interface IJavaType : IType { string DefaultValue { get; } + string ParameterVariant { get; } + + string ResponseVariant { get; } + IEnumerable Imports { get; } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs index 9f9acd05651d1..cff5e57c2f90d 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs @@ -6,12 +6,15 @@ using System.Threading.Tasks; using Microsoft.Rest.Generator.Java.TemplateModels; using Microsoft.Rest.Generator.Utilities; +using System.Globalization; namespace Microsoft.Rest.Generator.Java { public class JavaCompositeType : CompositeType, IJavaType { - private string _package; + protected string _package; + public const string ExternalExtension = "x-ms-external"; + protected string _runtimePackage = "com.microsoft.rest"; public JavaCompositeType(CompositeType compositeType, string package) : this(package) @@ -22,14 +25,42 @@ public JavaCompositeType(CompositeType compositeType, string package) public JavaCompositeType(string package) : base() { - this._package = package; + this._package = package.ToLower(CultureInfo.InvariantCulture); } - public PrimaryType ParameterType { get; private set; } + public virtual string Package + { + get + { + if (Extensions.ContainsKey(ExternalExtension) && + (bool)Extensions[ExternalExtension]) { + return _runtimePackage; + } + else + { + return string.Join( + ".", + _package, + "models"); + } + } + } - public PrimaryType InternalType { get; private set; } + public string ParameterVariant + { + get + { + return Name; + } + } - public PrimaryType ResponseType { get; private set; } + public string ResponseVariant + { + get + { + return Name; + } + } public string DefaultValue { @@ -43,7 +74,29 @@ public IEnumerable Imports { get { - yield return string.Join(".", _package, "models", Name); + var imports = new List(); + if (Name.Contains('<')) + { + imports.AddRange(ParseGenericType().SelectMany(t => t.Imports)); + } + else + { + imports.Add(string.Join(".", Package, Name)); + } + return imports; + } + } + + private IEnumerable ParseGenericType() + { + string name = Name; + string[] types = Name.Split(new String[] { "<", ">", ",", ", " }, StringSplitOptions.RemoveEmptyEntries); + foreach (var innerType in types.Where(t => !string.IsNullOrWhiteSpace(t))) + { + if (!JavaCodeNamer.PrimaryTypes.Contains(innerType.Trim())) + { + yield return new JavaCompositeType(_package) { Name = innerType.Trim() }; + } } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs index 2469f9b1fb74e..80dc63b0155ae 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs @@ -17,6 +17,22 @@ public JavaDictionaryType(DictionaryType dictionaryType) this.LoadFrom(dictionaryType); } + public string ParameterVariant + { + get + { + return Name; + } + } + + public string ResponseVariant + { + get + { + return Name; + } + } + public string DefaultValue { get diff --git a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs index 7aee5b56eae8b..a36d8d7dc4c1d 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Microsoft.Rest.Generator.Java.TemplateModels; using Microsoft.Rest.Generator.Utilities; +using System.Globalization; namespace Microsoft.Rest.Generator.Java { @@ -17,7 +18,23 @@ public JavaEnumType(EnumType enumType, string package) : base() { this.LoadFrom(enumType); - this._package = package; + this._package = package.ToLower(CultureInfo.InvariantCulture); + } + + public string ParameterVariant + { + get + { + return Name; + } + } + + public string ResponseVariant + { + get + { + return Name; + } } public string DefaultValue diff --git a/AutoRest/Generators/Java/Java/Types/JavaParameter.cs b/AutoRest/Generators/Java/Java/Types/JavaParameter.cs index 1fc5d74c09362..f14515f0f8094 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaParameter.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaParameter.cs @@ -6,30 +6,77 @@ using System.Threading.Tasks; using Microsoft.Rest.Generator.Java.TemplateModels; using Microsoft.Rest.Generator.Utilities; +using System.Globalization; namespace Microsoft.Rest.Generator.Java { public class JavaParameter : Parameter { - public JavaParameter(Parameter parameter) + private MethodTemplateModel _method; + + public JavaParameter(Parameter parameter, MethodTemplateModel method) : base() { this.LoadFrom(parameter); + this._method = method; } - //public string TypeString - //{ - // get - // { - // return ((IJavaType)Type).ParameterType; - // } - //} + public IJavaType JavaType + { + get + { + return (IJavaType) Type; + } + } + + public string Invoke(string reference, string clientReference) + { + if (JavaType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + return string.Format(CultureInfo.InvariantCulture, "new DateTimeRfc1123({0})", reference); + } + else if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData) + { + var primary = JavaType as JavaPrimaryType; + var sequence = JavaType as JavaSequenceType; + if (primary != null && primary.Name != "LocalDate" && primary.Name != "DateTime") + { + if (primary.Type == KnownPrimaryType.ByteArray) + { + return "Base64.encodeBase64String(" + reference + ")"; + } + else + { + return reference; + } + } + else if (sequence != null) + { + return clientReference + ".getMapperAdapter().serializeList(" + reference + + ", CollectionFormat." + CollectionFormat.ToString().ToUpper(CultureInfo.InvariantCulture) + ")"; + } + else + { + return clientReference + ".getMapperAdapter().serializeRaw(" + reference + ")"; + } + } + else if (JavaType.IsPrimaryType(KnownPrimaryType.Stream)) + { + return string.Format(CultureInfo.InvariantCulture, + "RequestBody.create(MediaType.parse(\"{0}\"), {1})", + _method.RequestContentType, reference); + } + else + { + return reference; + } + } public IEnumerable InterfaceImports { get { - return ((IJavaType) Type).Imports; + return JavaType.Imports; } } @@ -37,8 +84,12 @@ public IEnumerable RetrofitImports { get { + var imports = new List(); // type imports - var imports = new List(((IJavaType)Type).Imports); + if (this.Location == ParameterLocation.Body || !NeedsSpecialSerialization(Type)) + { + imports.AddRange(JavaType.Imports); + } if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { imports.Add("com.microsoft.rest.DateTimeRfc1123"); @@ -53,8 +104,8 @@ public IEnumerable ImplImports { get { - var imports = RetrofitImports.ToList(); - if (Location == ParameterLocation.Header) + var imports = new List(JavaType.Imports); + if (Location != ParameterLocation.Body) { if (this.Type.IsPrimaryType(KnownPrimaryType.ByteArray)) { @@ -65,6 +116,10 @@ public IEnumerable ImplImports imports.Add("com.microsoft.rest.serializer.CollectionFormat"); } } + if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + imports.Add("com.microsoft.rest.DateTimeRfc1123"); + } if (Type.IsPrimaryType(KnownPrimaryType.Stream) && Location == ParameterLocation.Body) { imports.Add("okhttp3.RequestBody"); @@ -89,5 +144,12 @@ private string LocationImport(ParameterLocation parameterLocation) return null; } } + + private bool NeedsSpecialSerialization(IType type) + { + var known = type as PrimaryType; + return (known != null && (known.Name == "LocalDate" || known.Name == "DateTime" || known.Type == KnownPrimaryType.ByteArray)) || + type is EnumType || type is CompositeType || type is SequenceType || type is DictionaryType; + } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs index 0fa0bfb7d79af..9a3eed550e672 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs @@ -56,7 +56,7 @@ public string DefaultValue } } - public string ParameterType + public string ParameterVariant { get { @@ -75,7 +75,7 @@ public string ParameterType } } - public string ResponseType + public string ResponseVariant { get { diff --git a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs index 8a8b7255e145e..e54cb600a46cc 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs @@ -17,6 +17,27 @@ public JavaSequenceType(SequenceType sequenceType) this.LoadFrom(sequenceType); } + public JavaSequenceType() + : base() + { + } + + public string ParameterVariant + { + get + { + return Name; + } + } + + public string ResponseVariant + { + get + { + return Name; + } + } + public string DefaultValue { get From ac318cf11aed1789d05a237e9400d46362fa721c Mon Sep 17 00:00:00 2001 From: Laurent Mazuel Date: Wed, 23 Mar 2016 17:09:12 -0700 Subject: [PATCH 26/99] Allows to parse integer as enum valid values --- ClientRuntimes/Python/msrest/msrest/serialization.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index 2fe97beaf7728..f68ca6adb6980 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -850,6 +850,12 @@ def deserialize_enum(self, data, enum_obj): :rtype: Enum :raises: DeserializationError if string is not valid enum value. """ + if isinstance(data, int): + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) try: return enum_obj(str(data)) except ValueError: From 671703c2a1c21b5535d15e9cda3999f9fc4d26ed Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 18:59:58 -0700 Subject: [PATCH 27/99] Add JavaResponse --- .../AzureMethodTemplateModel.cs | 16 +- .../HeaderResponseDatetimeRfc1123Headers.java | 3 + .../Java/Java/AutoRest.Generator.Java.csproj | 1 + .../Java/Java/ClientModelExtensions.cs | 47 +---- .../Generators/Java/Java/JavaCodeNamer.cs | 53 +----- .../TemplateModels/MethodTemplateModel.cs | 114 ++++-------- .../Java/TemplateModels/ModelTemplateModel.cs | 2 +- .../Java/Java/Templates/MethodTemplate.cshtml | 8 +- .../Java/Java/Templates/ModelTemplate.cshtml | 12 +- .../Generators/Java/Java/Types/IJavaType.cs | 2 + .../Java/Java/Types/JavaCompositeType.cs | 5 + .../Java/Java/Types/JavaDictionaryType.cs | 5 + .../Java/Java/Types/JavaEnumType.cs | 5 + .../Java/Java/Types/JavaParameter.cs | 38 +++- .../Java/Java/Types/JavaPrimaryType.cs | 27 ++- .../Java/Java/Types/JavaResponse.cs | 170 ++++++++++++++++++ .../Java/Java/Types/JavaSequenceType.cs | 5 + 17 files changed, 311 insertions(+), 202 deletions(-) create mode 100644 AutoRest/Generators/Java/Java/Types/JavaResponse.cs diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 7138b3125b854..72e70f6a5b0bd 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -112,7 +112,7 @@ public override string MethodParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant)) { - declarations.Add("final " + parameter.JavaType.ParameterVariant + " " + parameter.Name); + declarations.Add("final " + parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -131,7 +131,7 @@ public override string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add("final " + parameter.JavaType.ParameterVariant + " " + parameter.Name); + declarations.Add("final " + parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -581,7 +581,7 @@ public override List InterfaceImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.PagedList"); imports.Remove("java.util.List"); - imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportFrom()); + imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } return imports; } @@ -599,11 +599,11 @@ public override List ImplImports imports.Remove("com.microsoft.azure.AzureServiceResponseBuilder"); imports.Add("retrofit2.Callback"); this.Responses.Select(r => r.Value.Body).Concat(new IType[]{ DefaultResponse.Body }) - .SelectMany(t => t.ImportFrom()) - .Where(i => !this.Parameters.Any(p => p.Type.ImportFrom().Contains(i))) + .SelectMany(t => t.ImportSafe()) + .Where(i => !this.Parameters.Any(p => p.Type.ImportSafe().Contains(i))) .ForEach(i => imports.Remove(i)); // return type may have been removed as a side effect - imports.AddRange(this.ReturnType.Body.ImportFrom()); + imports.AddRange(this.ReturnType.Body.ImportSafe()); } if (this.IsPagingOperation || this.IsPagingNextOperation) { @@ -611,7 +611,7 @@ public override List ImplImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.Page"); imports.Add("com.microsoft.azure.PagedList"); - imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportFrom()); + imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } if (this.IsPagingNextOperation) { @@ -620,7 +620,7 @@ public override List ImplImports } if (this.IsPagingNonPollingOperation) { - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom()); + imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportSafe()); } return imports; } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java index 22c7e760a3ee1..f08b2dc6a2967 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java @@ -28,6 +28,9 @@ public class HeaderResponseDatetimeRfc1123Headers { * @return the value value */ public DateTime getValue() { + if (this.value == null) { + return null; + } return this.value.getDateTime(); } diff --git a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj index dd91747fe86d9..58452651f9c53 100644 --- a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj +++ b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj @@ -32,6 +32,7 @@ Resources.resx + diff --git a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs index 826d22e0c0bec..42b78c33a616f 100644 --- a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs +++ b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs @@ -15,51 +15,6 @@ public static class ClientModelExtensions { public const string ExternalExtension = "x-ms-external"; - public static bool NeedsSpecialSerialization(this IType type) - { - var known = type as PrimaryType; - return (known != null && (known.Name == "LocalDate" || known.Name == "DateTime" || known.Type == KnownPrimaryType.ByteArray)) || - type is EnumType || type is CompositeType || type is SequenceType || type is DictionaryType; - } - - /// - /// Simple conversion of the type to string - /// - /// The parameter to convert - /// a reference to an instance of the type - /// a reference to the service client - /// - public static string ToString(this Parameter parameter, string reference, string clientReference) - { - if (parameter == null) - { - return null; - } - var type = parameter.Type; - var known = type as PrimaryType; - var sequence = type as SequenceType; - if (known != null && known.Name != "LocalDate" && known.Name != "DateTime") - { - if (known.Type == KnownPrimaryType.ByteArray) - { - return "Base64.encodeBase64String(" + reference + ")"; - } - else - { - return reference; - } - } - else if (sequence != null) - { - return clientReference + ".getMapperAdapter().serializeList(" + reference + - ", CollectionFormat." + parameter.CollectionFormat.ToString().ToUpper(CultureInfo.InvariantCulture) + ")"; - } - else - { - return clientReference + ".getMapperAdapter().serializeRaw(" + reference + ")"; - } - } - public static string Period(this string documentation) { if (string.IsNullOrEmpty(documentation)) @@ -142,7 +97,7 @@ public static IType UserHandledType(this IType type) /// /// an instance of IJavaType /// a list of imports to append - public static IEnumerable ImportFrom(this IType type) + public static IEnumerable ImportSafe(this IType type) { if (type == null) { diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index df014255d5b91..3fd8f9d5ff41a 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -244,6 +244,11 @@ protected override void NormalizeClientProperties(ServiceClient client) } } } + public override Response NormalizeTypeReference(Response typePair) + { + return new Response((IJavaType) NormalizeTypeReference(typePair.Body), + (IJavaType) NormalizeTypeReference(typePair.Headers)); + } public override IType NormalizeTypeDeclaration(IType type) { @@ -388,54 +393,6 @@ public static IType WrapPrimitiveType(IType type) } } - public static IEnumerable ImportPrimaryType(PrimaryType primaryType) - { - if (primaryType == null) - { - yield break; - } - - if (primaryType.Type == KnownPrimaryType.Date || - primaryType.Name == "LocalDate") - { - yield return "org.joda.time.LocalDate"; - } - else if (primaryType.Type == KnownPrimaryType.DateTime || - primaryType.Name == "DateTime") - { - yield return "org.joda.time.DateTime"; - } - else if (primaryType.Type == KnownPrimaryType.Decimal || - primaryType.Name == "Decimal") - { - yield return "java.math.BigDecimal"; - } - else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123 || - primaryType.Name == "DateTimeRfc1123") - { - yield return "com.microsoft.rest.DateTimeRfc1123"; - yield return "org.joda.time.DateTime"; - } - else if (primaryType.Type == KnownPrimaryType.Stream || - primaryType.Name == "InputStream") - { - yield return "java.io.InputStream"; - } - else if (primaryType.Type == KnownPrimaryType.TimeSpan || - primaryType.Name == "Period") - { - yield return "org.joda.time.Period"; - } - else if (primaryType.Type == KnownPrimaryType.Uuid || primaryType.Name == "Uuid") - { - yield return "java.util.UUID"; - } - else - { - yield break; - } - } - public static string GetJavaException(string exception, ServiceClient serviceClient) { switch (exception) { diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index aedaddd87baf2..1455980174532 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -9,12 +9,15 @@ using System.Globalization; using System.Text; using System; +using System.Net; namespace Microsoft.Rest.Generator.Java { public class MethodTemplateModel : Method { private JavaCodeNamer _namer; + private JavaResponse _javaReturnType; + private Dictionary _javaResponses; public MethodTemplateModel(Method source, ServiceClient serviceClient) { @@ -36,6 +39,9 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) ClientReference = "this"; } _namer = new JavaCodeNamer(serviceClient.Namespace); + _javaReturnType = new JavaResponse(ReturnType); + _javaResponses = new Dictionary(); + Responses.ForEach(r => _javaResponses.Add(r.Key, new JavaResponse(r.Value))); } protected virtual JavaCodeNamer Namer @@ -56,6 +62,22 @@ protected virtual JavaCodeNamer Namer public List JavaLogicalParameters { get; private set; } + public JavaResponse JavaReturnType + { + get + { + return _javaReturnType; + } + } + + public Dictionary JavaResponses + { + get + { + return _javaResponses; + } + } + public IEnumerable RetrofitParameters { get @@ -111,24 +133,7 @@ public virtual string MethodParameterApiDeclaration parameter.SerializedName)); } var declarativeName = parameter.ClientProperty != null ? parameter.ClientProperty.Name : parameter.Name; - if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarationBuilder.Append("RequestBody"); - } - else if ((parameter.Location != ParameterLocation.Body) - && parameter.Type.NeedsSpecialSerialization()) - { - declarationBuilder.Append("String"); - } - else - { - string typeString = parameter.Type.Name; - if (!parameter.IsRequired) - { - typeString = JavaCodeNamer.WrapPrimitiveType(parameter.Type).Name; - } - declarationBuilder.Append(typeString); - } + declarationBuilder.Append(parameter.WireType.Name); declarationBuilder.Append(" " + declarativeName); declarations.Add(declarationBuilder.ToString()); } @@ -145,7 +150,7 @@ public virtual string MethodParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant)) { - declarations.Add(parameter.JavaType.ParameterVariant + " " + parameter.Name); + declarations.Add(parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -160,7 +165,7 @@ public virtual string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add(parameter.JavaType.ParameterVariant + " " + parameter.Name); + declarations.Add(parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -198,43 +203,6 @@ public string MethodParameterApiInvocation } } - public string MethodParameterApiInvocationWithCallback - { - get - { - var parameters = MethodParameterApiInvocation; - if (!parameters.IsNullOrEmpty()) - { - parameters += ", "; - } - parameters += string.Format(CultureInfo.InvariantCulture, "new ServiceResponseCallback()"); - return parameters; - } - } - - public string LocalMethodParameterInvocation - { - get - { - List declarations = new List(); - foreach (var parameter in LocalParameters) - { - if ((parameter.Location != ParameterLocation.Body) - && parameter.Type.NeedsSpecialSerialization()) - { - declarations.Add(parameter.ToString(parameter.Name, ClientReference)); - } - else - { - declarations.Add(parameter.Name); - } - } - - var declaration = string.Join(", ", declarations); - return declaration; - } - } - /// /// Generates input mapping code block. /// @@ -521,7 +489,7 @@ public virtual string GenericReturnTypeString { if (ReturnType.Body != null) { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body.UserHandledType()).Name; + return ((IJavaType) ReturnType.Body).InstanceType().ResponseVariant; } return "Void"; } @@ -541,7 +509,7 @@ public virtual string DelegateReturnTypeString { if (ReturnType.Body != null) { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).Name; + return ((IJavaType) ReturnType.Body).InstanceType().Name; } return "Void"; } @@ -647,16 +615,14 @@ public virtual string ResponseGeneration { get { - var userType = ReturnType.Body.UserHandledType(); - if (ReturnType.Body != userType) + if (JavaReturnType.NeedsConversion) { - userType = JavaCodeNamer.WrapPrimitiveType(userType); IndentedStringBuilder builder= new IndentedStringBuilder(); builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());", DelegateReturnTypeString, this.Name.ToCamelCase()); - builder.AppendLine("{0} body = null;", userType.Name) + builder.AppendLine("{0} body = null;", JavaReturnType.BodyClientType) .AppendLine("if (response.getBody() != null) {") - .Indent().AppendLine("body = response.getBody().get{0}();", userType.Name) + .Indent().AppendLine("body = {0};", JavaReturnType.ConvertBodyToClientType("response.getBody()")) .Outdent().AppendLine("}"); return builder.ToString(); } @@ -668,7 +634,7 @@ public virtual string ReturnValue { get { - if (ReturnType.Body.UserHandledType() != ReturnType.Body) + if (JavaReturnType.NeedsConversion) { return "new ServiceResponse<" + this.GenericReturnTypeString + ">(body, response.getResponse())"; } @@ -680,15 +646,13 @@ public virtual string SuccessCallback { get { - var userType = ReturnType.Body.UserHandledType(); - if (ReturnType.Body != userType) + if (JavaReturnType.NeedsConversion) { - userType = JavaCodeNamer.WrapPrimitiveType(userType); IndentedStringBuilder builder = new IndentedStringBuilder(); builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", DelegateReturnTypeString, this.Name); - builder.AppendLine("{0} body = null;", userType.Name) + builder.AppendLine("{0} body = null;", JavaReturnType.BodyClientType) .AppendLine("if (result.getBody() != null) {") - .Indent().AppendLine("body = result.getBody().get{0}();", userType.Name) + .Indent().AppendLine("body = {0};", JavaReturnType.ConvertBodyToClientType("result.getBody()")) .Outdent().AppendLine("}"); builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", GenericReturnTypeString); return builder.ToString(); @@ -725,9 +689,9 @@ public virtual List InterfaceImports // parameter types this.JavaParameters.ForEach(p => imports.AddRange(p.InterfaceImports)); // return type - imports.AddRange(this.ReturnType.Body.ImportFrom()); + imports.AddRange(this.ReturnType.Body.ImportSafe()); // Header type - imports.AddRange(this.ReturnType.Headers.ImportFrom()); + imports.AddRange(this.ReturnType.Headers.ImportSafe()); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => { @@ -789,15 +753,15 @@ public virtual List ImplImports this.LocalParameters.Concat(this.JavaLogicalParameters) .ForEach(p => imports.AddRange(p.ImplImports)); // return type - imports.AddRange(this.ReturnType.Body.ImportFrom()); + imports.AddRange(this.ReturnType.Body.ImportSafe()); if (ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) { imports.Add("retrofit2.http.Streaming"); } // response type (can be different from return type) - this.Responses.ForEach(r => imports.AddRange(r.Value.Body.ImportFrom())); + this.Responses.ForEach(r => imports.AddRange(r.Value.Body.ImportSafe())); // Header type - imports.AddRange(this.ReturnType.Headers.ImportFrom()); + imports.AddRange(this.ReturnType.Headers.ImportSafe()); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => diff --git a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs index da6db86b9a92a..ce81e2b3efd3a 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs @@ -142,7 +142,7 @@ public virtual IEnumerable ImportList { HashSet classes = new HashSet(); foreach (var property in this.Properties) { - classes.AddRange(property.Type.ImportFrom() + classes.AddRange(property.Type.ImportSafe() .Where(c => !c.StartsWith( string.Join(".", ServiceClient.Namespace, "models"), StringComparison.OrdinalIgnoreCase))); diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index 1d72e94b02212..bfc98fb3dd409 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -49,11 +49,11 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi { if (!parameter.IsRequired) { -@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = null; +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = null; } if (parameter.IsConstant) { -@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } @@ -109,11 +109,11 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW { if (!parameter.IsRequired) { -@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = null; +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = null; } if (parameter.IsConstant) { -@: final @(parameter.JavaType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } @Model.BuildInputMappings() diff --git a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml index deb64fca76b2e..d1234e95e3b0f 100644 --- a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml @@ -1,5 +1,6 @@ @using System.Linq @using System.Collections.Generic +@using Microsoft.Rest.Generator.Java @using Microsoft.Rest.Generator.Utilities @using Microsoft.Rest.Generator.ClientModel @using Microsoft.Rest.Generator.Java.TemplateModels @@ -87,9 +88,12 @@ if (!jsonSetting.IsNullOrEmpty()) @: * @@return the @property.Name value @: */ @: public @property.Type.UserHandledType().Name get@(property.Name.ToPascalCase())() { -if (property.Type.UserHandledType() != property.Type) +if (property.Type.Name != ((IJavaType) property.Type).ResponseVariant) { -@: return this.@(property.Name).get@(property.Type.UserHandledType().Name)(); +@: if (this.@(property.Name) == null) { +@: return null; +@: } +@: return this.@(property.Name).get@(((IJavaType)property.Type).ResponseVariant)(); } else { @@ -104,8 +108,8 @@ if (!property.IsReadOnly) @: * @: * @@param @property.Name the @property.Name value to set @: */ -@: public void set@(property.Name.ToPascalCase())(@property.Type.UserHandledType().Name @property.Name) { -if (property.Type.UserHandledType() != property.Type) +@: public void set@(property.Name.ToPascalCase())(@(((IJavaType)property.Type).ResponseVariant) @property.Name) { +if (property.Type.Name != ((IJavaType)property.Type).ResponseVariant) { @: this.@(property.Name) = new @(property.Type.Name)(@property.Name); } diff --git a/AutoRest/Generators/Java/Java/Types/IJavaType.cs b/AutoRest/Generators/Java/Java/Types/IJavaType.cs index 16d32abfafbff..fda926a15f3e9 100644 --- a/AutoRest/Generators/Java/Java/Types/IJavaType.cs +++ b/AutoRest/Generators/Java/Java/Types/IJavaType.cs @@ -18,5 +18,7 @@ public interface IJavaType : IType string ResponseVariant { get; } IEnumerable Imports { get; } + + IJavaType InstanceType(); } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs index cff5e57c2f90d..c02c3866f22a3 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs @@ -87,6 +87,11 @@ public IEnumerable Imports } } + public IJavaType InstanceType() + { + return this; + } + private IEnumerable ParseGenericType() { string name = Name; diff --git a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs index 80dc63b0155ae..021314f752943 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs @@ -49,5 +49,10 @@ public IEnumerable Imports return imports.Concat(((IJavaType) this.ValueType).Imports); } } + + public IJavaType InstanceType() + { + return this; + } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs index a36d8d7dc4c1d..b24efa94b37a8 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs @@ -52,5 +52,10 @@ public IEnumerable Imports yield return string.Join(".", _package, "models", Name); } } + + public IJavaType InstanceType() + { + return this; + } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaParameter.cs b/AutoRest/Generators/Java/Java/Types/JavaParameter.cs index f14515f0f8094..2723fb3d918d8 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaParameter.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaParameter.cs @@ -12,7 +12,7 @@ namespace Microsoft.Rest.Generator.Java { public class JavaParameter : Parameter { - private MethodTemplateModel _method; + private MethodTemplateModel _method; public JavaParameter(Parameter parameter, MethodTemplateModel method) : base() @@ -21,7 +21,7 @@ public JavaParameter(Parameter parameter, MethodTemplateModel method) this._method = method; } - public IJavaType JavaType + public IJavaType ClientType { get { @@ -29,16 +29,36 @@ public IJavaType JavaType } } + public IJavaType WireType + { + get + { + if (Type.IsPrimaryType(KnownPrimaryType.Stream)) + { + return new JavaPrimaryType(KnownPrimaryType.Stream) { Name = "RequestBody" }; + } + else if ((Location != ParameterLocation.Body) + && NeedsSpecialSerialization(Type)) + { + return new JavaPrimaryType(KnownPrimaryType.String); + } + else + { + return ClientType; + } + } + } + public string Invoke(string reference, string clientReference) { - if (JavaType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + if (ClientType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { return string.Format(CultureInfo.InvariantCulture, "new DateTimeRfc1123({0})", reference); } else if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData) { - var primary = JavaType as JavaPrimaryType; - var sequence = JavaType as JavaSequenceType; + var primary = ClientType as JavaPrimaryType; + var sequence = ClientType as JavaSequenceType; if (primary != null && primary.Name != "LocalDate" && primary.Name != "DateTime") { if (primary.Type == KnownPrimaryType.ByteArray) @@ -60,7 +80,7 @@ public string Invoke(string reference, string clientReference) return clientReference + ".getMapperAdapter().serializeRaw(" + reference + ")"; } } - else if (JavaType.IsPrimaryType(KnownPrimaryType.Stream)) + else if (ClientType.IsPrimaryType(KnownPrimaryType.Stream)) { return string.Format(CultureInfo.InvariantCulture, "RequestBody.create(MediaType.parse(\"{0}\"), {1})", @@ -76,7 +96,7 @@ public IEnumerable InterfaceImports { get { - return JavaType.Imports; + return ClientType.Imports; } } @@ -88,7 +108,7 @@ public IEnumerable RetrofitImports // type imports if (this.Location == ParameterLocation.Body || !NeedsSpecialSerialization(Type)) { - imports.AddRange(JavaType.Imports); + imports.AddRange(ClientType.Imports); } if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { @@ -104,7 +124,7 @@ public IEnumerable ImplImports { get { - var imports = new List(JavaType.Imports); + var imports = new List(ClientType.Imports); if (Location != ParameterLocation.Body) { if (this.Type.IsPrimaryType(KnownPrimaryType.ByteArray)) diff --git a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs index 9a3eed550e672..e981aa11bab3b 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs @@ -44,7 +44,7 @@ public string DefaultValue { return "new Byte[]"; } - else if (this.Name[0] >= 'A' && this.Name[0] <= 'Z') + else if (this.IsInstanceType) // instance type { return "null"; @@ -98,26 +98,39 @@ public IEnumerable Imports } } - public JavaPrimaryType IntanceType() + private bool IsInstanceType { + get + { + return this.Name[0] >= 'A' && this.Name[0] <= 'Z'; + } + } + + public IJavaType InstanceType() + { + if (this.IsInstanceType) + { + return this; + } + JavaPrimaryType instanceType = new JavaPrimaryType(this); - if (Name == "boolean") + if (instanceType.Name == "boolean") { instanceType.Name = "Boolean"; } - else if (Name == "double") + else if (instanceType.Name == "double") { instanceType.Name = "Double"; } - else if (Name == "int") + else if (instanceType.Name == "int") { instanceType.Name = "Integer"; } - else if (Name == "long") + else if (instanceType.Name == "long") { instanceType.Name = "Long"; } - else if (Name == "void") + else if (instanceType.Name == "void") { instanceType.Name = "Void"; } diff --git a/AutoRest/Generators/Java/Java/Types/JavaResponse.cs b/AutoRest/Generators/Java/Java/Types/JavaResponse.cs new file mode 100644 index 0000000000000..75d6c0ca0c403 --- /dev/null +++ b/AutoRest/Generators/Java/Java/Types/JavaResponse.cs @@ -0,0 +1,170 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class JavaResponse + { + private Response _response; + + public JavaResponse(Response response) + { + this._response = response; + } + + public JavaResponse(IJavaType body, IJavaType headers) + : this(new Response(body, headers)) + { + } + + public IJavaType Body + { + get + { + if (_response == null) + { + return null; + } + return (IJavaType)_response.Body; + } + } + + public IJavaType Headers + { + get + { + if (_response == null) + { + return null; + } + return (IJavaType)_response.Headers; + } + } + + public bool NeedsConversion + { + get + { + return (Body != null && + Body.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + || + (Headers != null && + Headers.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)); + } + } + + public IJavaType BodyClientType + { + get + { + if (Body == null) + { + return null; + } + else if (Body.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + return new JavaPrimaryType(KnownPrimaryType.DateTime); + } + else + { + return BodyWireType; + } + } + } + + public IJavaType BodyWireType + { + get + { + if (Body == null) + { + return null; + } + return (IJavaType) Body; + } + } + + public IJavaType HeaderClientType + { + get + { + if (Headers == null) + { + return null; + } + else if (Headers.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + return new JavaPrimaryType(KnownPrimaryType.DateTime); + } + else + { + return HeaderWireType; + } + } + } + + public IJavaType HeaderWireType + { + get + { + if (Headers == null) + { + return null; + } + return (IJavaType)Headers; + } + } + + public string ConvertBodyToClientType(string reference) + { + return converToClientType(Body, reference); + } + + public string ConvertHeaderToClientType(string reference) + { + return converToClientType(Headers, reference); + } + + public IEnumerable InterfaceImports + { + get + { + return BodyClientType.ImportSafe().Concat(HeaderClientType.ImportSafe()); + } + } + + public IEnumerable ImplImports + { + get + { + var imports = new List(InterfaceImports); + imports.AddRange(BodyWireType.ImportSafe()); + imports.AddRange(HeaderWireType.ImportSafe()); + return imports; + } + } + + private string converToClientType(IType type, string reference) + { + if (type == null) + { + return reference; + } + else if (type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + return reference + ".getDateTime()"; + } + else + { + return reference; + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs index e54cb600a46cc..bd006810059aa 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs +++ b/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs @@ -54,5 +54,10 @@ public IEnumerable Imports return imports.Concat(((IJavaType) this.ElementType).Imports); } } + + public IJavaType InstanceType() + { + return this; + } } } From 406a7410d864cd00448b0305119e523eef615803 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 22:56:40 -0700 Subject: [PATCH 28/99] Some renamings and cleanups --- .../Java/Azure.Java/AzureJavaCodeNamer.cs | 22 ++-- .../AzureMethodTemplateModel.cs | 41 +++---- .../Templates/AzureMethodTemplate.cshtml | 8 +- .../Types/AzureJavaCompositeType.cs | 4 +- .../Datetimerfc1123Operations.java | 14 +-- .../Datetimerfc1123OperationsImpl.java | 14 +-- .../Java/Java/AutoRest.Generator.Java.csproj | 16 +-- .../Java/Java/ClientModelExtensions.cs | 15 +-- .../Generators/Java/Java/JavaCodeNamer.cs | 19 ++-- .../TemplateModels/MethodTemplateModel.cs | 100 ++++++++---------- .../Java/Java/Templates/MethodTemplate.cshtml | 12 +-- .../Java/Java/Templates/ModelTemplate.cshtml | 10 +- ...CompositeType.cs => CompositeTypeModel.cs} | 12 +-- ...ctionaryType.cs => DictionaryTypeModel.cs} | 16 ++- .../{JavaEnumType.cs => EnumTypeModel.cs} | 6 +- .../Types/{IJavaType.cs => ITypeModel.cs} | 4 +- .../{JavaParameter.cs => ParameterModel.cs} | 25 +++-- ...JavaPrimaryType.cs => PrimaryTypeModel.cs} | 12 +-- .../{JavaResponse.cs => ResponseModel.cs} | 34 +++--- ...vaSequenceType.cs => SequenceTypeModel.cs} | 18 +++- 20 files changed, 192 insertions(+), 210 deletions(-) rename AutoRest/Generators/Java/Java/Types/{JavaCompositeType.cs => CompositeTypeModel.cs} (86%) rename AutoRest/Generators/Java/Java/Types/{JavaDictionaryType.cs => DictionaryTypeModel.cs} (71%) rename AutoRest/Generators/Java/Java/Types/{JavaEnumType.cs => EnumTypeModel.cs} (87%) rename AutoRest/Generators/Java/Java/Types/{IJavaType.cs => ITypeModel.cs} (86%) rename AutoRest/Generators/Java/Java/Types/{JavaParameter.cs => ParameterModel.cs} (88%) rename AutoRest/Generators/Java/Java/Types/{JavaPrimaryType.cs => PrimaryTypeModel.cs} (94%) rename AutoRest/Generators/Java/Java/Types/{JavaResponse.cs => ResponseModel.cs} (79%) rename AutoRest/Generators/Java/Java/Types/{JavaSequenceType.cs => SequenceTypeModel.cs} (70%) diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs index ae02381cbb9f3..0f4469c356a94 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs @@ -66,7 +66,7 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict throw new ArgumentNullException("serviceClient"); } - var convertedTypes = new Dictionary(); + var convertedTypes = new Dictionary(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { @@ -81,38 +81,38 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict method.Extensions[AzureExtensions.PageableExtension] = null; } - foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is JavaCompositeType).Select(s => s.Key).ToArray()) + foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeTypeModel).Select(s => s.Key).ToArray()) { - var compositType = (JavaCompositeType)method.Responses[responseStatus].Body; - var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is JavaSequenceType) as JavaSequenceType; + var compositType = (CompositeTypeModel)method.Responses[responseStatus].Body; + var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceTypeModel) as SequenceTypeModel; // if the type is a wrapper over page-able response if (sequenceType != null) { - IJavaType pagedResult; - pagedResult = new JavaSequenceType + ITypeModel pagedResult; + pagedResult = new SequenceTypeModel { ElementType = sequenceType.ElementType, NameFormat = "List<{0}>" }; - convertedTypes[(IJavaType)method.Responses[responseStatus].Body] = pagedResult; + convertedTypes[(ITypeModel)method.Responses[responseStatus].Body] = pagedResult; method.Responses[responseStatus] = new Response(pagedResult, method.Responses[responseStatus].Headers); } } - if (convertedTypes.ContainsKey((IJavaType) method.ReturnType.Body)) + if (convertedTypes.ContainsKey((ITypeModel) method.ReturnType.Body)) { - method.ReturnType = new Response(convertedTypes[(IJavaType)method.ReturnType.Body], method.ReturnType.Headers); + method.ReturnType = new Response(convertedTypes[(ITypeModel)method.ReturnType.Body], method.ReturnType.Headers); } } - Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet(convertedTypes.Keys.Cast().Select(t => t.Name))); + Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet(convertedTypes.Keys.Cast().Select(t => t.Name))); } protected override IType NormalizeCompositeType(CompositeType compositeType) { - return new AzureJavaCompositeType((JavaCompositeType) base.NormalizeCompositeType(compositeType)); + return new AzureJavaCompositeType((CompositeTypeModel) base.NormalizeCompositeType(compositeType)); } #endregion diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 72e70f6a5b0bd..5deb4d9c4041a 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -15,8 +15,6 @@ namespace Microsoft.Rest.Generator.Java.Azure { public class AzureMethodTemplateModel : MethodTemplateModel { - private AzureJavaCodeNamer _namer; - public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) : base(source, serviceClient) { @@ -27,15 +25,6 @@ public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source); this.RequestIdString = AzureExtensions.GetRequestIdString(source); - this._namer = new AzureJavaCodeNamer(serviceClient.Namespace); - } - - protected override JavaCodeNamer Namer - { - get - { - return _namer; - } } public string ClientRequestIdString { get; private set; } @@ -152,20 +141,19 @@ public override string MethodParameterDeclarationWithCallback } if (this.IsPagingOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else if (this.IsPagingNextOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCall serviceCall, final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else { - parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - ReturnType.Body != null ? JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).ToString() : "Void"); + parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", GenericReturnTypeString); } return parameters; @@ -183,20 +171,19 @@ public override string MethodRequiredParameterDeclarationWithCallback } if (this.IsPagingOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else if (this.IsPagingNextOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCall serviceCall, final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else { - parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - ReturnType.Body != null ? JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).ToString() : "Void"); + parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", GenericReturnTypeString); } return parameters; @@ -530,7 +517,7 @@ public override string CallbackGenericTypeString if (ReturnType.Body is SequenceType && (this.IsPagingOperation || this.IsPagingNextOperation)) { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).Name; + return base.GenericReturnTypeString; } return base.CallbackGenericTypeString; } @@ -581,7 +568,7 @@ public override List InterfaceImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.PagedList"); imports.Remove("java.util.List"); - imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); + imports.AddRange(new CompositeTypeModel(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } return imports; } @@ -603,7 +590,7 @@ public override List ImplImports .Where(i => !this.Parameters.Any(p => p.Type.ImportSafe().Contains(i))) .ForEach(i => imports.Remove(i)); // return type may have been removed as a side effect - imports.AddRange(this.ReturnType.Body.ImportSafe()); + imports.AddRange(this.ReturnTypeModel.ImplImports); } if (this.IsPagingOperation || this.IsPagingNextOperation) { @@ -611,7 +598,7 @@ public override List ImplImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.Page"); imports.Add("com.microsoft.azure.PagedList"); - imports.AddRange(new JavaCompositeType(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); + imports.AddRange(new CompositeTypeModel(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } if (this.IsPagingNextOperation) { diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index bc0f46d6748f9..c388eb70f362a 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -56,7 +56,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi @: Validator.validate(@(param.Name)); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -106,7 +106,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -176,7 +176,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParam @: Validator.validate(@(param.Name)); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -222,7 +222,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { diff --git a/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs b/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs index 3235473d46599..2f50fd0b1db72 100644 --- a/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs +++ b/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs @@ -10,11 +10,11 @@ namespace Microsoft.Rest.Generator.Java { - public class AzureJavaCompositeType : JavaCompositeType + public class AzureJavaCompositeType : CompositeTypeModel { protected string _azureRuntimePackage = "com.microsoft.azure"; - public AzureJavaCompositeType(JavaCompositeType javaCompositeType) + public AzureJavaCompositeType(CompositeTypeModel javaCompositeType) : this(javaCompositeType.Package.Replace(".models", "")) { this.LoadFrom(javaCompositeType); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java index 5ce7050bfb070..9204bc950ba56 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java @@ -27,7 +27,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -45,7 +45,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalid() throws ErrorException, IOException; @@ -63,7 +63,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getOverflow() throws ErrorException, IOException; @@ -81,7 +81,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUnderflow() throws ErrorException, IOException; @@ -120,7 +120,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUtcLowercaseMaxDateTime() throws ErrorException, IOException; @@ -138,7 +138,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUtcUppercaseMaxDateTime() throws ErrorException, IOException; @@ -177,7 +177,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUtcMinDateTime() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java index ba0652d5a04de..495e8aba4e7a5 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java @@ -98,7 +98,7 @@ interface Datetimerfc1123Service { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -153,7 +153,7 @@ private ServiceResponse getNullDelegate(Response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalid() throws ErrorException, IOException { Call call = service.getInvalid(); @@ -208,7 +208,7 @@ private ServiceResponse getInvalidDelegate(Response getOverflow() throws ErrorException, IOException { Call call = service.getOverflow(); @@ -263,7 +263,7 @@ private ServiceResponse getOverflowDelegate(Response getUnderflow() throws ErrorException, IOException { Call call = service.getUnderflow(); @@ -373,7 +373,7 @@ private ServiceResponse putUtcMaxDateTimeDelegate(Response r * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUtcLowercaseMaxDateTime() throws ErrorException, IOException { Call call = service.getUtcLowercaseMaxDateTime(); @@ -428,7 +428,7 @@ private ServiceResponse getUtcLowercaseMaxDateTimeDelegate(Resp * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUtcUppercaseMaxDateTime() throws ErrorException, IOException { Call call = service.getUtcUppercaseMaxDateTime(); @@ -538,7 +538,7 @@ private ServiceResponse putUtcMinDateTimeDelegate(Response r * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUtcMinDateTime() throws ErrorException, IOException { Call call = service.getUtcMinDateTime(); diff --git a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj index 58452651f9c53..5224b75d70669 100644 --- a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj +++ b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj @@ -32,14 +32,14 @@ Resources.resx - - - - - - - - + + + + + + + + diff --git a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs index 42b78c33a616f..dccdc10f9cee1 100644 --- a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs +++ b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs @@ -79,19 +79,6 @@ public static void AddRange(this HashSet hashSet, IEnumerable range) } } - public static IType UserHandledType(this IType type) - { - PrimaryType primaryType = type as PrimaryType; - if (primaryType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - return new PrimaryType(KnownPrimaryType.DateTime); - } - else - { - return type; - } - } - /// /// A null friendly wrapper around type imports. /// @@ -103,7 +90,7 @@ public static IEnumerable ImportSafe(this IType type) { return new List(); } - return ((IJavaType) type).Imports; + return ((ITypeModel) type).Imports; } public static string ImportFrom(this HttpMethod httpMethod) diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index 3fd8f9d5ff41a..3c02c6471bda6 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -209,6 +209,7 @@ protected override void NormalizeParameters(Method method) { parameterTransformation.OutputParameter.Name = method.Scope.GetUniqueName(GetParameterName(parameterTransformation.OutputParameter.GetClientName())); parameterTransformation.OutputParameter.Type = NormalizeTypeReference(parameterTransformation.OutputParameter.Type); + parameterTransformation.OutputParameter = new ParameterModel(parameterTransformation.OutputParameter, method); QuoteParameter(parameterTransformation.OutputParameter); @@ -246,8 +247,8 @@ protected override void NormalizeClientProperties(ServiceClient client) } public override Response NormalizeTypeReference(Response typePair) { - return new Response((IJavaType) NormalizeTypeReference(typePair.Body), - (IJavaType) NormalizeTypeReference(typePair.Headers)); + return new Response((ITypeModel) NormalizeTypeReference(typePair.Body), + (ITypeModel) NormalizeTypeReference(typePair.Headers)); } public override IType NormalizeTypeDeclaration(IType type) @@ -264,7 +265,7 @@ public override IType NormalizeTypeReference(IType type) var enumType = type as EnumType; if (enumType != null && enumType.ModelAsString) { - type = new JavaPrimaryType(KnownPrimaryType.String); + type = new PrimaryTypeModel(KnownPrimaryType.String); } if (type is PrimaryType) @@ -308,7 +309,7 @@ private IType NormalizeEnumType(EnumType enumType) { enumType.Values[i].Name = GetEnumMemberName(enumType.Values[i].Name); } - return new JavaEnumType(enumType, _package); + return new EnumTypeModel(enumType, _package); } protected virtual IType NormalizeCompositeType(CompositeType compositeType) @@ -325,31 +326,31 @@ protected virtual IType NormalizeCompositeType(CompositeType compositeType) } } - return new JavaCompositeType(compositeType, _package); + return new CompositeTypeModel(compositeType, _package); } - public static JavaPrimaryType NormalizePrimaryType(PrimaryType primaryType) + public static PrimaryTypeModel NormalizePrimaryType(PrimaryType primaryType) { if (primaryType == null) { throw new ArgumentNullException("primaryType"); } - return new JavaPrimaryType(primaryType); + return new PrimaryTypeModel(primaryType); } private IType NormalizeSequenceType(SequenceType sequenceType) { sequenceType.ElementType = WrapPrimitiveType(NormalizeTypeReference(sequenceType.ElementType)); sequenceType.NameFormat = "List<{0}>"; - return new JavaSequenceType(sequenceType); + return new SequenceTypeModel(sequenceType); } private IType NormalizeDictionaryType(DictionaryType dictionaryType) { dictionaryType.ValueType = WrapPrimitiveType(NormalizeTypeReference(dictionaryType.ValueType)); dictionaryType.NameFormat = "Map"; - return new JavaDictionaryType(dictionaryType); + return new DictionaryTypeModel(dictionaryType); } #endregion diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 1455980174532..6e5b816f9620d 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -15,18 +15,17 @@ namespace Microsoft.Rest.Generator.Java { public class MethodTemplateModel : Method { - private JavaCodeNamer _namer; - private JavaResponse _javaReturnType; - private Dictionary _javaResponses; + private ResponseModel _returnTypeModel; + private Dictionary _responseModels; public MethodTemplateModel(Method source, ServiceClient serviceClient) { this.LoadFrom(source); - JavaParameters = new List(); - JavaLogicalParameters = new List(); - source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p, this))); - source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => JavaParameters.Add(new JavaParameter(p, this))); - source.LogicalParameters.ForEach(p => JavaLogicalParameters.Add(new JavaParameter(p, this))); + ParameterModels = new List(); + LogicalParameterModels = new List(); + source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => ParameterModels.Add(new ParameterModel(p, this))); + source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => ParameterModels.Add(new ParameterModel(p, this))); + source.LogicalParameters.ForEach(p => LogicalParameterModels.Add(new ParameterModel(p, this))); ServiceClient = serviceClient; if (source.Group != null) { @@ -38,18 +37,9 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) OperationName = serviceClient.Name; ClientReference = "this"; } - _namer = new JavaCodeNamer(serviceClient.Namespace); - _javaReturnType = new JavaResponse(ReturnType); - _javaResponses = new Dictionary(); - Responses.ForEach(r => _javaResponses.Add(r.Key, new JavaResponse(r.Value))); - } - - protected virtual JavaCodeNamer Namer - { - get - { - return _namer; - } + _returnTypeModel = new ResponseModel(ReturnType); + _responseModels = new Dictionary(); + Responses.ForEach(r => _responseModels.Add(r.Key, new ResponseModel(r.Value))); } public string ClientReference { get; set; } @@ -58,36 +48,36 @@ protected virtual JavaCodeNamer Namer public ServiceClient ServiceClient { get; set; } - public List JavaParameters { get; private set; } + public List ParameterModels { get; private set; } - public List JavaLogicalParameters { get; private set; } + public List LogicalParameterModels { get; private set; } - public JavaResponse JavaReturnType + public ResponseModel ReturnTypeModel { get { - return _javaReturnType; + return _returnTypeModel; } } - public Dictionary JavaResponses + public Dictionary ResponseModels { get { - return _javaResponses; + return _responseModels; } } - public IEnumerable RetrofitParameters + public IEnumerable RetrofitParameters { get { - return JavaLogicalParameters.Where(p => p.Location != ParameterLocation.None) + return LogicalParameterModels.Where(p => p.Location != ParameterLocation.None) .Where(p => !p.Extensions.ContainsKey("hostParameter")); } } - public IEnumerable OrderedRetrofitParameters + public IEnumerable OrderedRetrofitParameters { get { @@ -217,7 +207,7 @@ public virtual string BuildInputMappings() if (conditionalAssignment) { builder.AppendLine("{0} {1} = null;", - ((IJavaType) transformation.OutputParameter.Type).ParameterVariant, + ((ParameterModel) transformation.OutputParameter).ClientType.ParameterVariant, transformation.OutputParameter.Name); builder.AppendLine("if ({0}) {{", nullCheck).Indent(); } @@ -226,7 +216,7 @@ public virtual string BuildInputMappings() transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0}{1} = new {2}();", - !conditionalAssignment ? ((IJavaType) transformation.OutputParameter.Type).ParameterVariant + " " : "", + !conditionalAssignment ? ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } @@ -235,7 +225,7 @@ public virtual string BuildInputMappings() { builder.AppendLine("{0}{1}{2};", !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? - ((IJavaType) transformation.OutputParameter.Type).ParameterVariant + " " : "", + ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "", transformation.OutputParameter.Name, GetMapping(mapping)); } @@ -283,11 +273,11 @@ private static string BuildNullCheckExpression(ParameterTransformation transform .Select(m => m.InputParameter.Name + " != null")); } - public IEnumerable RequiredNullableParameters + public IEnumerable RequiredNullableParameters { get { - foreach (var param in JavaParameters) + foreach (var param in ParameterModels) { if (!param.Type.IsPrimaryType(KnownPrimaryType.Int) && !param.Type.IsPrimaryType(KnownPrimaryType.Double) && @@ -301,11 +291,11 @@ public IEnumerable RequiredNullableParameters } } - public IEnumerable ParametersToValidate + public IEnumerable ParametersToValidate { get { - foreach (var param in JavaParameters) + foreach (var param in ParameterModels) { if (param.Type is PrimaryType || param.Type is EnumType || @@ -394,12 +384,12 @@ public virtual string MethodParameterInvocationWithCallback /// Get the parameters that are actually method parameters in the order they appear in the method signature /// exclude global parameters /// - public IEnumerable LocalParameters + public IEnumerable LocalParameters { get { //Omit parameter-group properties for now since Java doesn't support them yet - return JavaParameters.Where( + return ParameterModels.Where( p => p != null && p.ClientProperty == null && !string.IsNullOrWhiteSpace(p.Name)) .OrderBy(item => !item.IsRequired); } @@ -477,7 +467,7 @@ public string ReturnTypeString { if (ReturnType.Body != null) { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).Name; + return ((ITypeModel)ReturnType.Body).InstanceType().ResponseVariant; } return "void"; } @@ -489,7 +479,7 @@ public virtual string GenericReturnTypeString { if (ReturnType.Body != null) { - return ((IJavaType) ReturnType.Body).InstanceType().ResponseVariant; + return ((ITypeModel) ReturnType.Body).InstanceType().ResponseVariant; } return "Void"; } @@ -509,7 +499,7 @@ public virtual string DelegateReturnTypeString { if (ReturnType.Body != null) { - return ((IJavaType) ReturnType.Body).InstanceType().Name; + return ((ITypeModel) ReturnType.Body).InstanceType().Name; } return "Void"; } @@ -615,14 +605,14 @@ public virtual string ResponseGeneration { get { - if (JavaReturnType.NeedsConversion) + if (ReturnTypeModel.NeedsConversion) { IndentedStringBuilder builder= new IndentedStringBuilder(); builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());", DelegateReturnTypeString, this.Name.ToCamelCase()); - builder.AppendLine("{0} body = null;", JavaReturnType.BodyClientType) + builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) .AppendLine("if (response.getBody() != null) {") - .Indent().AppendLine("body = {0};", JavaReturnType.ConvertBodyToClientType("response.getBody()")) + .Indent().AppendLine("body = {0};", ReturnTypeModel.ConvertBodyToClientType("response.getBody()")) .Outdent().AppendLine("}"); return builder.ToString(); } @@ -634,7 +624,7 @@ public virtual string ReturnValue { get { - if (JavaReturnType.NeedsConversion) + if (ReturnTypeModel.NeedsConversion) { return "new ServiceResponse<" + this.GenericReturnTypeString + ">(body, response.getResponse())"; } @@ -646,13 +636,13 @@ public virtual string SuccessCallback { get { - if (JavaReturnType.NeedsConversion) + if (ReturnTypeModel.NeedsConversion) { IndentedStringBuilder builder = new IndentedStringBuilder(); builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", DelegateReturnTypeString, this.Name); - builder.AppendLine("{0} body = null;", JavaReturnType.BodyClientType) + builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) .AppendLine("if (result.getBody() != null) {") - .Indent().AppendLine("body = {0};", JavaReturnType.ConvertBodyToClientType("result.getBody()")) + .Indent().AppendLine("body = {0};", ReturnTypeModel.ConvertBodyToClientType("result.getBody()")) .Outdent().AppendLine("}"); builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", GenericReturnTypeString); return builder.ToString(); @@ -687,11 +677,9 @@ public virtual List InterfaceImports imports.Add("com.microsoft.rest." + OperationResponseType); imports.Add("com.microsoft.rest.ServiceCallback"); // parameter types - this.JavaParameters.ForEach(p => imports.AddRange(p.InterfaceImports)); + this.ParameterModels.ForEach(p => imports.AddRange(p.InterfaceImports)); // return type - imports.AddRange(this.ReturnType.Body.ImportSafe()); - // Header type - imports.AddRange(this.ReturnType.Headers.ImportSafe()); + imports.AddRange(this.ReturnTypeModel.InterfaceImports); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => { @@ -750,18 +738,16 @@ public virtual List ImplImports imports.Add("com.microsoft.rest.ServiceResponseCallback"); } // parameter utils - this.LocalParameters.Concat(this.JavaLogicalParameters) + this.LocalParameters.Concat(this.LogicalParameterModels) .ForEach(p => imports.AddRange(p.ImplImports)); // return type - imports.AddRange(this.ReturnType.Body.ImportSafe()); + imports.AddRange(this.ReturnTypeModel.ImplImports); if (ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) { imports.Add("retrofit2.http.Streaming"); } // response type (can be different from return type) - this.Responses.ForEach(r => imports.AddRange(r.Value.Body.ImportSafe())); - // Header type - imports.AddRange(this.ReturnType.Headers.ImportSafe()); + this.ResponseModels.ForEach(r => imports.AddRange(r.Value.ImplImports)); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index bfc98fb3dd409..e79f3ee7bac95 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -45,7 +45,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi { @: Validator.validate(@(param.Name)); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -105,7 +105,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { @@ -180,7 +180,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParam { @: Validator.validate(@(param.Name)); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -235,7 +235,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (JavaParameter parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -268,10 +268,10 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @EmptyLine private @Model.DelegateOperationResponseReturnTypeString @(Model.Name)Delegate(Response<@Model.CallType> response) throws @Model.ExceptionString { return new @Model.ResponseBuilder<@Model.DelegateReturnTypeString, @Model.OperationExceptionTypeString>(@(Model.ClientReference).getMapperAdapter()) -@foreach (var response in Model.Responses) +@foreach (var response in Model.ResponseModels) { - @:.register(@((int)response.Key), new TypeToken<@Model.TypeTokenType(response.Value.Body)>() { }.getType()) + @:.register(@((int)response.Key), new TypeToken<@response.Value.BodyWireType.InstanceType()>() { }.getType()) } @if (Model.DefaultResponse.Body != null) { diff --git a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml index d1234e95e3b0f..65ca7856ef46b 100644 --- a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml @@ -87,13 +87,13 @@ if (!jsonSetting.IsNullOrEmpty()) @: * @: * @@return the @property.Name value @: */ -@: public @property.Type.UserHandledType().Name get@(property.Name.ToPascalCase())() { -if (property.Type.Name != ((IJavaType) property.Type).ResponseVariant) +@: public @(((ITypeModel)property.Type).ResponseVariant) get@(property.Name.ToPascalCase())() { +if (property.Type.Name != ((ITypeModel) property.Type).ResponseVariant) { @: if (this.@(property.Name) == null) { @: return null; @: } -@: return this.@(property.Name).get@(((IJavaType)property.Type).ResponseVariant)(); +@: return this.@(property.Name).get@(((ITypeModel)property.Type).ResponseVariant)(); } else { @@ -108,8 +108,8 @@ if (!property.IsReadOnly) @: * @: * @@param @property.Name the @property.Name value to set @: */ -@: public void set@(property.Name.ToPascalCase())(@(((IJavaType)property.Type).ResponseVariant) @property.Name) { -if (property.Type.Name != ((IJavaType)property.Type).ResponseVariant) +@: public void set@(property.Name.ToPascalCase())(@(((ITypeModel)property.Type).ResponseVariant) @property.Name) { +if (property.Type.Name != ((ITypeModel)property.Type).ResponseVariant) { @: this.@(property.Name) = new @(property.Type.Name)(@property.Name); } diff --git a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs b/AutoRest/Generators/Java/Java/Types/CompositeTypeModel.cs similarity index 86% rename from AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs rename to AutoRest/Generators/Java/Java/Types/CompositeTypeModel.cs index c02c3866f22a3..2dbb0b8eab1a7 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaCompositeType.cs +++ b/AutoRest/Generators/Java/Java/Types/CompositeTypeModel.cs @@ -10,19 +10,19 @@ namespace Microsoft.Rest.Generator.Java { - public class JavaCompositeType : CompositeType, IJavaType + public class CompositeTypeModel : CompositeType, ITypeModel { protected string _package; public const string ExternalExtension = "x-ms-external"; protected string _runtimePackage = "com.microsoft.rest"; - public JavaCompositeType(CompositeType compositeType, string package) + public CompositeTypeModel(CompositeType compositeType, string package) : this(package) { this.LoadFrom(compositeType); } - public JavaCompositeType(string package) + public CompositeTypeModel(string package) : base() { this._package = package.ToLower(CultureInfo.InvariantCulture); @@ -87,12 +87,12 @@ public IEnumerable Imports } } - public IJavaType InstanceType() + public ITypeModel InstanceType() { return this; } - private IEnumerable ParseGenericType() + private IEnumerable ParseGenericType() { string name = Name; string[] types = Name.Split(new String[] { "<", ">", ",", ", " }, StringSplitOptions.RemoveEmptyEntries); @@ -100,7 +100,7 @@ private IEnumerable ParseGenericType() { if (!JavaCodeNamer.PrimaryTypes.Contains(innerType.Trim())) { - yield return new JavaCompositeType(_package) { Name = innerType.Trim() }; + yield return new CompositeTypeModel(_package) { Name = innerType.Trim() }; } } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs b/AutoRest/Generators/Java/Java/Types/DictionaryTypeModel.cs similarity index 71% rename from AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs rename to AutoRest/Generators/Java/Java/Types/DictionaryTypeModel.cs index 021314f752943..59c9743e936ce 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaDictionaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/DictionaryTypeModel.cs @@ -9,14 +9,22 @@ namespace Microsoft.Rest.Generator.Java { - public class JavaDictionaryType : DictionaryType, IJavaType + public class DictionaryTypeModel : DictionaryType, ITypeModel { - public JavaDictionaryType(DictionaryType dictionaryType) + public DictionaryTypeModel(DictionaryType dictionaryType) : base() { this.LoadFrom(dictionaryType); } + public ITypeModel ValueTypeModel + { + get + { + return (ITypeModel)this.ValueType; + } + } + public string ParameterVariant { get @@ -46,11 +54,11 @@ public IEnumerable Imports get { List imports = new List { "java.util.Map" }; - return imports.Concat(((IJavaType) this.ValueType).Imports); + return imports.Concat(((ITypeModel) this.ValueType).Imports); } } - public IJavaType InstanceType() + public ITypeModel InstanceType() { return this; } diff --git a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs b/AutoRest/Generators/Java/Java/Types/EnumTypeModel.cs similarity index 87% rename from AutoRest/Generators/Java/Java/Types/JavaEnumType.cs rename to AutoRest/Generators/Java/Java/Types/EnumTypeModel.cs index b24efa94b37a8..ee0b7ec043681 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaEnumType.cs +++ b/AutoRest/Generators/Java/Java/Types/EnumTypeModel.cs @@ -10,11 +10,11 @@ namespace Microsoft.Rest.Generator.Java { - public class JavaEnumType : EnumType, IJavaType + public class EnumTypeModel : EnumType, ITypeModel { private string _package; - public JavaEnumType(EnumType enumType, string package) + public EnumTypeModel(EnumType enumType, string package) : base() { this.LoadFrom(enumType); @@ -53,7 +53,7 @@ public IEnumerable Imports } } - public IJavaType InstanceType() + public ITypeModel InstanceType() { return this; } diff --git a/AutoRest/Generators/Java/Java/Types/IJavaType.cs b/AutoRest/Generators/Java/Java/Types/ITypeModel.cs similarity index 86% rename from AutoRest/Generators/Java/Java/Types/IJavaType.cs rename to AutoRest/Generators/Java/Java/Types/ITypeModel.cs index fda926a15f3e9..3c45f84efd0d0 100644 --- a/AutoRest/Generators/Java/Java/Types/IJavaType.cs +++ b/AutoRest/Generators/Java/Java/Types/ITypeModel.cs @@ -9,7 +9,7 @@ namespace Microsoft.Rest.Generator.Java { - public interface IJavaType : IType + public interface ITypeModel : IType { string DefaultValue { get; } @@ -19,6 +19,6 @@ public interface IJavaType : IType IEnumerable Imports { get; } - IJavaType InstanceType(); + ITypeModel InstanceType(); } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaParameter.cs b/AutoRest/Generators/Java/Java/Types/ParameterModel.cs similarity index 88% rename from AutoRest/Generators/Java/Java/Types/JavaParameter.cs rename to AutoRest/Generators/Java/Java/Types/ParameterModel.cs index 2723fb3d918d8..ee6389eb3771a 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaParameter.cs +++ b/AutoRest/Generators/Java/Java/Types/ParameterModel.cs @@ -10,37 +10,42 @@ namespace Microsoft.Rest.Generator.Java { - public class JavaParameter : Parameter + public class ParameterModel : Parameter { - private MethodTemplateModel _method; + private Method _method; - public JavaParameter(Parameter parameter, MethodTemplateModel method) + public ParameterModel(Parameter parameter, Method method) : base() { this.LoadFrom(parameter); this._method = method; + // Use instance type for optional parameters + if (!this.IsRequired) + { + this.Type = ((ITypeModel) Type).InstanceType(); + } } - public IJavaType ClientType + public ITypeModel ClientType { get { - return (IJavaType) Type; + return (ITypeModel) Type; } } - public IJavaType WireType + public ITypeModel WireType { get { if (Type.IsPrimaryType(KnownPrimaryType.Stream)) { - return new JavaPrimaryType(KnownPrimaryType.Stream) { Name = "RequestBody" }; + return new PrimaryTypeModel(KnownPrimaryType.Stream) { Name = "RequestBody" }; } else if ((Location != ParameterLocation.Body) && NeedsSpecialSerialization(Type)) { - return new JavaPrimaryType(KnownPrimaryType.String); + return new PrimaryTypeModel(KnownPrimaryType.String); } else { @@ -57,8 +62,8 @@ public string Invoke(string reference, string clientReference) } else if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData) { - var primary = ClientType as JavaPrimaryType; - var sequence = ClientType as JavaSequenceType; + var primary = ClientType as PrimaryTypeModel; + var sequence = ClientType as SequenceTypeModel; if (primary != null && primary.Name != "LocalDate" && primary.Name != "DateTime") { if (primary.Type == KnownPrimaryType.ByteArray) diff --git a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs b/AutoRest/Generators/Java/Java/Types/PrimaryTypeModel.cs similarity index 94% rename from AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs rename to AutoRest/Generators/Java/Java/Types/PrimaryTypeModel.cs index e981aa11bab3b..5702307f47955 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaPrimaryType.cs +++ b/AutoRest/Generators/Java/Java/Types/PrimaryTypeModel.cs @@ -10,16 +10,16 @@ namespace Microsoft.Rest.Generator.Java { - public class JavaPrimaryType : PrimaryType, IJavaType + public class PrimaryTypeModel : PrimaryType, ITypeModel { private List _imports; - public JavaPrimaryType(KnownPrimaryType knownPrimaryType) + public PrimaryTypeModel(KnownPrimaryType knownPrimaryType) : this (new PrimaryType(knownPrimaryType)) { } - public JavaPrimaryType(PrimaryType primaryType) + public PrimaryTypeModel(PrimaryType primaryType) : base (primaryType != null ? primaryType.Type : KnownPrimaryType.None) { if (primaryType == null) @@ -42,7 +42,7 @@ public string DefaultValue } else if (this.Name == "Byte[]") { - return "new Byte[]"; + return "new Byte[0]"; } else if (this.IsInstanceType) // instance type @@ -106,14 +106,14 @@ private bool IsInstanceType } } - public IJavaType InstanceType() + public ITypeModel InstanceType() { if (this.IsInstanceType) { return this; } - JavaPrimaryType instanceType = new JavaPrimaryType(this); + PrimaryTypeModel instanceType = new PrimaryTypeModel(this); if (instanceType.Name == "boolean") { instanceType.Name = "Boolean"; diff --git a/AutoRest/Generators/Java/Java/Types/JavaResponse.cs b/AutoRest/Generators/Java/Java/Types/ResponseModel.cs similarity index 79% rename from AutoRest/Generators/Java/Java/Types/JavaResponse.cs rename to AutoRest/Generators/Java/Java/Types/ResponseModel.cs index 75d6c0ca0c403..3ce41e2c9cecb 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaResponse.cs +++ b/AutoRest/Generators/Java/Java/Types/ResponseModel.cs @@ -10,21 +10,21 @@ namespace Microsoft.Rest.Generator.Java { - public class JavaResponse + public class ResponseModel { private Response _response; - public JavaResponse(Response response) + public ResponseModel(Response response) { this._response = response; } - public JavaResponse(IJavaType body, IJavaType headers) + public ResponseModel(ITypeModel body, ITypeModel headers) : this(new Response(body, headers)) { } - public IJavaType Body + public ITypeModel Body { get { @@ -32,11 +32,11 @@ public IJavaType Body { return null; } - return (IJavaType)_response.Body; + return (ITypeModel)_response.Body; } } - public IJavaType Headers + public ITypeModel Headers { get { @@ -44,7 +44,7 @@ public IJavaType Headers { return null; } - return (IJavaType)_response.Headers; + return (ITypeModel)_response.Headers; } } @@ -60,17 +60,17 @@ public bool NeedsConversion } } - public IJavaType BodyClientType + public ITypeModel BodyClientType { get { if (Body == null) { - return null; + return new PrimaryTypeModel(KnownPrimaryType.None) { Name = "void" }; } else if (Body.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { - return new JavaPrimaryType(KnownPrimaryType.DateTime); + return new PrimaryTypeModel(KnownPrimaryType.DateTime); } else { @@ -79,19 +79,19 @@ public IJavaType BodyClientType } } - public IJavaType BodyWireType + public ITypeModel BodyWireType { get { if (Body == null) { - return null; + return new PrimaryTypeModel(KnownPrimaryType.None) { Name = "void" }; } - return (IJavaType) Body; + return (ITypeModel) Body; } } - public IJavaType HeaderClientType + public ITypeModel HeaderClientType { get { @@ -101,7 +101,7 @@ public IJavaType HeaderClientType } else if (Headers.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { - return new JavaPrimaryType(KnownPrimaryType.DateTime); + return new PrimaryTypeModel(KnownPrimaryType.DateTime); } else { @@ -110,7 +110,7 @@ public IJavaType HeaderClientType } } - public IJavaType HeaderWireType + public ITypeModel HeaderWireType { get { @@ -118,7 +118,7 @@ public IJavaType HeaderWireType { return null; } - return (IJavaType)Headers; + return (ITypeModel)Headers; } } diff --git a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs b/AutoRest/Generators/Java/Java/Types/SequenceTypeModel.cs similarity index 70% rename from AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs rename to AutoRest/Generators/Java/Java/Types/SequenceTypeModel.cs index bd006810059aa..30137c350913f 100644 --- a/AutoRest/Generators/Java/Java/Types/JavaSequenceType.cs +++ b/AutoRest/Generators/Java/Java/Types/SequenceTypeModel.cs @@ -9,19 +9,27 @@ namespace Microsoft.Rest.Generator.Java { - public class JavaSequenceType : SequenceType, IJavaType + public class SequenceTypeModel : SequenceType, ITypeModel { - public JavaSequenceType(SequenceType sequenceType) + public SequenceTypeModel(SequenceType sequenceType) : base() { this.LoadFrom(sequenceType); } - public JavaSequenceType() + public SequenceTypeModel() : base() { } + public ITypeModel ElementTypeModel + { + get + { + return (ITypeModel) this.ElementType; + } + } + public string ParameterVariant { get @@ -51,11 +59,11 @@ public IEnumerable Imports get { List imports = new List { "java.util.List" }; - return imports.Concat(((IJavaType) this.ElementType).Imports); + return imports.Concat(((ITypeModel) this.ElementType).Imports); } } - public IJavaType InstanceType() + public ITypeModel InstanceType() { return this; } From 3c7cc6c0957554362a59e20dd3fbe658a60ecadb Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 23:02:17 -0700 Subject: [PATCH 29/99] Fix type token type --- .../Azure.Java/TemplateModels/AzureMethodTemplateModel.cs | 6 +++--- .../Java/Java/TemplateModels/MethodTemplateModel.cs | 4 ++-- .../Generators/Java/Java/Templates/MethodTemplate.cshtml | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 5deb4d9c4041a..64c69aa4f20bc 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -484,12 +484,12 @@ public override string DelegateReturnTypeString } } - public override string TypeTokenType(IType type) + public override string TypeTokenType(ITypeModel type) { - SequenceType sequenceType = type as SequenceType; + SequenceTypeModel sequenceType = type as SequenceTypeModel; if (sequenceType != null && (this.IsPagingOperation || this.IsPagingNextOperation || this.IsPagingNonPollingOperation)) { - return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", sequenceType.ElementType); + return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", sequenceType.ElementTypeModel.InstanceType()); } return base.TypeTokenType(type); } diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 6e5b816f9620d..956b010d63d2b 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -505,9 +505,9 @@ public virtual string DelegateReturnTypeString } } - public virtual string TypeTokenType(IType type) + public virtual string TypeTokenType(ITypeModel type) { - return JavaCodeNamer.WrapPrimitiveType(type).Name; + return type.InstanceType().Name; } public string OperationResponseType diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index e79f3ee7bac95..c9aab9ef9e4b3 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -271,7 +271,7 @@ private @Model.DelegateOperationResponseReturnTypeString @(Model.Name)Delegate(R @foreach (var response in Model.ResponseModels) { - @:.register(@((int)response.Key), new TypeToken<@response.Value.BodyWireType.InstanceType()>() { }.getType()) + @:.register(@((int)response.Key), new TypeToken<@Model.TypeTokenType(response.Value.BodyWireType)>() { }.getType()) } @if (Model.DefaultResponse.Body != null) { From f35d545bf973b423c3359754d28b86f2a9f4d69d Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 23:02:54 -0700 Subject: [PATCH 30/99] Move folder --- .../Java/Java/{Types => TypeModels}/CompositeTypeModel.cs | 0 .../Java/Java/{Types => TypeModels}/DictionaryTypeModel.cs | 0 .../Generators/Java/Java/{Types => TypeModels}/EnumTypeModel.cs | 0 AutoRest/Generators/Java/Java/{Types => TypeModels}/ITypeModel.cs | 0 .../Generators/Java/Java/{Types => TypeModels}/ParameterModel.cs | 0 .../Java/Java/{Types => TypeModels}/PrimaryTypeModel.cs | 0 .../Generators/Java/Java/{Types => TypeModels}/ResponseModel.cs | 0 .../Java/Java/{Types => TypeModels}/SequenceTypeModel.cs | 0 8 files changed, 0 insertions(+), 0 deletions(-) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/CompositeTypeModel.cs (100%) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/DictionaryTypeModel.cs (100%) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/EnumTypeModel.cs (100%) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/ITypeModel.cs (100%) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/ParameterModel.cs (100%) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/PrimaryTypeModel.cs (100%) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/ResponseModel.cs (100%) rename AutoRest/Generators/Java/Java/{Types => TypeModels}/SequenceTypeModel.cs (100%) diff --git a/AutoRest/Generators/Java/Java/Types/CompositeTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/CompositeTypeModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs diff --git a/AutoRest/Generators/Java/Java/Types/DictionaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/DictionaryTypeModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs diff --git a/AutoRest/Generators/Java/Java/Types/EnumTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/EnumTypeModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs diff --git a/AutoRest/Generators/Java/Java/Types/ITypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/ITypeModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs diff --git a/AutoRest/Generators/Java/Java/Types/ParameterModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/ParameterModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs diff --git a/AutoRest/Generators/Java/Java/Types/PrimaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/PrimaryTypeModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs diff --git a/AutoRest/Generators/Java/Java/Types/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/ResponseModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs diff --git a/AutoRest/Generators/Java/Java/Types/SequenceTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs similarity index 100% rename from AutoRest/Generators/Java/Java/Types/SequenceTypeModel.cs rename to AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs From 1539446eb408ce27746ba0ee5ae75603eeb3ccb6 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 23 Mar 2016 23:15:21 -0700 Subject: [PATCH 31/99] Move OperationResponseType to ResponseModel --- .../AutoRest.Generator.Azure.Java.csproj | 3 +- .../Java/Azure.Java/AzureJavaCodeNamer.cs | 2 +- .../AzureMethodTemplateModel.cs | 20 +++++------ .../Templates/AzureMethodTemplate.cshtml | 8 ++--- .../AzureCompositeTypeModel.cs} | 10 +++--- .../TypeModels/AzureResponseModel.cs | 28 +++++++++++++++ .../Java/Java/AutoRest.Generator.Java.csproj | 16 ++++----- .../TemplateModels/MethodTemplateModel.cs | 35 +++++-------------- .../Templates/MethodInterfaceTemplate.cshtml | 8 ++--- .../Java/Java/Templates/MethodTemplate.cshtml | 8 ++--- .../Java/Java/TypeModels/ResponseModel.cs | 15 ++++++++ 11 files changed, 89 insertions(+), 64 deletions(-) rename AutoRest/Generators/Java/Azure.Java/{Types/AzureJavaCompositeType.cs => TypeModels/AzureCompositeTypeModel.cs} (80%) create mode 100644 AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs diff --git a/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj b/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj index 2e000f6631f02..3047a09afadb8 100644 --- a/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj +++ b/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj @@ -66,7 +66,8 @@ AzureServiceClientRetrofitTemplate.cshtml - + + diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs index 0f4469c356a94..bfeaa978fb465 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs @@ -112,7 +112,7 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict protected override IType NormalizeCompositeType(CompositeType compositeType) { - return new AzureJavaCompositeType((CompositeTypeModel) base.NormalizeCompositeType(compositeType)); + return new AzureCompositeTypeModel((CompositeTypeModel) base.NormalizeCompositeType(compositeType)); } #endregion diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 64c69aa4f20bc..741a443ed4e79 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -303,7 +303,7 @@ public override string ResponseGeneration { var builder = new IndentedStringBuilder(); builder.AppendLine("{0}> response = {2}Delegate(call.execute());", - this.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + ReturnTypeModel.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); builder.AppendLine("{0} result = response.getBody().getItems();", this.ReturnType.Body.Name); return builder.ToString(); } @@ -323,12 +323,12 @@ public override string ReturnValue if (ReturnType.Headers != null) { return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.getHeaders(), response.getResponse())", - this.OperationResponseType); + ReturnTypeModel.OperationResponseType); } else { return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.getResponse())", - this.OperationResponseType); + ReturnTypeModel.OperationResponseType); } } else @@ -360,11 +360,11 @@ public override string SuccessCallback builder.AppendLine("} else {").Indent(); if (ReturnType.Headers == null) { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", this.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.OperationResponseType); } else { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", this.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.OperationResponseType); } builder.Outdent().AppendLine("}"); return builder.ToString(); @@ -383,11 +383,11 @@ public override string SuccessCallback builder.AppendLine("} else {").Indent(); if (ReturnType.Headers == null) { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", this.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.OperationResponseType); } else { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", this.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.OperationResponseType); } builder.Outdent().AppendLine("}"); return builder.ToString(); @@ -396,14 +396,14 @@ public override string SuccessCallback { var builder = new IndentedStringBuilder(); builder.AppendLine("{0}> result = {2}Delegate(response);", - this.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + ReturnTypeModel.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); if (ReturnType.Headers == null) { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", this.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", ReturnTypeModel.OperationResponseType); } else { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", this.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.OperationResponseType); } return builder.ToString(); } diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index c388eb70f362a..8d16e6c5c5996 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -37,11 +37,11 @@ if (Model.LocalParameters.Any(p => !p.IsConstant && !p.IsRequired)) } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. } else { -@: * @@return the @Model.OperationResponseType object if successful. +@: * @@return the @Model.ReturnTypeModel.OperationResponseType object if successful. } */ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { @@ -157,11 +157,11 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. } else { -@: * @@return the @Model.OperationResponseType object if successful. +@: * @@return the @Model.ReturnTypeModel.OperationResponseType object if successful. } */ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { diff --git a/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureCompositeTypeModel.cs similarity index 80% rename from AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs rename to AutoRest/Generators/Java/Azure.Java/TypeModels/AzureCompositeTypeModel.cs index 2f50fd0b1db72..b3d43ea2b8033 100644 --- a/AutoRest/Generators/Java/Azure.Java/Types/AzureJavaCompositeType.cs +++ b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureCompositeTypeModel.cs @@ -8,25 +8,25 @@ using Microsoft.Rest.Generator.Utilities; using Microsoft.Rest.Generator.Azure; -namespace Microsoft.Rest.Generator.Java +namespace Microsoft.Rest.Generator.Java.Azure { - public class AzureJavaCompositeType : CompositeTypeModel + public class AzureCompositeTypeModel : CompositeTypeModel { protected string _azureRuntimePackage = "com.microsoft.azure"; - public AzureJavaCompositeType(CompositeTypeModel javaCompositeType) + public AzureCompositeTypeModel(CompositeTypeModel javaCompositeType) : this(javaCompositeType.Package.Replace(".models", "")) { this.LoadFrom(javaCompositeType); } - public AzureJavaCompositeType(CompositeType compositeType, string package) + public AzureCompositeTypeModel(CompositeType compositeType, string package) : this(package) { this.LoadFrom(compositeType); } - public AzureJavaCompositeType(string package) + public AzureCompositeTypeModel(string package) : base(package) { this._package = package; diff --git a/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs new file mode 100644 index 0000000000000..ebfb24f2503fc --- /dev/null +++ b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs @@ -0,0 +1,28 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java.Azure +{ + public class AzureResponseModel : ResponseModel + { + private Response _response; + + public AzureResponseModel(Response response) + : base (response) + { + this._response = response; + } + + public AzureResponseModel(ITypeModel body, ITypeModel headers) + : this(new Response(body, headers)) + { + } + } +} diff --git a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj index 5224b75d70669..2072eabb4463d 100644 --- a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj +++ b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj @@ -32,14 +32,14 @@ Resources.resx - - - - - - - - + + + + + + + + diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 956b010d63d2b..cc9f96205b287 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -497,11 +497,7 @@ public virtual string DelegateReturnTypeString { get { - if (ReturnType.Body != null) - { - return ((ITypeModel) ReturnType.Body).InstanceType().Name; - } - return "Void"; + return ReturnTypeModel.BodyWireType.InstanceType().Name; } } @@ -510,32 +506,17 @@ public virtual string TypeTokenType(ITypeModel type) return type.InstanceType().Name; } - public string OperationResponseType - { - get - { - if (ReturnType.Headers == null) - { - return "ServiceResponse"; - } - else - { - return "ServiceResponseWithHeaders"; - } - } - } - public string OperationResponseReturnTypeString { get { - if (ReturnType.Headers == null) + if (ReturnTypeModel.Headers == null) { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", OperationResponseType, GenericReturnTypeString); + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ReturnTypeModel.OperationResponseType, GenericReturnTypeString); } else { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", OperationResponseType, GenericReturnTypeString, ReturnType.Headers.Name); + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ReturnTypeModel.OperationResponseType, GenericReturnTypeString, ReturnType.Headers.Name); } } } @@ -546,11 +527,11 @@ public virtual string DelegateOperationResponseReturnTypeString { if (ReturnType.Headers == null) { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", OperationResponseType, DelegateReturnTypeString); + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ReturnTypeModel.OperationResponseType, DelegateReturnTypeString); } else { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", OperationResponseType, DelegateReturnTypeString, ReturnType.Headers.Name); + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ReturnTypeModel.OperationResponseType, DelegateReturnTypeString, ReturnType.Headers.Name); } } } @@ -674,7 +655,7 @@ public virtual List InterfaceImports HashSet imports = new HashSet(); // static imports imports.Add("com.microsoft.rest.ServiceCall"); - imports.Add("com.microsoft.rest." + OperationResponseType); + imports.Add("com.microsoft.rest." + ReturnTypeModel.OperationResponseType); imports.Add("com.microsoft.rest.ServiceCallback"); // parameter types this.ParameterModels.ForEach(p => imports.AddRange(p.InterfaceImports)); @@ -712,7 +693,7 @@ public virtual List ImplImports imports.Add("okhttp3.ResponseBody"); } imports.Add("com.microsoft.rest.ServiceCall"); - imports.Add("com.microsoft.rest." + OperationResponseType); + imports.Add("com.microsoft.rest." + ReturnTypeModel.OperationResponseType); imports.Add(RuntimeBasePackage + "." + ResponseBuilder); imports.Add("com.microsoft.rest.ServiceCallback"); this.RetrofitParameters.ForEach(p => imports.AddRange(p.RetrofitImports)); diff --git a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml index fbc6a1d9a99f7..4f1204572fb41 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml @@ -27,11 +27,11 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. } */ @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString; @@ -77,11 +77,11 @@ ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationWithCall } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. } */ @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString; diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index c9aab9ef9e4b3..85a6874e1793b 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -27,11 +27,11 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. } */ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { @@ -162,11 +162,11 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. } */ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs index 3ce41e2c9cecb..57bb9761275d1 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -151,6 +151,21 @@ public IEnumerable ImplImports } } + public string OperationResponseType + { + get + { + if (Headers == null) + { + return "ServiceResponse"; + } + else + { + return "ServiceResponseWithHeaders"; + } + } + } + private string converToClientType(IType type, string reference) { if (type == null) From 5dfaf9bd6a384a4aa4443b882da9079ac238b155 Mon Sep 17 00:00:00 2001 From: Laurent Mazuel Date: Thu, 24 Mar 2016 09:53:57 -0700 Subject: [PATCH 32/99] Explicit comment as a temp workaround --- ClientRuntimes/Python/msrest/msrest/serialization.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index f68ca6adb6980..18254317e58e2 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -851,6 +851,8 @@ def deserialize_enum(self, data, enum_obj): :raises: DeserializationError if string is not valid enum value. """ if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] except IndexError: From 05a7ebc93d25172e481c07263e6f4f4431e40c89 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Thu, 24 Mar 2016 11:12:23 -0700 Subject: [PATCH 33/99] Let Response model handle client type string --- .../fixtures/head/HttpSuccessOperations.java | 6 +- .../head/HttpSuccessOperationsImpl.java | 6 +- .../AzureMethodTemplateModel.cs | 37 ++++++------ .../Templates/AzureMethodTemplate.cshtml | 4 +- .../TypeModels/AzureResponseModel.cs | 25 +++++++-- .../fixtures/bodyboolean/BoolOperations.java | 8 +-- .../bodyboolean/BoolOperationsImpl.java | 8 +-- .../fixtures/bodyinteger/IntOperations.java | 12 ++-- .../bodyinteger/IntOperationsImpl.java | 12 ++-- .../fixtures/bodynumber/NumberOperations.java | 18 +++--- .../bodynumber/NumberOperationsImpl.java | 18 +++--- .../fixtures/http/HttpFailureOperations.java | 4 +- .../http/HttpFailureOperationsImpl.java | 4 +- .../fixtures/http/HttpSuccessOperations.java | 2 +- .../http/HttpSuccessOperationsImpl.java | 2 +- .../TemplateModels/MethodTemplateModel.cs | 43 +++----------- .../Templates/MethodInterfaceTemplate.cshtml | 4 +- .../Java/Java/Templates/MethodTemplate.cshtml | 4 +- .../Java/Java/TypeModels/ResponseModel.cs | 56 +++++++++++++------ 19 files changed, 141 insertions(+), 132 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java index a7faf0d1d9b85..7ca9a529752e3 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java @@ -26,7 +26,7 @@ public interface HttpSuccessOperations { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse head200() throws CloudException, IOException; @@ -44,7 +44,7 @@ public interface HttpSuccessOperations { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse head204() throws CloudException, IOException; @@ -62,7 +62,7 @@ public interface HttpSuccessOperations { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse head404() throws CloudException, IOException; diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java index 7848477599c2a..b3f31dbd8a2c2 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java @@ -70,7 +70,7 @@ interface HttpSuccessService { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse head200() throws CloudException, IOException { Call call = service.head200(this.client.getAcceptLanguage()); @@ -116,7 +116,7 @@ private ServiceResponse head200Delegate(Response response) throws * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse head204() throws CloudException, IOException { Call call = service.head204(this.client.getAcceptLanguage()); @@ -162,7 +162,7 @@ private ServiceResponse head204Delegate(Response response) throws * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse head404() throws CloudException, IOException { Call call = service.head404(this.client.getAcceptLanguage()); diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 741a443ed4e79..51a3e26e76ee0 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -15,6 +15,8 @@ namespace Microsoft.Rest.Generator.Java.Azure { public class AzureMethodTemplateModel : MethodTemplateModel { + private AzureResponseModel _returnTypeModel; + public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) : base(source, serviceClient) { @@ -25,12 +27,21 @@ public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source); this.RequestIdString = AzureExtensions.GetRequestIdString(source); + _returnTypeModel = new AzureResponseModel(ReturnType, this); } public string ClientRequestIdString { get; private set; } public string RequestIdString { get; private set; } + public override ResponseModel ReturnTypeModel + { + get + { + return _returnTypeModel; + } + } + /// /// Returns true if method has x-ms-long-running-operation extension. /// @@ -153,7 +164,7 @@ public override string MethodParameterDeclarationWithCallback } else { - parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", GenericReturnTypeString); + parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", ReturnTypeModel.GenericBodyClientTypeString); } return parameters; @@ -183,7 +194,7 @@ public override string MethodRequiredParameterDeclarationWithCallback } else { - parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", GenericReturnTypeString); + parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", ReturnTypeModel.GenericBodyClientTypeString); } return parameters; @@ -257,10 +268,10 @@ public string PollingResourceTypeArgs { get { - string args = "new TypeToken<" + GenericReturnTypeString + ">() { }.getType()"; + string args = "new TypeToken<" + ReturnTypeModel.GenericBodyClientTypeString + ">() { }.getType()"; if (ReturnType.Headers != null) { - args += ", " + ReturnType.Headers.Name + ".class"; + args += ", " + ReturnTypeModel.HeaderWireType + ".class"; } return args; } @@ -494,22 +505,6 @@ public override string TypeTokenType(ITypeModel type) return base.TypeTokenType(type); } - public override string GenericReturnTypeString - { - get - { - if (ReturnType.Body is SequenceType && this.IsPagingNextOperation) - { - return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", ((SequenceType)ReturnType.Body).ElementType); - } - else if (ReturnType.Body is SequenceType && this.IsPagingOperation) - { - return string.Format(CultureInfo.InvariantCulture, "PagedList<{0}>", ((SequenceType)ReturnType.Body).ElementType); - } - return base.GenericReturnTypeString; - } - } - public override string CallbackGenericTypeString { get @@ -517,7 +512,7 @@ public override string CallbackGenericTypeString if (ReturnType.Body is SequenceType && (this.IsPagingOperation || this.IsPagingNextOperation)) { - return base.GenericReturnTypeString; + return base.ReturnTypeModel.GenericBodyClientTypeString; } return base.CallbackGenericTypeString; } diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index 8d16e6c5c5996..b8f66301cdbb8 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -37,7 +37,7 @@ if (Model.LocalParameters.Any(p => !p.IsConstant && !p.IsRequired)) } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. } else { @@ -157,7 +157,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. } else { diff --git a/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs index ebfb24f2503fc..004db936204d2 100644 --- a/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs @@ -12,17 +12,34 @@ namespace Microsoft.Rest.Generator.Java.Azure { public class AzureResponseModel : ResponseModel { - private Response _response; + private AzureMethodTemplateModel _method; - public AzureResponseModel(Response response) + public AzureResponseModel(Response response, AzureMethodTemplateModel method) : base (response) { this._response = response; + this._method = method; } - public AzureResponseModel(ITypeModel body, ITypeModel headers) - : this(new Response(body, headers)) + public AzureResponseModel(ITypeModel body, ITypeModel headers, AzureMethodTemplateModel method) + : this(new Response(body, headers), method) { } + + public override string GenericBodyClientTypeString + { + get + { + if (BodyClientType is SequenceType && _method.IsPagingNextOperation) + { + return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", ((SequenceType)BodyClientType).ElementType); + } + else if (BodyClientType is SequenceType && _method.IsPagingOperation) + { + return string.Format(CultureInfo.InvariantCulture, "PagedList<{0}>", ((SequenceType)BodyClientType).ElementType); + } + return base.GenericBodyClientTypeString; + } + } } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java index 9630dce2205bf..15e2e11de56bd 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java @@ -26,7 +26,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getTrue() throws ErrorException, IOException; @@ -64,7 +64,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getFalse() throws ErrorException, IOException; @@ -102,7 +102,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -120,7 +120,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalid() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java index 756d569f7489a..5c3107666e0bc 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java @@ -84,7 +84,7 @@ interface BoolService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getTrue() throws ErrorException, IOException { Call call = service.getTrue(); @@ -176,7 +176,7 @@ private ServiceResponse putTrueDelegate(Response response) t * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getFalse() throws ErrorException, IOException { Call call = service.getFalse(); @@ -268,7 +268,7 @@ private ServiceResponse putFalseDelegate(Response response) * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -313,7 +313,7 @@ private ServiceResponse getNullDelegate(Response response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalid() throws ErrorException, IOException { Call call = service.getInvalid(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java index aee8ce76f60ef..2f705c55d8129 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java @@ -26,7 +26,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -44,7 +44,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalid() throws ErrorException, IOException; @@ -62,7 +62,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getOverflowInt32() throws ErrorException, IOException; @@ -80,7 +80,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUnderflowInt32() throws ErrorException, IOException; @@ -98,7 +98,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Long object wrapped in {@link ServiceResponse} if successful. + * @return the long object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getOverflowInt64() throws ErrorException, IOException; @@ -116,7 +116,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Long object wrapped in {@link ServiceResponse} if successful. + * @return the long object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUnderflowInt64() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java index 9074eb6cbbf90..8e9325c0caf42 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java @@ -100,7 +100,7 @@ interface IntService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -145,7 +145,7 @@ private ServiceResponse getNullDelegate(Response response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalid() throws ErrorException, IOException { Call call = service.getInvalid(); @@ -190,7 +190,7 @@ private ServiceResponse getInvalidDelegate(Response respo * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getOverflowInt32() throws ErrorException, IOException { Call call = service.getOverflowInt32(); @@ -235,7 +235,7 @@ private ServiceResponse getOverflowInt32Delegate(Response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUnderflowInt32() throws ErrorException, IOException { Call call = service.getUnderflowInt32(); @@ -280,7 +280,7 @@ private ServiceResponse getUnderflowInt32Delegate(Response getOverflowInt64() throws ErrorException, IOException { Call call = service.getOverflowInt64(); @@ -325,7 +325,7 @@ private ServiceResponse getOverflowInt64Delegate(Response re * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Long object wrapped in {@link ServiceResponse} if successful. + * @return the long object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUnderflowInt64() throws ErrorException, IOException { Call call = service.getUnderflowInt64(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java index ad3036ecd7b7b..d12b81146b25f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java @@ -27,7 +27,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -45,7 +45,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalidFloat() throws ErrorException, IOException; @@ -63,7 +63,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalidDouble() throws ErrorException, IOException; @@ -119,7 +119,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigFloat() throws ErrorException, IOException; @@ -157,7 +157,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigDouble() throws ErrorException, IOException; @@ -195,7 +195,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigDoublePositiveDecimal() throws ErrorException, IOException; @@ -233,7 +233,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigDoubleNegativeDecimal() throws ErrorException, IOException; @@ -388,7 +388,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getSmallFloat() throws ErrorException, IOException; @@ -426,7 +426,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getSmallDouble() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java index 4e73af2346ed6..63b156894fe55 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java @@ -157,7 +157,7 @@ interface NumberService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -202,7 +202,7 @@ private ServiceResponse getNullDelegate(Response response) * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalidFloat() throws ErrorException, IOException { Call call = service.getInvalidFloat(); @@ -247,7 +247,7 @@ private ServiceResponse getInvalidFloatDelegate(Response r * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalidDouble() throws ErrorException, IOException { Call call = service.getInvalidDouble(); @@ -384,7 +384,7 @@ private ServiceResponse putBigFloatDelegate(Response respons * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getBigFloat() throws ErrorException, IOException { Call call = service.getBigFloat(); @@ -476,7 +476,7 @@ private ServiceResponse putBigDoubleDelegate(Response respon * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getBigDouble() throws ErrorException, IOException { Call call = service.getBigDouble(); @@ -568,7 +568,7 @@ private ServiceResponse putBigDoublePositiveDecimalDelegate(Response getBigDoublePositiveDecimal() throws ErrorException, IOException { Call call = service.getBigDoublePositiveDecimal(); @@ -660,7 +660,7 @@ private ServiceResponse putBigDoubleNegativeDecimalDelegate(Response getBigDoubleNegativeDecimal() throws ErrorException, IOException { Call call = service.getBigDoubleNegativeDecimal(); @@ -1052,7 +1052,7 @@ private ServiceResponse putSmallFloatDelegate(Response respo * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getSmallFloat() throws ErrorException, IOException { Call call = service.getSmallFloat(); @@ -1144,7 +1144,7 @@ private ServiceResponse putSmallDoubleDelegate(Response resp * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getSmallDouble() throws ErrorException, IOException { Call call = service.getSmallDouble(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java index 2b77460dcacfb..b5db0e90d14de 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java @@ -27,7 +27,7 @@ public interface HttpFailureOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getEmptyError() throws ErrorException, IOException; @@ -45,7 +45,7 @@ public interface HttpFailureOperations { * * @throws ServiceException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNoModelError() throws ServiceException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java index e704f8bcfbf15..9ee5a909d873c 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java @@ -67,7 +67,7 @@ interface HttpFailureService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getEmptyError() throws ErrorException, IOException { Call call = service.getEmptyError(); @@ -112,7 +112,7 @@ private ServiceResponse getEmptyErrorDelegate(Response re * * @throws ServiceException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNoModelError() throws ServiceException, IOException { Call call = service.getNoModelError(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java index a6a6fbcb5beff..f47159a00177d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java @@ -44,7 +44,7 @@ public interface HttpSuccessOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse get200() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java index 792e759ec66f9..09ab15c84944e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java @@ -182,7 +182,7 @@ private ServiceResponse head200Delegate(Response response) throws Er * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse get200() throws ErrorException, IOException { Call call = service.get200(); diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index cc9f96205b287..4f27236357f71 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -52,7 +52,7 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) public List LogicalParameterModels { get; private set; } - public ResponseModel ReturnTypeModel + public virtual ResponseModel ReturnTypeModel { get { @@ -346,7 +346,7 @@ public virtual string MethodParameterDeclarationWithCallback parameters += ", "; } parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - GenericReturnTypeString); + ReturnTypeModel.GenericBodyClientTypeString); return parameters; } } @@ -361,7 +361,7 @@ public virtual string MethodRequiredParameterDeclarationWithCallback parameters += ", "; } parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - GenericReturnTypeString); + ReturnTypeModel.GenericBodyClientTypeString); return parameters; } } @@ -458,38 +458,11 @@ public virtual List ExceptionStatements } } - /// - /// Get the type name for the method's return type - /// - public string ReturnTypeString - { - get - { - if (ReturnType.Body != null) - { - return ((ITypeModel)ReturnType.Body).InstanceType().ResponseVariant; - } - return "void"; - } - } - - public virtual string GenericReturnTypeString - { - get - { - if (ReturnType.Body != null) - { - return ((ITypeModel) ReturnType.Body).InstanceType().ResponseVariant; - } - return "Void"; - } - } - public virtual string CallbackGenericTypeString { get { - return GenericReturnTypeString; + return ReturnTypeModel.GenericBodyClientTypeString; } } @@ -512,11 +485,11 @@ public string OperationResponseReturnTypeString { if (ReturnTypeModel.Headers == null) { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ReturnTypeModel.OperationResponseType, GenericReturnTypeString); + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ReturnTypeModel.OperationResponseType, ReturnTypeModel.GenericBodyClientTypeString); } else { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ReturnTypeModel.OperationResponseType, GenericReturnTypeString, ReturnType.Headers.Name); + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ReturnTypeModel.OperationResponseType, ReturnTypeModel.GenericBodyClientTypeString, ReturnTypeModel.GenericHeaderClientTypeString); } } } @@ -607,7 +580,7 @@ public virtual string ReturnValue { if (ReturnTypeModel.NeedsConversion) { - return "new ServiceResponse<" + this.GenericReturnTypeString + ">(body, response.getResponse())"; + return "new ServiceResponse<" + ReturnTypeModel.GenericBodyClientTypeString + ">(body, response.getResponse())"; } return this.Name + "Delegate(call.execute())"; } @@ -625,7 +598,7 @@ public virtual string SuccessCallback .AppendLine("if (result.getBody() != null) {") .Indent().AppendLine("body = {0};", ReturnTypeModel.ConvertBodyToClientType("result.getBody()")) .Outdent().AppendLine("}"); - builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", GenericReturnTypeString); + builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", ReturnTypeModel.GenericBodyClientTypeString); return builder.ToString(); } return string.Format(CultureInfo.InvariantCulture, "serviceCallback.success({0}Delegate(response));", this.Name); diff --git a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml index 4f1204572fb41..c1cbaed69ebfd 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml @@ -27,7 +27,7 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { @@ -77,7 +77,7 @@ ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationWithCall } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index 85a6874e1793b..d01b23893df4b 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -27,7 +27,7 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { @@ -162,7 +162,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. } else { diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs index 57bb9761275d1..cc111ad6bf16c 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -12,7 +12,7 @@ namespace Microsoft.Rest.Generator.Java { public class ResponseModel { - private Response _response; + protected Response _response; public ResponseModel(Response response) { @@ -24,6 +24,8 @@ public ResponseModel(ITypeModel body, ITypeModel headers) { } + #region types + public ITypeModel Body { get @@ -132,6 +134,43 @@ public string ConvertHeaderToClientType(string reference) return converToClientType(Headers, reference); } + #endregion + + #region template strings + + public string OperationResponseType + { + get + { + if (Headers == null) + { + return "ServiceResponse"; + } + else + { + return "ServiceResponseWithHeaders"; + } + } + } + + public virtual string GenericBodyClientTypeString + { + get + { + return BodyClientType.InstanceType().Name; + } + } + + public virtual string GenericHeaderClientTypeString + { + get + { + return HeaderClientType.InstanceType().Name; + } + } + + #endregion + public IEnumerable InterfaceImports { get @@ -151,21 +190,6 @@ public IEnumerable ImplImports } } - public string OperationResponseType - { - get - { - if (Headers == null) - { - return "ServiceResponse"; - } - else - { - return "ServiceResponseWithHeaders"; - } - } - } - private string converToClientType(IType type, string reference) { if (type == null) From 83c82919b33b396f8631ded717b7211bfa288e91 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Thu, 24 Mar 2016 11:49:16 -0700 Subject: [PATCH 34/99] Move all string templates to ResponseModel --- .../AzureMethodTemplateModel.cs | 60 ++++++++----------- .../Templates/AzureMethodTemplate.cshtml | 12 ++-- .../TypeModels/AzureResponseModel.cs | 33 ++++++++++ .../TemplateModels/MethodTemplateModel.cs | 55 ++--------------- .../Templates/MethodInterfaceTemplate.cshtml | 12 ++-- .../Java/Java/Templates/MethodTemplate.cshtml | 22 +++---- .../Java/Java/TypeModels/ResponseModel.cs | 56 ++++++++++++++++- 7 files changed, 142 insertions(+), 108 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 51a3e26e76ee0..6d617948766f3 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -10,12 +10,14 @@ using Microsoft.Rest.Generator.Java.Azure.Properties; using Microsoft.Rest.Generator.Java.TemplateModels; using Microsoft.Rest.Generator.Utilities; +using System.Net; namespace Microsoft.Rest.Generator.Java.Azure { public class AzureMethodTemplateModel : MethodTemplateModel { private AzureResponseModel _returnTypeModel; + private Dictionary _responseModels; public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) : base(source, serviceClient) @@ -28,6 +30,8 @@ public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source); this.RequestIdString = AzureExtensions.GetRequestIdString(source); _returnTypeModel = new AzureResponseModel(ReturnType, this); + _responseModels = new Dictionary(); + Responses.ForEach(r => _responseModels.Add(r.Key, new AzureResponseModel(r.Value, this))); } public string ClientRequestIdString { get; private set; } @@ -42,6 +46,14 @@ public override ResponseModel ReturnTypeModel } } + public override Dictionary ResponseModels + { + get + { + return _responseModels; + } + } + /// /// Returns true if method has x-ms-long-running-operation extension. /// @@ -293,7 +305,7 @@ public override string ResponseGeneration { var builder = new IndentedStringBuilder(); builder.AppendLine("{0} response = {1}Delegate(call.execute());", - this.DelegateOperationResponseReturnTypeString, this.Name); + ReturnTypeModel.WireResponseTypeString, this.Name); string invocation; AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation); @@ -314,7 +326,7 @@ public override string ResponseGeneration { var builder = new IndentedStringBuilder(); builder.AppendLine("{0}> response = {2}Delegate(call.execute());", - ReturnTypeModel.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); builder.AppendLine("{0} result = response.getBody().getItems();", this.ReturnType.Body.Name); return builder.ToString(); } @@ -334,12 +346,12 @@ public override string ReturnValue if (ReturnType.Headers != null) { return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.getHeaders(), response.getResponse())", - ReturnTypeModel.OperationResponseType); + ReturnTypeModel.ClientResponseType); } else { return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.getResponse())", - ReturnTypeModel.OperationResponseType); + ReturnTypeModel.ClientResponseType); } } else @@ -357,7 +369,7 @@ public override string SuccessCallback { var builder = new IndentedStringBuilder(); builder.AppendLine("{0} result = {1}Delegate(response);", - this.DelegateOperationResponseReturnTypeString, this.Name); + ReturnTypeModel.WireResponseTypeString, this.Name); builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent() .AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); @@ -371,11 +383,11 @@ public override string SuccessCallback builder.AppendLine("} else {").Indent(); if (ReturnType.Headers == null) { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } else { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } builder.Outdent().AppendLine("}"); return builder.ToString(); @@ -383,7 +395,7 @@ public override string SuccessCallback else if (this.IsPagingNextOperation) { var builder = new IndentedStringBuilder(); - builder.AppendLine("{0} result = {1}Delegate(response);", this.DelegateOperationResponseReturnTypeString, this.Name); + builder.AppendLine("{0} result = {1}Delegate(response);", ReturnTypeModel.WireResponseTypeString, this.Name); builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent(); builder.AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); @@ -394,11 +406,11 @@ public override string SuccessCallback builder.AppendLine("} else {").Indent(); if (ReturnType.Headers == null) { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } else { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } builder.Outdent().AppendLine("}"); return builder.ToString(); @@ -407,14 +419,14 @@ public override string SuccessCallback { var builder = new IndentedStringBuilder(); builder.AppendLine("{0}> result = {2}Delegate(response);", - ReturnTypeModel.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); if (ReturnType.Headers == null) { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", ReturnTypeModel.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } else { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.OperationResponseType); + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } return builder.ToString(); } @@ -483,28 +495,6 @@ private void TransformPagingGroupedParameter(IndentedStringBuilder builder, Azur } } - public override string DelegateReturnTypeString - { - get - { - if (this.IsPagingOperation || this.IsPagingNextOperation || this.IsPagingNonPollingOperation) - { - return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", ((SequenceType)ReturnType.Body).ElementType); - } - return base.DelegateReturnTypeString; - } - } - - public override string TypeTokenType(ITypeModel type) - { - SequenceTypeModel sequenceType = type as SequenceTypeModel; - if (sequenceType != null && (this.IsPagingOperation || this.IsPagingNextOperation || this.IsPagingNonPollingOperation)) - { - return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", sequenceType.ElementTypeModel.InstanceType()); - } - return base.TypeTokenType(type); - } - public override string CallbackGenericTypeString { get diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index b8f66301cdbb8..f2648e60c8fe6 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -37,14 +37,14 @@ if (Model.LocalParameters.Any(p => !p.IsConstant && !p.IsRequired)) } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.ClientResponseType if successful. } else { -@: * @@return the @Model.ReturnTypeModel.OperationResponseType object if successful. +@: * @@return the @Model.ReturnTypeModel.ClientResponseType object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { @@ -157,14 +157,14 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.ClientResponseType if successful. } else { -@: * @@return the @Model.ReturnTypeModel.OperationResponseType object if successful. +@: * @@return the @Model.ReturnTypeModel.ClientResponseType object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { diff --git a/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs index 004db936204d2..9195830021b21 100644 --- a/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs @@ -41,5 +41,38 @@ public override string GenericBodyClientTypeString return base.GenericBodyClientTypeString; } } + + public override string GenericBodyWireTypeString + { + get + { + SequenceTypeModel sequenceType = BodyWireType as SequenceTypeModel; + if (sequenceType != null && (_method.IsPagingOperation || _method.IsPagingNextOperation || _method.IsPagingNonPollingOperation)) + { + return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", sequenceType.ElementTypeModel.InstanceType()); + } + return base.GenericBodyWireTypeString; + } + } + public override string ClientCallbackTypeString + { + get + { + if (Body is SequenceType && + (_method.IsPagingOperation || _method.IsPagingNextOperation)) + { + return BodyClientType.InstanceType().Name; + } + return base.ClientCallbackTypeString; + } + } + + public override string GenericHeaderWireTypeString + { + get + { + return HeaderWireType.InstanceType().Name; + } + } } } diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 4f27236357f71..1bf4b1cdddf58 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -60,7 +60,7 @@ public virtual ResponseModel ReturnTypeModel } } - public Dictionary ResponseModels + public virtual Dictionary ResponseModels { get { @@ -466,49 +466,6 @@ public virtual string CallbackGenericTypeString } } - public virtual string DelegateReturnTypeString - { - get - { - return ReturnTypeModel.BodyWireType.InstanceType().Name; - } - } - - public virtual string TypeTokenType(ITypeModel type) - { - return type.InstanceType().Name; - } - - public string OperationResponseReturnTypeString - { - get - { - if (ReturnTypeModel.Headers == null) - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ReturnTypeModel.OperationResponseType, ReturnTypeModel.GenericBodyClientTypeString); - } - else - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ReturnTypeModel.OperationResponseType, ReturnTypeModel.GenericBodyClientTypeString, ReturnTypeModel.GenericHeaderClientTypeString); - } - } - } - - public virtual string DelegateOperationResponseReturnTypeString - { - get - { - if (ReturnType.Headers == null) - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ReturnTypeModel.OperationResponseType, DelegateReturnTypeString); - } - else - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ReturnTypeModel.OperationResponseType, DelegateReturnTypeString, ReturnType.Headers.Name); - } - } - } - public string CallType { get @@ -563,8 +520,8 @@ public virtual string ResponseGeneration { IndentedStringBuilder builder= new IndentedStringBuilder(); builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());", - DelegateReturnTypeString, this.Name.ToCamelCase()); - builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) + ReturnTypeModel.GenericBodyWireTypeString, this.Name.ToCamelCase()); + builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType.Name) .AppendLine("if (response.getBody() != null) {") .Indent().AppendLine("body = {0};", ReturnTypeModel.ConvertBodyToClientType("response.getBody()")) .Outdent().AppendLine("}"); @@ -593,7 +550,7 @@ public virtual string SuccessCallback if (ReturnTypeModel.NeedsConversion) { IndentedStringBuilder builder = new IndentedStringBuilder(); - builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", DelegateReturnTypeString, this.Name); + builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeModel.GenericBodyWireTypeString, this.Name); builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) .AppendLine("if (result.getBody() != null) {") .Indent().AppendLine("body = {0};", ReturnTypeModel.ConvertBodyToClientType("result.getBody()")) @@ -628,7 +585,7 @@ public virtual List InterfaceImports HashSet imports = new HashSet(); // static imports imports.Add("com.microsoft.rest.ServiceCall"); - imports.Add("com.microsoft.rest." + ReturnTypeModel.OperationResponseType); + imports.Add("com.microsoft.rest." + ReturnTypeModel.ClientResponseType); imports.Add("com.microsoft.rest.ServiceCallback"); // parameter types this.ParameterModels.ForEach(p => imports.AddRange(p.InterfaceImports)); @@ -666,7 +623,7 @@ public virtual List ImplImports imports.Add("okhttp3.ResponseBody"); } imports.Add("com.microsoft.rest.ServiceCall"); - imports.Add("com.microsoft.rest." + ReturnTypeModel.OperationResponseType); + imports.Add("com.microsoft.rest." + ReturnTypeModel.ClientResponseType); imports.Add(RuntimeBasePackage + "." + ResponseBuilder); imports.Add("com.microsoft.rest.ServiceCallback"); this.RetrofitParameters.ForEach(p => imports.AddRange(p.RetrofitImports)); diff --git a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml index c1cbaed69ebfd..b2379b5e0115e 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml @@ -27,14 +27,14 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -@Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString; +@Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString; @EmptyLine /** @if (!string.IsNullOrEmpty(Model.Summary)) @@ -77,14 +77,14 @@ ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationWithCall } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -@Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString; +@Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString; @EmptyLine /** @if (!string.IsNullOrEmpty(Model.Summary)) diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index d01b23893df4b..bf299b19a9f95 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -27,14 +27,14 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { @@ -127,7 +127,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host } Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); @Model.ServiceCallConstruction - call.enqueue(new @Model.InternalCallback<@(Model.CallbackGenericTypeString)>(serviceCallback) { + call.enqueue(new @Model.InternalCallback<@(Model.ReturnTypeModel.ClientCallbackTypeString)>(serviceCallback) { @@Override public void onResponse(Call<@Model.CallType> call, Response<@Model.CallType> response) { try { @@ -162,14 +162,14 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.ReturnTypeModel.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { @@ -253,7 +253,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host } Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); @Model.ServiceCallConstruction - call.enqueue(new @Model.InternalCallback<@(Model.CallbackGenericTypeString)>(serviceCallback) { + call.enqueue(new @Model.InternalCallback<@(Model.ReturnTypeModel.ClientCallbackTypeString)>(serviceCallback) { @@Override public void onResponse(Call<@Model.CallType> call, Response<@Model.CallType> response) { try { @@ -266,12 +266,12 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host return serviceCall; } @EmptyLine -private @Model.DelegateOperationResponseReturnTypeString @(Model.Name)Delegate(Response<@Model.CallType> response) throws @Model.ExceptionString { - return new @Model.ResponseBuilder<@Model.DelegateReturnTypeString, @Model.OperationExceptionTypeString>(@(Model.ClientReference).getMapperAdapter()) +private @Model.ReturnTypeModel.WireResponseTypeString @(Model.Name)Delegate(Response<@Model.CallType> response) throws @Model.ExceptionString { + return new @Model.ResponseBuilder<@Model.ReturnTypeModel.GenericBodyWireTypeString, @Model.OperationExceptionTypeString>(@(Model.ClientReference).getMapperAdapter()) @foreach (var response in Model.ResponseModels) { - @:.register(@((int)response.Key), new TypeToken<@Model.TypeTokenType(response.Value.BodyWireType)>() { }.getType()) + @:.register(@((int)response.Key), new TypeToken<@response.Value.GenericBodyWireTypeString>() { }.getType()) } @if (Model.DefaultResponse.Body != null) { diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs index cc111ad6bf16c..9580933998522 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -138,7 +138,7 @@ public string ConvertHeaderToClientType(string reference) #region template strings - public string OperationResponseType + public string ClientResponseType { get { @@ -153,6 +153,44 @@ public string OperationResponseType } } + public string ClientResponseTypeString + { + get + { + if (Headers == null) + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ClientResponseType, GenericBodyClientTypeString); + } + else + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ClientResponseType, GenericBodyClientTypeString, GenericHeaderClientTypeString); + } + } + } + + public virtual string ClientCallbackTypeString + { + get + { + return GenericBodyClientTypeString; + } + } + + public string WireResponseTypeString + { + get + { + if (Headers == null) + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ClientResponseType, GenericBodyWireTypeString); + } + else + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ClientResponseType, GenericBodyWireTypeString, GenericHeaderWireTypeString); + } + } + } + public virtual string GenericBodyClientTypeString { get @@ -169,6 +207,22 @@ public virtual string GenericHeaderClientTypeString } } + public virtual string GenericBodyWireTypeString + { + get + { + return BodyWireType.InstanceType().Name; + } + } + + public virtual string GenericHeaderWireTypeString + { + get + { + return HeaderWireType.InstanceType().Name; + } + } + #endregion public IEnumerable InterfaceImports From d824238cfe548217a2648973938650824d5da9b3 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Thu, 24 Mar 2016 12:03:47 -0700 Subject: [PATCH 35/99] Address code analysis errors --- .../Java/Azure.Java/GlobalSuppressions.cs | 4 ++++ .../AzureMethodTemplateModel.cs | 13 ------------ .../Java/Java/GlobalSuppressions.cs | 20 +++++++++++++++++++ .../TemplateModels/MethodTemplateModel.cs | 10 +--------- 4 files changed, 25 insertions(+), 22 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs index 01fefddaea2f7..fe0a68ed70c54 100644 --- a/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs @@ -39,3 +39,7 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceCallback", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureJavaCodeNamer.#ImportType(Microsoft.Rest.Generator.ClientModel.IType,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureJavaCodeNamer.#ImportType(Microsoft.Rest.Generator.ClientModel.IType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureCompositeTypeModel.#_azureRuntimePackage")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureCompositeTypeModel.#.ctor(Microsoft.Rest.Generator.Java.CompositeTypeModel)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureJavaCodeGenerator.#.ctor(Microsoft.Rest.Generator.Settings)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureModelTemplateModel.#.ctor(Microsoft.Rest.Generator.ClientModel.CompositeType,Microsoft.Rest.Generator.ClientModel.ServiceClient)")] diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 6d617948766f3..ce89f3e81498d 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -495,19 +495,6 @@ private void TransformPagingGroupedParameter(IndentedStringBuilder builder, Azur } } - public override string CallbackGenericTypeString - { - get - { - if (ReturnType.Body is SequenceType && - (this.IsPagingOperation || this.IsPagingNextOperation)) - { - return base.ReturnTypeModel.GenericBodyClientTypeString; - } - return base.CallbackGenericTypeString; - } - } - public override string ServiceCallConstruction { get diff --git a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs index 061a6e9f8b865..6e21099c380ef 100644 --- a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs @@ -144,3 +144,23 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getDateTime", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DateTime", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#converToClientType(Microsoft.Rest.Generator.ClientModel.IType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#_package")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#_runtimePackage")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.EnumTypeModel.#.ctor(Microsoft.Rest.Generator.ClientModel.EnumType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.EnumTypeModel.#.ctor(Microsoft.Rest.Generator.ClientModel.EnumType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Imports", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ITypeModel.#Imports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeGenerator.#.ctor(Microsoft.Rest.Generator.Settings)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#_package")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#NormalizeTypeReference(Microsoft.Rest.Generator.ClientModel.IType)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#NormalizeCompositeType(Microsoft.Rest.Generator.ClientModel.CompositeType)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ParameterModels")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#LogicalParameterModels")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ModelTemplateModel.#.ctor(Microsoft.Rest.Generator.ClientModel.CompositeType,Microsoft.Rest.Generator.ClientModel.ServiceClient)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#LocationImport(Microsoft.Rest.Generator.ClientModel.ParameterLocation)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#NeedsSpecialSerialization(Microsoft.Rest.Generator.ClientModel.IType)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_response")] diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 1bf4b1cdddf58..65f2418aebe51 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -458,14 +458,6 @@ public virtual List ExceptionStatements } } - public virtual string CallbackGenericTypeString - { - get - { - return ReturnTypeModel.GenericBodyClientTypeString; - } - } - public string CallType { get @@ -648,7 +640,7 @@ public virtual List ImplImports { imports.Add("com.microsoft.rest.ServiceResponseCallback"); } - // parameter utils + // parameters this.LocalParameters.Concat(this.LogicalParameterModels) .ForEach(p => imports.AddRange(p.ImplImports)); // return type From 3b3b14eb7f39360ae90d076fa3d9ec2afb1c0209 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 24 Mar 2016 15:59:03 -0700 Subject: [PATCH 36/99] pusblished 1.12.0 version of ms-rest and ms-rest-azure --- .../NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs | 2 +- AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs | 2 +- ClientRuntimes/NodeJS/ms-rest-azure/package.json | 4 ++-- ClientRuntimes/NodeJS/ms-rest/package.json | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs b/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs index cddd7a2adba46..ac8eea6fb028a 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs @@ -18,7 +18,7 @@ namespace Microsoft.Rest.Generator.Azure.NodeJS { public class AzureNodeJSCodeGenerator : NodeJSCodeGenerator { - private const string ClientRuntimePackage = "ms-rest-azure version 1.10.0"; + private const string ClientRuntimePackage = "ms-rest-azure version 1.12.0"; // List of models with paging extensions. private IList pageModels; diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs index bdc9153f1ca06..04bacdaeb59b0 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs @@ -16,7 +16,7 @@ namespace Microsoft.Rest.Generator.NodeJS { public class NodeJSCodeGenerator : CodeGenerator { - private const string ClientRuntimePackage = "ms-rest version 1.10.0"; + private const string ClientRuntimePackage = "ms-rest version 1.12.0"; public NodeJsCodeNamer Namer { get; private set; } diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/package.json b/ClientRuntimes/NodeJS/ms-rest-azure/package.json index da011dad01070..0cb2731447104 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/package.json +++ b/ClientRuntimes/NodeJS/ms-rest-azure/package.json @@ -5,7 +5,7 @@ "email": "azsdkteam@microsoft.com", "url": "https://github.com/Azure/AutoRest" }, - "version": "1.11.0", + "version": "1.12.0", "description": "Client Runtime for Node.js Azure client libraries generated using AutoRest", "tags": [ "node", "microsoft", "autorest", "azure", "clientruntime" ], "keywords": [ "node", "microsoft", "autorest", "azure", "clientruntime" ], @@ -23,7 +23,7 @@ "async": "0.2.7", "uuid": "2.0.1", "adal-node": "0.1.17", - "ms-rest": "^1.11.0", + "ms-rest": "^1.12.0", "underscore": "^1.4.0", "moment": "^2.6.0" }, diff --git a/ClientRuntimes/NodeJS/ms-rest/package.json b/ClientRuntimes/NodeJS/ms-rest/package.json index 76fe82cddb802..b21efcee2df2c 100644 --- a/ClientRuntimes/NodeJS/ms-rest/package.json +++ b/ClientRuntimes/NodeJS/ms-rest/package.json @@ -5,7 +5,7 @@ "email": "azsdkteam@microsoft.com", "url": "https://github.com/Azure/AutoRest" }, - "version": "1.11.0", + "version": "1.12.0", "description": "Client Runtime for Node.js client libraries generated using AutoRest", "tags": ["node", "microsoft", "autorest", "clientruntime"], "keywords": ["node", "microsoft", "autorest", "clientruntime"], @@ -26,7 +26,7 @@ "request": "2.69.0", "duplexer": "~0.1.1", "through": "~2.3.4", - "moment": "^2.6.0" + "moment": "^2.9.0" }, "devDependencies": { "jshint": "2.6.3", From de7c6e9e757bbcbc03a5f3078cec027ae9d8cf7d Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Thu, 24 Mar 2016 18:14:47 -0700 Subject: [PATCH 37/99] Add property model and fix type conversion --- .../fixtures/bodyarray/ArrayOperations.java | 10 +- .../bodyarray/ArrayOperationsImpl.java | 40 ++++-- .../Datetimerfc1123OperationsImpl.java | 40 +++--- .../bodydictionary/DictionaryOperations.java | 10 +- .../DictionaryOperationsImpl.java | 40 ++++-- .../bodyformdata/FormdataOperationsImpl.java | 8 +- .../fixtures/header/HeaderOperationsImpl.java | 10 +- .../HeaderResponseDatetimeRfc1123Headers.java | 2 +- .../Java/Java/AutoRest.Generator.Java.csproj | 1 + .../Java/Java/GlobalSuppressions.cs | 3 + .../TemplateModels/MethodTemplateModel.cs | 10 +- .../Java/TemplateModels/ModelTemplateModel.cs | 21 ++-- .../Java/Java/Templates/ModelTemplate.cshtml | 4 +- .../Java/TypeModels/CompositeTypeModel.cs | 8 +- .../Java/TypeModels/DictionaryTypeModel.cs | 24 +++- .../Java/Java/TypeModels/EnumTypeModel.cs | 8 +- .../Java/Java/TypeModels/ITypeModel.cs | 4 +- .../Java/Java/TypeModels/ParameterModel.cs | 2 +- .../Java/Java/TypeModels/PrimaryTypeModel.cs | 16 +-- .../Java/Java/TypeModels/PropertyModel.cs | 40 ++++++ .../Java/Java/TypeModels/ResponseModel.cs | 117 +++++++++++------- .../Java/Java/TypeModels/SequenceTypeModel.cs | 24 +++- 22 files changed, 294 insertions(+), 148 deletions(-) create mode 100644 AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java index d781da1d96839..5a78a5b4f48e5 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java @@ -765,9 +765,9 @@ public interface ArrayOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the List<DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the List<DateTime> object wrapped in {@link ServiceResponse} if successful. */ - ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; + ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; /** * Get date-time array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT']. @@ -776,7 +776,7 @@ public interface ArrayOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; /** * Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT']. @@ -787,7 +787,7 @@ public interface ArrayOperations { * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException; /** * Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT']. @@ -797,7 +797,7 @@ public interface ArrayOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']. diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java index 45b10b52164d4..a157cf8e59d3e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java @@ -11,6 +11,7 @@ package fixtures.bodyarray; import com.google.common.reflect.TypeToken; +import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; @@ -20,6 +21,7 @@ import fixtures.bodyarray.models.ErrorException; import fixtures.bodyarray.models.Product; import java.io.IOException; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; @@ -223,7 +225,7 @@ interface ArrayService { @Headers("Content-Type: application/json; charset=utf-8") @PUT("array/prim/date-time-rfc1123/valid") - Call putDateTimeRfc1123Valid(@Body List arrayBody); + Call putDateTimeRfc1123Valid(@Body List arrayBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("array/prim/duration/valid") @@ -2199,11 +2201,21 @@ private ServiceResponse> getDateTimeInvalidCharsDelegate(Response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the List<DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the List<DateTime> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { + public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { Call call = service.getDateTimeRfc1123Valid(); - return getDateTimeRfc1123ValidDelegate(call.execute()); + ServiceResponse> response = getDateTimeRfc1123ValidDelegate(call.execute()); + List body = null; + if (response.getBody() != null) { + body = new ArrayList(); + for (DateTimeRfc1123 item : response.getBody()) { + DateTime value; + value = item.getDateTime(); + body.add(value); + }; + } + return new ServiceResponse>(body, response.getResponse()); } /** @@ -2213,17 +2225,27 @@ public ServiceResponse> getDateTimeRfc1123Valid() throws E * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Call call = service.getDateTimeRfc1123Valid(); final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { + call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override public void onResponse(Call call, Response response) { try { - serviceCallback.success(getDateTimeRfc1123ValidDelegate(response)); + ServiceResponse> result = getDateTimeRfc1123ValidDelegate(response); + List body = null; + if (result.getBody() != null) { + body = new ArrayList(); + for (DateTimeRfc1123 item : result.getBody()) { + DateTime value; + value = item.getDateTime(); + body.add(value); + }; + } + serviceCallback.success(new ServiceResponse>(body, result.getResponse())); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } @@ -2248,7 +2270,7 @@ private ServiceResponse> getDateTimeRfc1123ValidDelegate(R * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException { + public ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException { if (arrayBody == null) { throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null."); } @@ -2265,7 +2287,7 @@ public ServiceResponse putDateTimeRfc1123Valid(List array * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java index 495e8aba4e7a5..b10cad7f09b2e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java @@ -73,7 +73,7 @@ interface Datetimerfc1123Service { @Headers("Content-Type: application/json; charset=utf-8") @PUT("datetimerfc1123/max") - Call putUtcMaxDateTime(@Body DateTimeRfc1123 datetimeBody); + Call putUtcMaxDateTime(@Body DateTime datetimeBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("datetimerfc1123/max/lowercase") @@ -85,7 +85,7 @@ interface Datetimerfc1123Service { @Headers("Content-Type: application/json; charset=utf-8") @PUT("datetimerfc1123/min") - Call putUtcMinDateTime(@Body DateTimeRfc1123 datetimeBody); + Call putUtcMinDateTime(@Body DateTime datetimeBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("datetimerfc1123/min") @@ -105,7 +105,7 @@ public ServiceResponse getNull() throws ErrorException, IOException { ServiceResponse response = getNullDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime(); + body = response.getBody().getDateTime();; } return new ServiceResponse(body, response.getResponse()); } @@ -130,7 +130,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getNullDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime(); + body = result.getBody().getDateTime();; } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -160,7 +160,7 @@ public ServiceResponse getInvalid() throws ErrorException, IOException ServiceResponse response = getInvalidDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime(); + body = response.getBody().getDateTime();; } return new ServiceResponse(body, response.getResponse()); } @@ -185,7 +185,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getInvalidDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime(); + body = result.getBody().getDateTime();; } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -215,7 +215,7 @@ public ServiceResponse getOverflow() throws ErrorException, IOExceptio ServiceResponse response = getOverflowDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime(); + body = response.getBody().getDateTime();; } return new ServiceResponse(body, response.getResponse()); } @@ -240,7 +240,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getOverflowDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime(); + body = result.getBody().getDateTime();; } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -270,7 +270,7 @@ public ServiceResponse getUnderflow() throws ErrorException, IOExcepti ServiceResponse response = getUnderflowDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime(); + body = response.getBody().getDateTime();; } return new ServiceResponse(body, response.getResponse()); } @@ -295,7 +295,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUnderflowDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime(); + body = result.getBody().getDateTime();; } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -326,7 +326,7 @@ public ServiceResponse putUtcMaxDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); + Call call = service.putUtcMaxDateTime(datetimeBody); return putUtcMaxDateTimeDelegate(call.execute()); } @@ -346,7 +346,7 @@ public ServiceCall putUtcMaxDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); + Call call = service.putUtcMaxDateTime(datetimeBody); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -380,7 +380,7 @@ public ServiceResponse getUtcLowercaseMaxDateTime() throws ErrorExcept ServiceResponse response = getUtcLowercaseMaxDateTimeDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime(); + body = response.getBody().getDateTime();; } return new ServiceResponse(body, response.getResponse()); } @@ -405,7 +405,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUtcLowercaseMaxDateTimeDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime(); + body = result.getBody().getDateTime();; } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -435,7 +435,7 @@ public ServiceResponse getUtcUppercaseMaxDateTime() throws ErrorExcept ServiceResponse response = getUtcUppercaseMaxDateTimeDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime(); + body = response.getBody().getDateTime();; } return new ServiceResponse(body, response.getResponse()); } @@ -460,7 +460,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUtcUppercaseMaxDateTimeDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime(); + body = result.getBody().getDateTime();; } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -491,7 +491,7 @@ public ServiceResponse putUtcMinDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); + Call call = service.putUtcMinDateTime(datetimeBody); return putUtcMinDateTimeDelegate(call.execute()); } @@ -511,7 +511,7 @@ public ServiceCall putUtcMinDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); + Call call = service.putUtcMinDateTime(datetimeBody); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -545,7 +545,7 @@ public ServiceResponse getUtcMinDateTime() throws ErrorException, IOEx ServiceResponse response = getUtcMinDateTimeDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime(); + body = response.getBody().getDateTime();; } return new ServiceResponse(body, response.getResponse()); } @@ -570,7 +570,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUtcMinDateTimeDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime(); + body = result.getBody().getDateTime();; } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java index e6c01f856a4b0..74450586af8c1 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java @@ -761,9 +761,9 @@ public interface DictionaryOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Map<String, DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the Map<String, DateTime> object wrapped in {@link ServiceResponse} if successful. */ - ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; + ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; /** * Get date-time-rfc1123 dictionary value {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. @@ -772,7 +772,7 @@ public interface DictionaryOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; /** * Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. @@ -783,7 +783,7 @@ public interface DictionaryOperations { * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException; /** * Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. @@ -793,7 +793,7 @@ public interface DictionaryOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall putDateTimeRfc1123ValidAsync(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall putDateTimeRfc1123ValidAsync(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Get duration dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}. diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java index d350ead94103b..b954eae668960 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java @@ -11,6 +11,7 @@ package fixtures.bodydictionary; import com.google.common.reflect.TypeToken; +import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; @@ -20,6 +21,7 @@ import fixtures.bodydictionary.models.ErrorException; import fixtures.bodydictionary.models.Widget; import java.io.IOException; +import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; @@ -222,7 +224,7 @@ interface DictionaryService { @Headers("Content-Type: application/json; charset=utf-8") @PUT("dictionary/prim/date-time-rfc1123/valid") - Call putDateTimeRfc1123Valid(@Body Map arrayBody); + Call putDateTimeRfc1123Valid(@Body Map arrayBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("dictionary/prim/duration/valid") @@ -2186,11 +2188,21 @@ private ServiceResponse> getDateTimeInvalidCharsDelegate(R * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Map<String, DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the Map<String, DateTime> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { + public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { Call call = service.getDateTimeRfc1123Valid(); - return getDateTimeRfc1123ValidDelegate(call.execute()); + ServiceResponse> response = getDateTimeRfc1123ValidDelegate(call.execute()); + Map body = null; + if (response.getBody() != null) { + body = new HashMap(); + for (Map.Entry entry : response.getBody().entrySet()) { + DateTime value; + value = entry.getValue().getDateTime(); + body.put(entry.getKey(), value); + }; + } + return new ServiceResponse>(body, response.getResponse()); } /** @@ -2200,17 +2212,27 @@ public ServiceResponse> getDateTimeRfc1123Valid() t * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Call call = service.getDateTimeRfc1123Valid(); final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { + call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override public void onResponse(Call call, Response response) { try { - serviceCallback.success(getDateTimeRfc1123ValidDelegate(response)); + ServiceResponse> result = getDateTimeRfc1123ValidDelegate(response); + Map body = null; + if (result.getBody() != null) { + body = new HashMap(); + for (Map.Entry entry : result.getBody().entrySet()) { + DateTime value; + value = entry.getValue().getDateTime(); + body.put(entry.getKey(), value); + }; + } + serviceCallback.success(new ServiceResponse>(body, result.getResponse())); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } @@ -2235,7 +2257,7 @@ private ServiceResponse> getDateTimeRfc1123ValidDel * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException { + public ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException { if (arrayBody == null) { throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null."); } @@ -2252,7 +2274,7 @@ public ServiceResponse putDateTimeRfc1123Valid(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall putDateTimeRfc1123ValidAsync(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java index e02b9db18446e..8458fd8f20f0b 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java @@ -88,7 +88,7 @@ public ServiceResponse uploadFile(byte[] fileContent, String fileNa if (fileName == null) { throw new IllegalArgumentException("Parameter fileName is required and cannot be null."); } - Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); + Call call = service.uploadFile(fileContent, fileName); return uploadFileDelegate(call.execute()); } @@ -113,7 +113,7 @@ public ServiceCall uploadFileAsync(byte[] fileContent, String fileName, final Se serviceCallback.failure(new IllegalArgumentException("Parameter fileName is required and cannot be null.")); return null; } - Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); + Call call = service.uploadFile(fileContent, fileName); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -148,7 +148,7 @@ public ServiceResponse uploadFileViaBody(byte[] fileContent) throws if (fileContent == null) { throw new IllegalArgumentException("Parameter fileContent is required and cannot be null."); } - Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); + Call call = service.uploadFileViaBody(fileContent); return uploadFileViaBodyDelegate(call.execute()); } @@ -168,7 +168,7 @@ public ServiceCall uploadFileViaBodyAsync(byte[] fileContent, final ServiceCallb serviceCallback.failure(new IllegalArgumentException("Parameter fileContent is required and cannot be null.")); return null; } - Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); + Call call = service.uploadFileViaBody(fileContent); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 80c9db76accc4..69e6785d8d9de 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -155,7 +155,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/datetimerfc1123") - Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") DateTimeRfc1123 value); + Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") DateTime value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/datetimerfc1123") @@ -1365,7 +1365,7 @@ public ServiceResponse paramDatetimeRfc1123(String scenario) throws ErrorE throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1386,7 +1386,7 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, final ServiceCallb return null; } final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1415,7 +1415,7 @@ public ServiceResponse paramDatetimeRfc1123(String scenario, DateTime valu if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1436,7 +1436,7 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, DateTime value, fi serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java index f08b2dc6a2967..acc652d6a8fc7 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java @@ -10,7 +10,7 @@ package fixtures.header.models; -import org.joda.time.DateTime; +import com.microsoft.rest.DateTimeRfc1123; /** * Defines headers for responseDatetimeRfc1123 operation. diff --git a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj index 2072eabb4463d..e1287ab35efdf 100644 --- a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj +++ b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj @@ -32,6 +32,7 @@ Resources.resx + diff --git a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs index 6e21099c380ef..f79d039c95c7e 100644 --- a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs @@ -164,3 +164,6 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#LocationImport(Microsoft.Rest.Generator.ClientModel.ParameterLocation)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#NeedsSpecialSerialization(Microsoft.Rest.Generator.ClientModel.IType)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_response")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ModelTemplateModel.#PropertyModels")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PropertyModel.#.ctor(Microsoft.Rest.Generator.ClientModel.Property,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PropertyModel.#.ctor(Microsoft.Rest.Generator.ClientModel.Property,System.String)")] diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 65f2418aebe51..4164cc43eabfb 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -182,13 +182,13 @@ public string MethodParameterApiInvocation { get { - List declarations = new List(); + List invocations = new List(); foreach (var parameter in OrderedRetrofitParameters) { - declarations.Add(parameter.Invoke(parameter.Name, ClientReference)); + invocations.Add(parameter.Invoke(parameter.Name, ClientReference)); } - var declaration = string.Join(", ", declarations); + var declaration = string.Join(", ", invocations); return declaration; } } @@ -515,7 +515,7 @@ public virtual string ResponseGeneration ReturnTypeModel.GenericBodyWireTypeString, this.Name.ToCamelCase()); builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType.Name) .AppendLine("if (response.getBody() != null) {") - .Indent().AppendLine("body = {0};", ReturnTypeModel.ConvertBodyToClientType("response.getBody()")) + .Indent().AppendLine("{0};", ReturnTypeModel.ConvertBodyToClientType("response.getBody()", "body")) .Outdent().AppendLine("}"); return builder.ToString(); } @@ -545,7 +545,7 @@ public virtual string SuccessCallback builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeModel.GenericBodyWireTypeString, this.Name); builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) .AppendLine("if (result.getBody() != null) {") - .Indent().AppendLine("body = {0};", ReturnTypeModel.ConvertBodyToClientType("result.getBody()")) + .Indent().AppendLine("{0};", ReturnTypeModel.ConvertBodyToClientType("result.getBody()", "body")) .Outdent().AppendLine("}"); builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", ReturnTypeModel.GenericBodyClientTypeString); return builder.ToString(); diff --git a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs index ce81e2b3efd3a..a47aa6b345011 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs @@ -26,6 +26,8 @@ public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } _namer = new JavaCodeNamer(serviceClient.Namespace); + PropertyModels = new List(); + Properties.ForEach(p => PropertyModels.Add(new PropertyModel(p, serviceClient.Namespace))); } protected virtual JavaCodeNamer Namer @@ -38,6 +40,8 @@ protected virtual JavaCodeNamer Namer public ServiceClient ServiceClient { get; set; } + public List PropertyModels { get; private set; } + public bool IsPolymorphic { get @@ -139,18 +143,11 @@ private bool isSpecial(IType type) public virtual IEnumerable ImportList { get { - HashSet classes = new HashSet(); - foreach (var property in this.Properties) + var classes = new HashSet(); + classes.AddRange(PropertyModels.SelectMany(pm => pm.Imports)); + if (this.Properties.Any(p => !p.GetJsonProperty().IsNullOrEmpty())) { - classes.AddRange(property.Type.ImportSafe() - .Where(c => !c.StartsWith( - string.Join(".", ServiceClient.Namespace, "models"), - StringComparison.OrdinalIgnoreCase))); - - if (this.Properties.Any(p => !p.GetJsonProperty().IsNullOrEmpty())) - { - classes.Add("com.fasterxml.jackson.annotation.JsonProperty"); - } + classes.Add("com.fasterxml.jackson.annotation.JsonProperty"); } // For polymorphism if (IsPolymorphic) @@ -167,7 +164,7 @@ public virtual IEnumerable ImportList { { classes.Add("com.microsoft.rest.serializer.JsonFlatten"); } - return classes.Distinct().AsEnumerable(); + return classes.AsEnumerable(); } } diff --git a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml index 65ca7856ef46b..5dd8b297b4726 100644 --- a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml @@ -88,7 +88,7 @@ if (!jsonSetting.IsNullOrEmpty()) @: * @@return the @property.Name value @: */ @: public @(((ITypeModel)property.Type).ResponseVariant) get@(property.Name.ToPascalCase())() { -if (property.Type.Name != ((ITypeModel) property.Type).ResponseVariant) +if (property.Type.Name != ((ITypeModel) property.Type).ResponseVariant.Name) { @: if (this.@(property.Name) == null) { @: return null; @@ -109,7 +109,7 @@ if (!property.IsReadOnly) @: * @@param @property.Name the @property.Name value to set @: */ @: public void set@(property.Name.ToPascalCase())(@(((ITypeModel)property.Type).ResponseVariant) @property.Name) { -if (property.Type.Name != ((ITypeModel)property.Type).ResponseVariant) +if (property.Type.Name != ((ITypeModel)property.Type).ResponseVariant.Name) { @: this.@(property.Name) = new @(property.Type.Name)(@property.Name); } diff --git a/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs index 2dbb0b8eab1a7..c2d1e30a0faf3 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs @@ -46,19 +46,19 @@ public virtual string Package } } - public string ParameterVariant + public ITypeModel ParameterVariant { get { - return Name; + return this; } } - public string ResponseVariant + public ITypeModel ResponseVariant { get { - return Name; + return this; } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs index 59c9743e936ce..7fbf65406e1f3 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs @@ -25,19 +25,35 @@ public ITypeModel ValueTypeModel } } - public string ParameterVariant + public ITypeModel ParameterVariant { get { - return Name; + if (ValueTypeModel.ParameterVariant != ValueTypeModel) + { + return new DictionaryTypeModel(new DictionaryType() + { + NameFormat = "Map", + ValueType = ValueTypeModel.ParameterVariant + }); + } + return this; } } - public string ResponseVariant + public ITypeModel ResponseVariant { get { - return Name; + if (ValueTypeModel.ResponseVariant != ValueTypeModel) + { + return new DictionaryTypeModel(new DictionaryType() + { + NameFormat = "Map", + ValueType = ValueTypeModel.ResponseVariant + }); + } + return this; } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs index ee0b7ec043681..25df159a7f12a 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs @@ -21,19 +21,19 @@ public EnumTypeModel(EnumType enumType, string package) this._package = package.ToLower(CultureInfo.InvariantCulture); } - public string ParameterVariant + public ITypeModel ParameterVariant { get { - return Name; + return this; } } - public string ResponseVariant + public ITypeModel ResponseVariant { get { - return Name; + return this; } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs index 3c45f84efd0d0..dbc95f16f2cbb 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs @@ -13,9 +13,9 @@ public interface ITypeModel : IType { string DefaultValue { get; } - string ParameterVariant { get; } + ITypeModel ParameterVariant { get; } - string ResponseVariant { get; } + ITypeModel ResponseVariant { get; } IEnumerable Imports { get; } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs index ee6389eb3771a..4cef0b77cdcde 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs @@ -30,7 +30,7 @@ public ITypeModel ClientType { get { - return (ITypeModel) Type; + return ((ITypeModel) Type).ParameterVariant; } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs index 5702307f47955..892c4abc0b28d 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs @@ -56,36 +56,36 @@ public string DefaultValue } } - public string ParameterVariant + public ITypeModel ParameterVariant { get { if (Type == KnownPrimaryType.DateTimeRfc1123) { - return "DateTime"; + return new PrimaryTypeModel(KnownPrimaryType.DateTime); } else if (Type == KnownPrimaryType.Stream) { - return "byte[]"; + return new PrimaryTypeModel(KnownPrimaryType.ByteArray); } else { - return Name; + return this; } } } - public string ResponseVariant + public ITypeModel ResponseVariant { get { if (Type == KnownPrimaryType.DateTimeRfc1123) { - return "DateTime"; + return new PrimaryTypeModel(KnownPrimaryType.DateTime); } else { - return Name; + return this; } } } @@ -164,7 +164,7 @@ private void Initialize(PrimaryType primaryType) else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123) { Name = "DateTimeRfc1123"; - _imports.Add("org.joda.time.DateTime"); + _imports.Add("com.microsoft.rest.DateTimeRfc1123"); } else if (primaryType.Type == KnownPrimaryType.Double) { diff --git a/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs new file mode 100644 index 0000000000000..b077c5cd657de --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs @@ -0,0 +1,40 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class PropertyModel : Property + { + private string _package; + + public PropertyModel(Property property, string package) + : base() + { + this.LoadFrom(property); + this._package = package.ToLower(CultureInfo.InvariantCulture); + } + + public IEnumerable Imports + { + get + { + var imports = new List(Type.ImportSafe() + .Where(c => !c.StartsWith( + string.Join(".", _package, "models"), + StringComparison.OrdinalIgnoreCase))); + if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + imports.Add("com.microsoft.rest.DateTimeRfc1123"); + } + return imports; + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs index 9580933998522..99a1ad0d28cc8 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -13,10 +13,14 @@ namespace Microsoft.Rest.Generator.Java public class ResponseModel { protected Response _response; + protected List _interfaceImports; + protected List _implImports; public ResponseModel(Response response) { this._response = response; + this._interfaceImports = new List(); + this._implImports = new List(); } public ResponseModel(ITypeModel body, ITypeModel headers) @@ -30,10 +34,6 @@ public ITypeModel Body { get { - if (_response == null) - { - return null; - } return (ITypeModel)_response.Body; } } @@ -42,10 +42,6 @@ public ITypeModel Headers { get { - if (_response == null) - { - return null; - } return (ITypeModel)_response.Headers; } } @@ -54,11 +50,8 @@ public bool NeedsConversion { get { - return (Body != null && - Body.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - || - (Headers != null && - Headers.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)); + return BodyWireType != BodyClientType || + HeaderWireType != HeaderClientType; } } @@ -66,30 +59,28 @@ public ITypeModel BodyClientType { get { - if (Body == null) - { - return new PrimaryTypeModel(KnownPrimaryType.None) { Name = "void" }; - } - else if (Body.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - return new PrimaryTypeModel(KnownPrimaryType.DateTime); - } - else - { - return BodyWireType; - } + return BodyWireType.ResponseVariant; } } + private ITypeModel _bodyWireType; + public ITypeModel BodyWireType { get { - if (Body == null) + if (_bodyWireType == null) { - return new PrimaryTypeModel(KnownPrimaryType.None) { Name = "void" }; + if (Body == null) + { + _bodyWireType = new PrimaryTypeModel(KnownPrimaryType.None) { Name = "void" }; + } + else + { + _bodyWireType = (ITypeModel) Body; + } } - return (ITypeModel) Body; + return _bodyWireType; } } @@ -101,13 +92,9 @@ public ITypeModel HeaderClientType { return null; } - else if (Headers.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - return new PrimaryTypeModel(KnownPrimaryType.DateTime); - } else { - return HeaderWireType; + return HeaderWireType.ResponseVariant; } } } @@ -124,14 +111,14 @@ public ITypeModel HeaderWireType } } - public string ConvertBodyToClientType(string reference) + public string ConvertBodyToClientType(string source, string target) { - return converToClientType(Body, reference); + return converToClientType(BodyWireType, source, target); } - public string ConvertHeaderToClientType(string reference) + public string ConvertHeaderToClientType(string source, string target) { - return converToClientType(Headers, reference); + return converToClientType(HeaderWireType, source, target); } #endregion @@ -195,7 +182,7 @@ public virtual string GenericBodyClientTypeString { get { - return BodyClientType.InstanceType().Name; + return BodyClientType.InstanceType().ResponseVariant.Name; } } @@ -203,7 +190,7 @@ public virtual string GenericHeaderClientTypeString { get { - return HeaderClientType.InstanceType().Name; + return HeaderClientType.InstanceType().ResponseVariant.Name; } } @@ -229,7 +216,7 @@ public IEnumerable InterfaceImports { get { - return BodyClientType.ImportSafe().Concat(HeaderClientType.ImportSafe()); + return _interfaceImports.Concat(BodyClientType.ImportSafe()).Concat(HeaderClientType.ImportSafe()); } } @@ -240,23 +227,65 @@ public IEnumerable ImplImports var imports = new List(InterfaceImports); imports.AddRange(BodyWireType.ImportSafe()); imports.AddRange(HeaderWireType.ImportSafe()); + if (this.NeedsConversion && (Body is SequenceType || Headers is SequenceType)) + { + imports.Add("java.util.ArrayList"); + } + if (this.NeedsConversion && (Body is DictionaryType || Headers is DictionaryType)) + { + imports.Add("java.util.HashMap"); + } return imports; } } - private string converToClientType(IType type, string reference) + private string converToClientType(ITypeModel type, string source, string target, int level = 0) { if (type == null) { - return reference; + return target + " = " + source + ";"; + } + + IndentedStringBuilder builder = new IndentedStringBuilder(); + + SequenceTypeModel sequenceType = type as SequenceTypeModel; + DictionaryTypeModel dictionaryType = type as DictionaryTypeModel; + + if (sequenceType != null) + { + var elementType = sequenceType.ElementTypeModel; + var itemName = string.Format("item{0}", level == 0 ? "" : level.ToString()); + var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + builder.AppendLine("{0} = new ArrayList<{1}>();", target, elementType.ResponseVariant.Name) + .AppendLine("for ({0} {1} : {2}) {{", elementType.Name, itemName, source) + .Indent().AppendLine("{0} {1};", elementType.ResponseVariant.Name, itemTarget) + .AppendLine(converToClientType(elementType, itemName, itemTarget, level + 1)) + .AppendLine("{0}.add({1});", target, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.ArrayList"); + return builder.ToString(); + } + else if (dictionaryType != null) + { + var valueType = dictionaryType.ValueTypeModel; + var itemName = string.Format("entry{0}", level == 0 ? "" : level.ToString()); + var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + builder.AppendLine("{0} = new HashMap();", target, valueType.Name) + .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.ResponseVariant.Name, itemName, source) + .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget) + .AppendLine(converToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1)) + .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.HashMap"); + return builder.ToString(); } else if (type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { - return reference + ".getDateTime()"; + return target + " = " + source + ".getDateTime();"; } else { - return reference; + return target + " = " + source + ";"; } } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs index 30137c350913f..cd24f114945b0 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs @@ -30,19 +30,35 @@ public ITypeModel ElementTypeModel } } - public string ParameterVariant + public ITypeModel ParameterVariant { get { - return Name; + if (ElementTypeModel.ParameterVariant != ElementTypeModel) + { + return new SequenceTypeModel(new SequenceType() + { + NameFormat = "List<{0}>", + ElementType = ElementTypeModel.ParameterVariant + }); + } + return this; } } - public string ResponseVariant + public ITypeModel ResponseVariant { get { - return Name; + if (ElementTypeModel.ResponseVariant != ElementTypeModel) + { + return new SequenceTypeModel(new SequenceType() + { + NameFormat = "List<{0}>", + ElementType = ElementTypeModel.ResponseVariant + }); + } + return this; } } From 754785b9ac2758f17f72c3c3d3034277f3013b25 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Thu, 24 Mar 2016 18:20:27 -0700 Subject: [PATCH 38/99] Fix some imports --- .../fixtures/bodyarray/ArrayOperationsImpl.java | 2 +- .../Datetimerfc1123OperationsImpl.java | 14 +++++++------- .../bodydictionary/DictionaryOperationsImpl.java | 10 +++++----- .../HeaderResponseDatetimeRfc1123Headers.java | 1 + .../Java/TemplateModels/MethodTemplateModel.cs | 2 +- .../Java/Java/TypeModels/PropertyModel.cs | 3 ++- .../Java/Java/TypeModels/ResponseModel.cs | 4 ++-- 7 files changed, 19 insertions(+), 17 deletions(-) diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java index a157cf8e59d3e..ed9d7d50f4046 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java @@ -2243,7 +2243,7 @@ public void onResponse(Call call, Response response) DateTime value; value = item.getDateTime(); body.add(value); - }; + } } serviceCallback.success(new ServiceResponse>(body, result.getResponse())); } catch (ErrorException | IOException exception) { diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java index b10cad7f09b2e..b42333bdee125 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java @@ -130,7 +130,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getNullDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime();; + body = result.getBody().getDateTime(); } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -185,7 +185,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getInvalidDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime();; + body = result.getBody().getDateTime(); } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -240,7 +240,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getOverflowDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime();; + body = result.getBody().getDateTime(); } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -295,7 +295,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUnderflowDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime();; + body = result.getBody().getDateTime(); } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -405,7 +405,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUtcLowercaseMaxDateTimeDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime();; + body = result.getBody().getDateTime(); } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -460,7 +460,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUtcUppercaseMaxDateTimeDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime();; + body = result.getBody().getDateTime(); } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { @@ -570,7 +570,7 @@ public void onResponse(Call call, Response response) ServiceResponse result = getUtcMinDateTimeDelegate(response); DateTime body = null; if (result.getBody() != null) { - body = result.getBody().getDateTime();; + body = result.getBody().getDateTime(); } serviceCallback.success(new ServiceResponse(body, result.getResponse())); } catch (ErrorException | IOException exception) { diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java index b954eae668960..8ab4230eac158 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java @@ -2195,8 +2195,8 @@ public ServiceResponse> getDateTimeRfc1123Valid() throws E ServiceResponse> response = getDateTimeRfc1123ValidDelegate(call.execute()); Map body = null; if (response.getBody() != null) { - body = new HashMap(); - for (Map.Entry entry : response.getBody().entrySet()) { + body = new HashMap(); + for (Map.Entry entry : response.getBody().entrySet()) { DateTime value; value = entry.getValue().getDateTime(); body.put(entry.getKey(), value); @@ -2225,12 +2225,12 @@ public void onResponse(Call call, Response response) ServiceResponse> result = getDateTimeRfc1123ValidDelegate(response); Map body = null; if (result.getBody() != null) { - body = new HashMap(); - for (Map.Entry entry : result.getBody().entrySet()) { + body = new HashMap(); + for (Map.Entry entry : result.getBody().entrySet()) { DateTime value; value = entry.getValue().getDateTime(); body.put(entry.getKey(), value); - }; + } } serviceCallback.success(new ServiceResponse>(body, result.getResponse())); } catch (ErrorException | IOException exception) { diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java index acc652d6a8fc7..9728eb3f4d64a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java @@ -11,6 +11,7 @@ package fixtures.header.models; import com.microsoft.rest.DateTimeRfc1123; +import org.joda.time.DateTime; /** * Defines headers for responseDatetimeRfc1123 operation. diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 4164cc43eabfb..15f1f0c63f100 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -545,7 +545,7 @@ public virtual string SuccessCallback builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeModel.GenericBodyWireTypeString, this.Name); builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) .AppendLine("if (result.getBody() != null) {") - .Indent().AppendLine("{0};", ReturnTypeModel.ConvertBodyToClientType("result.getBody()", "body")) + .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("result.getBody()", "body")) .Outdent().AppendLine("}"); builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", ReturnTypeModel.GenericBodyClientTypeString); return builder.ToString(); diff --git a/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs index b077c5cd657de..aaed0a6840996 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs @@ -31,7 +31,8 @@ public IEnumerable Imports StringComparison.OrdinalIgnoreCase))); if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { - imports.Add("com.microsoft.rest.DateTimeRfc1123"); + imports.AddRange(Type.ImportSafe()); + imports.AddRange(((ITypeModel) Type).ResponseVariant.ImportSafe()); } return imports; } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs index 99a1ad0d28cc8..9fa9315e31412 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -270,8 +270,8 @@ private string converToClientType(ITypeModel type, string source, string target, var valueType = dictionaryType.ValueTypeModel; var itemName = string.Format("entry{0}", level == 0 ? "" : level.ToString()); var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); - builder.AppendLine("{0} = new HashMap();", target, valueType.Name) - .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.ResponseVariant.Name, itemName, source) + builder.AppendLine("{0} = new HashMap();", target, valueType.ResponseVariant.Name) + .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.Name, itemName, source) .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget) .AppendLine(converToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1)) .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget) From 9b1bb48d57d30128fcd30c7cf797d60f551ed910 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Fri, 25 Mar 2016 11:42:19 -0700 Subject: [PATCH 39/99] Fix parameter invocation --- .../fixtures/bodyarray/ArrayOperationsImpl.java | 2 +- .../Datetimerfc1123OperationsImpl.java | 12 ++++++------ .../bodydictionary/DictionaryOperationsImpl.java | 2 +- .../bodyformdata/FormdataOperationsImpl.java | 8 ++++---- .../java/fixtures/header/HeaderOperationsImpl.java | 10 +++++----- .../Java/Java/TypeModels/ParameterModel.cs | 14 +++++++------- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java index ed9d7d50f4046..5591d326765dc 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java @@ -225,7 +225,7 @@ interface ArrayService { @Headers("Content-Type: application/json; charset=utf-8") @PUT("array/prim/date-time-rfc1123/valid") - Call putDateTimeRfc1123Valid(@Body List arrayBody); + Call putDateTimeRfc1123Valid(@Body List arrayBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("array/prim/duration/valid") diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java index b42333bdee125..e8a4207447ffc 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java @@ -73,7 +73,7 @@ interface Datetimerfc1123Service { @Headers("Content-Type: application/json; charset=utf-8") @PUT("datetimerfc1123/max") - Call putUtcMaxDateTime(@Body DateTime datetimeBody); + Call putUtcMaxDateTime(@Body DateTimeRfc1123 datetimeBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("datetimerfc1123/max/lowercase") @@ -85,7 +85,7 @@ interface Datetimerfc1123Service { @Headers("Content-Type: application/json; charset=utf-8") @PUT("datetimerfc1123/min") - Call putUtcMinDateTime(@Body DateTime datetimeBody); + Call putUtcMinDateTime(@Body DateTimeRfc1123 datetimeBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("datetimerfc1123/min") @@ -326,7 +326,7 @@ public ServiceResponse putUtcMaxDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMaxDateTime(datetimeBody); + Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); return putUtcMaxDateTimeDelegate(call.execute()); } @@ -346,7 +346,7 @@ public ServiceCall putUtcMaxDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMaxDateTime(datetimeBody); + Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -491,7 +491,7 @@ public ServiceResponse putUtcMinDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMinDateTime(datetimeBody); + Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); return putUtcMinDateTimeDelegate(call.execute()); } @@ -511,7 +511,7 @@ public ServiceCall putUtcMinDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMinDateTime(datetimeBody); + Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java index 8ab4230eac158..52bdc52882c0e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java @@ -224,7 +224,7 @@ interface DictionaryService { @Headers("Content-Type: application/json; charset=utf-8") @PUT("dictionary/prim/date-time-rfc1123/valid") - Call putDateTimeRfc1123Valid(@Body Map arrayBody); + Call putDateTimeRfc1123Valid(@Body Map arrayBody); @Headers("Content-Type: application/json; charset=utf-8") @GET("dictionary/prim/duration/valid") diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java index 8458fd8f20f0b..e02b9db18446e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java @@ -88,7 +88,7 @@ public ServiceResponse uploadFile(byte[] fileContent, String fileNa if (fileName == null) { throw new IllegalArgumentException("Parameter fileName is required and cannot be null."); } - Call call = service.uploadFile(fileContent, fileName); + Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); return uploadFileDelegate(call.execute()); } @@ -113,7 +113,7 @@ public ServiceCall uploadFileAsync(byte[] fileContent, String fileName, final Se serviceCallback.failure(new IllegalArgumentException("Parameter fileName is required and cannot be null.")); return null; } - Call call = service.uploadFile(fileContent, fileName); + Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -148,7 +148,7 @@ public ServiceResponse uploadFileViaBody(byte[] fileContent) throws if (fileContent == null) { throw new IllegalArgumentException("Parameter fileContent is required and cannot be null."); } - Call call = service.uploadFileViaBody(fileContent); + Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); return uploadFileViaBodyDelegate(call.execute()); } @@ -168,7 +168,7 @@ public ServiceCall uploadFileViaBodyAsync(byte[] fileContent, final ServiceCallb serviceCallback.failure(new IllegalArgumentException("Parameter fileContent is required and cannot be null.")); return null; } - Call call = service.uploadFileViaBody(fileContent); + Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 69e6785d8d9de..80c9db76accc4 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -155,7 +155,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/datetimerfc1123") - Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") DateTime value); + Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") DateTimeRfc1123 value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/datetimerfc1123") @@ -1365,7 +1365,7 @@ public ServiceResponse paramDatetimeRfc1123(String scenario) throws ErrorE throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1386,7 +1386,7 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, final ServiceCallb return null; } final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1415,7 +1415,7 @@ public ServiceResponse paramDatetimeRfc1123(String scenario, DateTime valu if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1436,7 +1436,7 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, DateTime value, fi serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramDatetimeRfc1123(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs index 4cef0b77cdcde..fc25fb4e2b3c3 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs @@ -49,18 +49,14 @@ public ITypeModel WireType } else { - return ClientType; + return (ITypeModel) Type; } } } public string Invoke(string reference, string clientReference) { - if (ClientType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - return string.Format(CultureInfo.InvariantCulture, "new DateTimeRfc1123({0})", reference); - } - else if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData) + if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData) { var primary = ClientType as PrimaryTypeModel; var sequence = ClientType as SequenceTypeModel; @@ -85,7 +81,11 @@ public string Invoke(string reference, string clientReference) return clientReference + ".getMapperAdapter().serializeRaw(" + reference + ")"; } } - else if (ClientType.IsPrimaryType(KnownPrimaryType.Stream)) + else if (WireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + return string.Format(CultureInfo.InvariantCulture, "new DateTimeRfc1123({0})", reference); + } + else if (WireType.IsPrimaryType(KnownPrimaryType.Stream)) { return string.Format(CultureInfo.InvariantCulture, "RequestBody.create(MediaType.parse(\"{0}\"), {1})", From b8cfd81fdcf61fef4fb5afed1965c067f6d57130 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Fri, 25 Mar 2016 17:17:47 -0700 Subject: [PATCH 40/99] Add parameter conversion --- .../Templates/AzureMethodTemplate.cshtml | 4 +- .../bodyarray/ArrayOperationsImpl.java | 16 +- .../Datetimerfc1123OperationsImpl.java | 26 +-- .../DictionaryOperationsImpl.java | 16 +- .../bodyformdata/FormdataOperationsImpl.java | 12 +- .../fixtures/header/HeaderOperationsImpl.java | 44 +++-- .../AvailabilitySetsOperationsImpl.java | 2 + .../ExplicitOperationsImpl.java | 18 +- .../fixtures/url/PathsOperationsImpl.java | 54 ++++-- .../fixtures/url/QueriesOperationsImpl.java | 162 ++++++++++++------ .../TemplateModels/MethodTemplateModel.cs | 19 +- .../Java/Java/Templates/MethodTemplate.cshtml | 4 + .../Java/Java/TypeModels/ParameterModel.cs | 119 +++++++++---- .../Java/Java/TypeModels/ResponseModel.cs | 10 +- 14 files changed, 353 insertions(+), 153 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index f2648e60c8fe6..5595b8214911f 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -118,7 +118,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW } } @Model.BuildInputMappings() - + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback<@Model.CallType>() { @@ -184,7 +184,7 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth } } @Model.BuildInputMappings() - + @Model.ParameterConversion Response result = service.@(Model.Name)(@Model.MethodParameterApiInvocation).execute(); return client.getAzureClient().@(Model.PollingMethod)(result, @Model.PollingResourceTypeArgs); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java index 5591d326765dc..f0286e8f8435f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java @@ -2213,7 +2213,7 @@ public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorExc DateTime value; value = item.getDateTime(); body.add(value); - }; + } } return new ServiceResponse>(body, response.getResponse()); } @@ -2275,7 +2275,12 @@ public ServiceResponse putDateTimeRfc1123Valid(List arrayBody) t throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null."); } Validator.validate(arrayBody); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + List arrayBodyConverted = new ArrayList(); + for (DateTime item : arrayBody) { + DateTimeRfc1123 value = new DateTimeRfc1123(item); + arrayBodyConverted.add(value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); return putDateTimeRfc1123ValidDelegate(call.execute()); } @@ -2296,7 +2301,12 @@ public ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final return null; } Validator.validate(arrayBody, serviceCallback); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + List arrayBodyConverted = new ArrayList(); + for (DateTime item : arrayBody) { + DateTimeRfc1123 value = new DateTimeRfc1123(item); + arrayBodyConverted.add(value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java index e8a4207447ffc..aa6910fc4de5d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java @@ -105,7 +105,7 @@ public ServiceResponse getNull() throws ErrorException, IOException { ServiceResponse response = getNullDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime();; + body = response.getBody().getDateTime(); } return new ServiceResponse(body, response.getResponse()); } @@ -160,7 +160,7 @@ public ServiceResponse getInvalid() throws ErrorException, IOException ServiceResponse response = getInvalidDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime();; + body = response.getBody().getDateTime(); } return new ServiceResponse(body, response.getResponse()); } @@ -215,7 +215,7 @@ public ServiceResponse getOverflow() throws ErrorException, IOExceptio ServiceResponse response = getOverflowDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime();; + body = response.getBody().getDateTime(); } return new ServiceResponse(body, response.getResponse()); } @@ -270,7 +270,7 @@ public ServiceResponse getUnderflow() throws ErrorException, IOExcepti ServiceResponse response = getUnderflowDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime();; + body = response.getBody().getDateTime(); } return new ServiceResponse(body, response.getResponse()); } @@ -326,7 +326,8 @@ public ServiceResponse putUtcMaxDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMaxDateTime(datetimeBodyConverted); return putUtcMaxDateTimeDelegate(call.execute()); } @@ -346,7 +347,8 @@ public ServiceCall putUtcMaxDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMaxDateTime(datetimeBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -380,7 +382,7 @@ public ServiceResponse getUtcLowercaseMaxDateTime() throws ErrorExcept ServiceResponse response = getUtcLowercaseMaxDateTimeDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime();; + body = response.getBody().getDateTime(); } return new ServiceResponse(body, response.getResponse()); } @@ -435,7 +437,7 @@ public ServiceResponse getUtcUppercaseMaxDateTime() throws ErrorExcept ServiceResponse response = getUtcUppercaseMaxDateTimeDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime();; + body = response.getBody().getDateTime(); } return new ServiceResponse(body, response.getResponse()); } @@ -491,7 +493,8 @@ public ServiceResponse putUtcMinDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMinDateTime(datetimeBodyConverted); return putUtcMinDateTimeDelegate(call.execute()); } @@ -511,7 +514,8 @@ public ServiceCall putUtcMinDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMinDateTime(datetimeBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -545,7 +549,7 @@ public ServiceResponse getUtcMinDateTime() throws ErrorException, IOEx ServiceResponse response = getUtcMinDateTimeDelegate(call.execute()); DateTime body = null; if (response.getBody() != null) { - body = response.getBody().getDateTime();; + body = response.getBody().getDateTime(); } return new ServiceResponse(body, response.getResponse()); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java index 52bdc52882c0e..9eb9216ca1d77 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java @@ -2200,7 +2200,7 @@ public ServiceResponse> getDateTimeRfc1123Valid() throws E DateTime value; value = entry.getValue().getDateTime(); body.put(entry.getKey(), value); - }; + } } return new ServiceResponse>(body, response.getResponse()); } @@ -2262,7 +2262,12 @@ public ServiceResponse putDateTimeRfc1123Valid(Map array throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null."); } Validator.validate(arrayBody); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + Map arrayBodyConverted = new HashMap(); + for (Map.Entry entry : arrayBody.entrySet()) { + DateTimeRfc1123 value = new DateTimeRfc1123(entry.getValue()); + arrayBodyConverted.put(entry.getKey(), value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); return putDateTimeRfc1123ValidDelegate(call.execute()); } @@ -2283,7 +2288,12 @@ public ServiceCall putDateTimeRfc1123ValidAsync(Map arrayBody, return null; } Validator.validate(arrayBody, serviceCallback); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + Map arrayBodyConverted = new HashMap(); + for (Map.Entry entry : arrayBody.entrySet()) { + DateTimeRfc1123 value = new DateTimeRfc1123(entry.getValue()); + arrayBodyConverted.put(entry.getKey(), value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java index e02b9db18446e..94db4668feedc 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java @@ -88,7 +88,8 @@ public ServiceResponse uploadFile(byte[] fileContent, String fileNa if (fileName == null) { throw new IllegalArgumentException("Parameter fileName is required and cannot be null."); } - Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("multipart/form-data"), fileContent); + Call call = service.uploadFile(fileContentConverted, fileName); return uploadFileDelegate(call.execute()); } @@ -113,7 +114,8 @@ public ServiceCall uploadFileAsync(byte[] fileContent, String fileName, final Se serviceCallback.failure(new IllegalArgumentException("Parameter fileName is required and cannot be null.")); return null; } - Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("multipart/form-data"), fileContent); + Call call = service.uploadFile(fileContentConverted, fileName); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -148,7 +150,8 @@ public ServiceResponse uploadFileViaBody(byte[] fileContent) throws if (fileContent == null) { throw new IllegalArgumentException("Parameter fileContent is required and cannot be null."); } - Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("application/octet-stream"), fileContent); + Call call = service.uploadFileViaBody(fileContentConverted); return uploadFileViaBodyDelegate(call.execute()); } @@ -168,7 +171,8 @@ public ServiceCall uploadFileViaBodyAsync(byte[] fileContent, final ServiceCallb serviceCallback.failure(new IllegalArgumentException("Parameter fileContent is required and cannot be null.")); return null; } - Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("application/octet-stream"), fileContent); + Call call = service.uploadFileViaBody(fileContentConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 80c9db76accc4..47310c19f5823 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -155,7 +155,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/datetimerfc1123") - Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") DateTimeRfc1123 value); + Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") String value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/datetimerfc1123") @@ -1130,7 +1130,8 @@ public ServiceResponse paramDate(String scenario, LocalDate value) throws if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - Call call = service.paramDate(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDate(scenario, valueConverted); return paramDateDelegate(call.execute()); } @@ -1155,7 +1156,8 @@ public ServiceCall paramDateAsync(String scenario, LocalDate value, final Servic serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - Call call = service.paramDate(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDate(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1249,7 +1251,8 @@ public ServiceResponse paramDatetime(String scenario, DateTime value) thro if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - Call call = service.paramDatetime(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDatetime(scenario, valueConverted); return paramDatetimeDelegate(call.execute()); } @@ -1274,7 +1277,8 @@ public ServiceCall paramDatetimeAsync(String scenario, DateTime value, final Ser serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - Call call = service.paramDatetime(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDatetime(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1365,7 +1369,8 @@ public ServiceResponse paramDatetimeRfc1123(String scenario) throws ErrorE throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1386,7 +1391,8 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, final ServiceCallb return null; } final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1415,7 +1421,8 @@ public ServiceResponse paramDatetimeRfc1123(String scenario, DateTime valu if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1436,7 +1443,8 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, DateTime value, fi serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1649,7 +1657,8 @@ public ServiceResponse paramByte(String scenario, byte[] value) throws Err if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - Call call = service.paramByte(scenario, Base64.encodeBase64String(value)); + String valueConverted = Base64.encodeBase64String(value); + Call call = service.paramByte(scenario, valueConverted); return paramByteDelegate(call.execute()); } @@ -1674,7 +1683,8 @@ public ServiceCall paramByteAsync(String scenario, byte[] value, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - Call call = service.paramByte(scenario, Base64.encodeBase64String(value)); + String valueConverted = Base64.encodeBase64String(value); + Call call = service.paramByte(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1765,7 +1775,8 @@ public ServiceResponse paramEnum(String scenario) throws ErrorException, I throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } final GreyscaleColors value = null; - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramEnum(scenario, valueConverted); return paramEnumDelegate(call.execute()); } @@ -1786,7 +1797,8 @@ public ServiceCall paramEnumAsync(String scenario, final ServiceCallback s return null; } final GreyscaleColors value = null; - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramEnum(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1815,7 +1827,8 @@ public ServiceResponse paramEnum(String scenario, GreyscaleColors value) t if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramEnum(scenario, valueConverted); return paramEnumDelegate(call.execute()); } @@ -1836,7 +1849,8 @@ public ServiceCall paramEnumAsync(String scenario, GreyscaleColors value, final serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + Call call = service.paramEnum(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java index d3193904df5e1..6654a636532ab 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java @@ -86,6 +86,7 @@ public ServiceResponse update(String resourceGroupName, String avset, Map< Validator.validate(tags); AvailabilitySetUpdateParameters tags1 = new AvailabilitySetUpdateParameters(); tags1.setTags(tags); + String tagsConverted = this.client.getMapperAdapter().serializeRaw(tags); Call call = service.update(resourceGroupName, avset, tags1); return updateDelegate(call.execute()); } @@ -119,6 +120,7 @@ public ServiceCall updateAsync(String resourceGroupName, String avset, Map call = service.update(resourceGroupName, avset, tags1); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java index 9beced52bb191..eb8ab498ffdfd 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java @@ -1588,7 +1588,8 @@ public ServiceResponse postRequiredArrayHeader(List headerParamet throw new IllegalArgumentException("Parameter headerParameter is required and cannot be null."); } Validator.validate(headerParameter); - Call call = service.postRequiredArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postRequiredArrayHeader(headerParameterConverted); return postRequiredArrayHeaderDelegate(call.execute()); } @@ -1609,7 +1610,8 @@ public ServiceCall postRequiredArrayHeaderAsync(List headerParameter, fi return null; } Validator.validate(headerParameter, serviceCallback); - Call call = service.postRequiredArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postRequiredArrayHeader(headerParameterConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1639,7 +1641,8 @@ private ServiceResponse postRequiredArrayHeaderDelegate(Response postOptionalArrayHeader() throws ErrorException, IOException { final List headerParameter = null; - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postOptionalArrayHeader(headerParameterConverted); return postOptionalArrayHeaderDelegate(call.execute()); } @@ -1655,7 +1658,8 @@ public ServiceCall postOptionalArrayHeaderAsync(final ServiceCallback serv throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List headerParameter = null; - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postOptionalArrayHeader(headerParameterConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1680,7 +1684,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse postOptionalArrayHeader(List headerParameter) throws ErrorException, IOException { Validator.validate(headerParameter); - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postOptionalArrayHeader(headerParameterConverted); return postOptionalArrayHeaderDelegate(call.execute()); } @@ -1697,7 +1702,8 @@ public ServiceCall postOptionalArrayHeaderAsync(List headerParameter, fi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(headerParameter, serviceCallback); - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postOptionalArrayHeader(headerParameterConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java index 0786c24f6b576..b8355565b7329 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 @@ -829,7 +829,8 @@ public ServiceResponse enumValid(UriColor enumPath) throws ErrorException, if (enumPath == null) { throw new IllegalArgumentException("Parameter enumPath is required and cannot be null."); } - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumPath)); + String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); + Call call = service.enumValid(enumPathConverted); return enumValidDelegate(call.execute()); } @@ -849,7 +850,8 @@ public ServiceCall enumValidAsync(UriColor enumPath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter enumPath is required and cannot be null.")); return null; } - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumPath)); + String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); + Call call = service.enumValid(enumPathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -884,7 +886,8 @@ public ServiceResponse enumNull(UriColor enumPath) throws ErrorException, if (enumPath == null) { throw new IllegalArgumentException("Parameter enumPath is required and cannot be null."); } - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumPath)); + String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); + Call call = service.enumNull(enumPathConverted); return enumNullDelegate(call.execute()); } @@ -904,7 +907,8 @@ public ServiceCall enumNullAsync(UriColor enumPath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter enumPath is required and cannot be null.")); return null; } - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumPath)); + String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); + Call call = service.enumNull(enumPathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -939,7 +943,8 @@ public ServiceResponse byteMultiByte(byte[] bytePath) throws ErrorExceptio if (bytePath == null) { throw new IllegalArgumentException("Parameter bytePath is required and cannot be null."); } - Call call = service.byteMultiByte(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteMultiByte(bytePathConverted); return byteMultiByteDelegate(call.execute()); } @@ -959,7 +964,8 @@ public ServiceCall byteMultiByteAsync(byte[] bytePath, final ServiceCallback call = service.byteMultiByte(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteMultiByte(bytePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -990,7 +996,8 @@ private ServiceResponse byteMultiByteDelegate(Response respo */ public ServiceResponse byteEmpty() throws ErrorException, IOException { final byte[] bytePath = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteEmpty(bytePathConverted); return byteEmptyDelegate(call.execute()); } @@ -1006,7 +1013,8 @@ public ServiceCall byteEmptyAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final byte[] bytePath = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteEmpty(bytePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1041,7 +1049,8 @@ public ServiceResponse byteNull(byte[] bytePath) throws ErrorException, IO if (bytePath == null) { throw new IllegalArgumentException("Parameter bytePath is required and cannot be null."); } - Call call = service.byteNull(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteNull(bytePathConverted); return byteNullDelegate(call.execute()); } @@ -1061,7 +1070,8 @@ public ServiceCall byteNullAsync(byte[] bytePath, final ServiceCallback se serviceCallback.failure(new IllegalArgumentException("Parameter bytePath is required and cannot be null.")); return null; } - Call call = service.byteNull(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteNull(bytePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1092,7 +1102,8 @@ private ServiceResponse byteNullDelegate(Response response) */ public ServiceResponse dateValid() throws ErrorException, IOException { final LocalDate datePath = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(datePath)); + String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); + Call call = service.dateValid(datePathConverted); return dateValidDelegate(call.execute()); } @@ -1108,7 +1119,8 @@ public ServiceCall dateValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate datePath = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(datePath)); + String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); + Call call = service.dateValid(datePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1143,7 +1155,8 @@ public ServiceResponse dateNull(LocalDate datePath) throws ErrorException, if (datePath == null) { throw new IllegalArgumentException("Parameter datePath is required and cannot be null."); } - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(datePath)); + String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); + Call call = service.dateNull(datePathConverted); return dateNullDelegate(call.execute()); } @@ -1163,7 +1176,8 @@ public ServiceCall dateNullAsync(LocalDate datePath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter datePath is required and cannot be null.")); return null; } - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(datePath)); + String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); + Call call = service.dateNull(datePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1194,7 +1208,8 @@ private ServiceResponse dateNullDelegate(Response response) */ public ServiceResponse dateTimeValid() throws ErrorException, IOException { final DateTime dateTimePath = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); + Call call = service.dateTimeValid(dateTimePathConverted); return dateTimeValidDelegate(call.execute()); } @@ -1210,7 +1225,8 @@ public ServiceCall dateTimeValidAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimePath = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); + Call call = service.dateTimeValid(dateTimePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1245,7 +1261,8 @@ public ServiceResponse dateTimeNull(DateTime dateTimePath) throws ErrorExc if (dateTimePath == null) { throw new IllegalArgumentException("Parameter dateTimePath is required and cannot be null."); } - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); + Call call = service.dateTimeNull(dateTimePathConverted); return dateTimeNullDelegate(call.execute()); } @@ -1265,7 +1282,8 @@ public ServiceCall dateTimeNullAsync(DateTime dateTimePath, final ServiceCallbac serviceCallback.failure(new IllegalArgumentException("Parameter dateTimePath is required and cannot be null.")); return null; } - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); + Call call = service.dateTimeNull(dateTimePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java index 864bbb1badf44..248416d5fca13 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java @@ -1339,7 +1339,8 @@ private ServiceResponse stringNullDelegate(Response response */ public ServiceResponse enumValid() throws ErrorException, IOException { final UriColor enumQuery = null; - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumValid(enumQueryConverted); return enumValidDelegate(call.execute()); } @@ -1355,7 +1356,8 @@ public ServiceCall enumValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final UriColor enumQuery = null; - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumValid(enumQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1379,7 +1381,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumValid(UriColor enumQuery) throws ErrorException, IOException { - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumValid(enumQueryConverted); return enumValidDelegate(call.execute()); } @@ -1395,7 +1398,8 @@ public ServiceCall enumValidAsync(UriColor enumQuery, final ServiceCallback call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumValid(enumQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1426,7 +1430,8 @@ private ServiceResponse enumValidDelegate(Response response) */ public ServiceResponse enumNull() throws ErrorException, IOException { final UriColor enumQuery = null; - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumNull(enumQueryConverted); return enumNullDelegate(call.execute()); } @@ -1442,7 +1447,8 @@ public ServiceCall enumNullAsync(final ServiceCallback serviceCallback) th throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final UriColor enumQuery = null; - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumNull(enumQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1466,7 +1472,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumNull(UriColor enumQuery) throws ErrorException, IOException { - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumNull(enumQueryConverted); return enumNullDelegate(call.execute()); } @@ -1482,7 +1489,8 @@ public ServiceCall enumNullAsync(UriColor enumQuery, final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); + Call call = service.enumNull(enumQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1513,7 +1521,8 @@ private ServiceResponse enumNullDelegate(Response response) */ public ServiceResponse byteMultiByte() throws ErrorException, IOException { final byte[] byteQuery = null; - Call call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteMultiByte(byteQueryConverted); return byteMultiByteDelegate(call.execute()); } @@ -1529,7 +1538,8 @@ public ServiceCall byteMultiByteAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final byte[] byteQuery = null; - Call call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteMultiByte(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1553,7 +1563,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteMultiByte(byte[] byteQuery) throws ErrorException, IOException { - Call call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteMultiByte(byteQueryConverted); return byteMultiByteDelegate(call.execute()); } @@ -1569,7 +1580,8 @@ public ServiceCall byteMultiByteAsync(byte[] byteQuery, final ServiceCallback call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteMultiByte(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1600,7 +1612,8 @@ private ServiceResponse byteMultiByteDelegate(Response respo */ public ServiceResponse byteEmpty() throws ErrorException, IOException { final byte[] byteQuery = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteEmpty(byteQueryConverted); return byteEmptyDelegate(call.execute()); } @@ -1616,7 +1629,8 @@ public ServiceCall byteEmptyAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final byte[] byteQuery = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteEmpty(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1647,7 +1661,8 @@ private ServiceResponse byteEmptyDelegate(Response response) */ public ServiceResponse byteNull() throws ErrorException, IOException { final byte[] byteQuery = null; - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteNull(byteQueryConverted); return byteNullDelegate(call.execute()); } @@ -1663,7 +1678,8 @@ public ServiceCall byteNullAsync(final ServiceCallback serviceCallback) th throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final byte[] byteQuery = null; - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteNull(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1687,7 +1703,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteNull(byte[] byteQuery) throws ErrorException, IOException { - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteNull(byteQueryConverted); return byteNullDelegate(call.execute()); } @@ -1703,7 +1720,8 @@ public ServiceCall byteNullAsync(byte[] byteQuery, final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteNull(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1734,7 +1752,8 @@ private ServiceResponse byteNullDelegate(Response response) */ public ServiceResponse dateValid() throws ErrorException, IOException { final LocalDate dateQuery = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(dateQuery)); + String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); + Call call = service.dateValid(dateQueryConverted); return dateValidDelegate(call.execute()); } @@ -1750,7 +1769,8 @@ public ServiceCall dateValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate dateQuery = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(dateQuery)); + String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); + Call call = service.dateValid(dateQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1781,7 +1801,8 @@ private ServiceResponse dateValidDelegate(Response response) */ public ServiceResponse dateNull() throws ErrorException, IOException { final LocalDate dateQuery = null; - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); + Call call = service.dateNull(dateQueryConverted); return dateNullDelegate(call.execute()); } @@ -1797,7 +1818,8 @@ public ServiceCall dateNullAsync(final ServiceCallback serviceCallback) th throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate dateQuery = null; - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); + Call call = service.dateNull(dateQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1821,7 +1843,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateNull(LocalDate dateQuery) throws ErrorException, IOException { - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); + Call call = service.dateNull(dateQueryConverted); return dateNullDelegate(call.execute()); } @@ -1837,7 +1860,8 @@ public ServiceCall dateNullAsync(LocalDate dateQuery, final ServiceCallback call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); + Call call = service.dateNull(dateQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1868,7 +1892,8 @@ private ServiceResponse dateNullDelegate(Response response) */ public ServiceResponse dateTimeValid() throws ErrorException, IOException { final DateTime dateTimeQuery = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); + Call call = service.dateTimeValid(dateTimeQueryConverted); return dateTimeValidDelegate(call.execute()); } @@ -1884,7 +1909,8 @@ public ServiceCall dateTimeValidAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimeQuery = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); + Call call = service.dateTimeValid(dateTimeQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1915,7 +1941,8 @@ private ServiceResponse dateTimeValidDelegate(Response respo */ public ServiceResponse dateTimeNull() throws ErrorException, IOException { final DateTime dateTimeQuery = null; - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); + Call call = service.dateTimeNull(dateTimeQueryConverted); return dateTimeNullDelegate(call.execute()); } @@ -1931,7 +1958,8 @@ public ServiceCall dateTimeNullAsync(final ServiceCallback serviceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimeQuery = null; - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); + Call call = service.dateTimeNull(dateTimeQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1955,7 +1983,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateTimeNull(DateTime dateTimeQuery) throws ErrorException, IOException { - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); + Call call = service.dateTimeNull(dateTimeQueryConverted); return dateTimeNullDelegate(call.execute()); } @@ -1971,7 +2000,8 @@ public ServiceCall dateTimeNullAsync(DateTime dateTimeQuery, final ServiceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); + Call call = service.dateTimeNull(dateTimeQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2002,7 +2032,8 @@ private ServiceResponse dateTimeNullDelegate(Response respon */ public ServiceResponse arrayStringCsvValid() throws ErrorException, IOException { final List arrayQuery = null; - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvValid(arrayQueryConverted); return arrayStringCsvValidDelegate(call.execute()); } @@ -2018,7 +2049,8 @@ public ServiceCall arrayStringCsvValidAsync(final ServiceCallback serviceC throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List arrayQuery = null; - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2043,7 +2075,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringCsvValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvValid(arrayQueryConverted); return arrayStringCsvValidDelegate(call.execute()); } @@ -2060,7 +2093,8 @@ public ServiceCall arrayStringCsvValidAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2091,7 +2125,8 @@ private ServiceResponse arrayStringCsvValidDelegate(Response */ public ServiceResponse arrayStringCsvNull() throws ErrorException, IOException { final List arrayQuery = null; - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvNull(arrayQueryConverted); return arrayStringCsvNullDelegate(call.execute()); } @@ -2107,7 +2142,8 @@ public ServiceCall arrayStringCsvNullAsync(final ServiceCallback serviceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List arrayQuery = null; - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvNull(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2132,7 +2168,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringCsvNull(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvNull(arrayQueryConverted); return arrayStringCsvNullDelegate(call.execute()); } @@ -2149,7 +2186,8 @@ public ServiceCall arrayStringCsvNullAsync(List arrayQuery, final Servic throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvNull(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2180,7 +2218,8 @@ private ServiceResponse arrayStringCsvNullDelegate(Response */ public ServiceResponse arrayStringCsvEmpty() throws ErrorException, IOException { final List arrayQuery = null; - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); return arrayStringCsvEmptyDelegate(call.execute()); } @@ -2196,7 +2235,8 @@ public ServiceCall arrayStringCsvEmptyAsync(final ServiceCallback serviceC throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List arrayQuery = null; - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2221,7 +2261,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringCsvEmpty(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); return arrayStringCsvEmptyDelegate(call.execute()); } @@ -2238,7 +2279,8 @@ public ServiceCall arrayStringCsvEmptyAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2269,7 +2311,8 @@ private ServiceResponse arrayStringCsvEmptyDelegate(Response */ public ServiceResponse arrayStringSsvValid() throws ErrorException, IOException { final List arrayQuery = null; - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); + Call call = service.arrayStringSsvValid(arrayQueryConverted); return arrayStringSsvValidDelegate(call.execute()); } @@ -2285,7 +2328,8 @@ public ServiceCall arrayStringSsvValidAsync(final ServiceCallback serviceC throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List arrayQuery = null; - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); + Call call = service.arrayStringSsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2310,7 +2354,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringSsvValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); + Call call = service.arrayStringSsvValid(arrayQueryConverted); return arrayStringSsvValidDelegate(call.execute()); } @@ -2327,7 +2372,8 @@ public ServiceCall arrayStringSsvValidAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); + Call call = service.arrayStringSsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2358,7 +2404,8 @@ private ServiceResponse arrayStringSsvValidDelegate(Response */ public ServiceResponse arrayStringTsvValid() throws ErrorException, IOException { final List arrayQuery = null; - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); + Call call = service.arrayStringTsvValid(arrayQueryConverted); return arrayStringTsvValidDelegate(call.execute()); } @@ -2374,7 +2421,8 @@ public ServiceCall arrayStringTsvValidAsync(final ServiceCallback serviceC throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List arrayQuery = null; - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); + Call call = service.arrayStringTsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2399,7 +2447,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringTsvValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); + Call call = service.arrayStringTsvValid(arrayQueryConverted); return arrayStringTsvValidDelegate(call.execute()); } @@ -2416,7 +2465,8 @@ public ServiceCall arrayStringTsvValidAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); + Call call = service.arrayStringTsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2447,7 +2497,8 @@ private ServiceResponse arrayStringTsvValidDelegate(Response */ public ServiceResponse arrayStringPipesValid() throws ErrorException, IOException { final List arrayQuery = null; - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); + Call call = service.arrayStringPipesValid(arrayQueryConverted); return arrayStringPipesValidDelegate(call.execute()); } @@ -2463,7 +2514,8 @@ public ServiceCall arrayStringPipesValidAsync(final ServiceCallback servic throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List arrayQuery = null; - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); + Call call = service.arrayStringPipesValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2488,7 +2540,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringPipesValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); + Call call = service.arrayStringPipesValid(arrayQueryConverted); return arrayStringPipesValidDelegate(call.execute()); } @@ -2505,7 +2558,8 @@ public ServiceCall arrayStringPipesValidAsync(List arrayQuery, final Ser throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); + Call call = service.arrayStringPipesValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 15f1f0c63f100..5367aac11395a 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -185,7 +185,7 @@ public string MethodParameterApiInvocation List invocations = new List(); foreach (var parameter in OrderedRetrofitParameters) { - invocations.Add(parameter.Invoke(parameter.Name, ClientReference)); + invocations.Add(parameter.WireName); } var declaration = string.Join(", ", invocations); @@ -193,6 +193,21 @@ public string MethodParameterApiInvocation } } + public string ParameterConversion + { + get + { + IndentedStringBuilder builder = new IndentedStringBuilder(); + foreach (var p in ParameterModels) { + if (p.NeedsConversion) + { + builder.Append(p.ConvertToWireType(p.Name, ClientReference)); + } + } + return builder.ToString(); + } + } + /// /// Generates input mapping code block. /// @@ -515,7 +530,7 @@ public virtual string ResponseGeneration ReturnTypeModel.GenericBodyWireTypeString, this.Name.ToCamelCase()); builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType.Name) .AppendLine("if (response.getBody() != null) {") - .Indent().AppendLine("{0};", ReturnTypeModel.ConvertBodyToClientType("response.getBody()", "body")) + .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("response.getBody()", "body")) .Outdent().AppendLine("}"); return builder.ToString(); } diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index bf299b19a9f95..8c20b2b88d51c 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -66,6 +66,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); @Model.ResponseGeneration return @Model.ReturnValue; @@ -125,6 +126,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); @Model.ServiceCallConstruction call.enqueue(new @Model.InternalCallback<@(Model.ReturnTypeModel.ClientCallbackTypeString)>(serviceCallback) { @@ -196,6 +198,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); @Model.ResponseGeneration return @Model.ReturnValue; @@ -251,6 +254,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); @Model.ServiceCallConstruction call.enqueue(new @Model.InternalCallback<@(Model.ReturnTypeModel.ClientCallbackTypeString)>(serviceCallback) { diff --git a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs index fc25fb4e2b3c3..cd19c894d7c49 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs @@ -24,6 +24,12 @@ public ParameterModel(Parameter parameter, Method method) { this.Type = ((ITypeModel) Type).InstanceType(); } + _wireName = this.Name.ToCamelCase(); + if (NeedsConversion) + { + _wireName += "Converted"; + } + _implImports = new List(); } public ITypeModel ClientType @@ -54,47 +60,102 @@ public ITypeModel WireType } } - public string Invoke(string reference, string clientReference) + private string _wireName; + + public string WireName + { + get + { + return _wireName; + } + } + + public bool NeedsConversion + { + get + { + return ClientType != WireType; + } + } + + public string ConvertToWireType(string source, string clientReference) { if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData) { var primary = ClientType as PrimaryTypeModel; var sequence = ClientType as SequenceTypeModel; - if (primary != null && primary.Name != "LocalDate" && primary.Name != "DateTime") + if (primary != null && !NeedsSpecialSerialization(primary)) { - if (primary.Type == KnownPrimaryType.ByteArray) - { - return "Base64.encodeBase64String(" + reference + ")"; - } - else - { - return reference; - } + return source; + } + if (primary != null && primary.IsPrimaryType(KnownPrimaryType.ByteArray)) + { + return string.Format(CultureInfo.InvariantCulture, "{0} {1} = Base64.encodeBase64String({2});", WireType.Name, _wireName, source); } else if (sequence != null) { - return clientReference + ".getMapperAdapter().serializeList(" + reference + - ", CollectionFormat." + CollectionFormat.ToString().ToUpper(CultureInfo.InvariantCulture) + ")"; + return string.Format(CultureInfo.InvariantCulture, + "{0} {1} = {2}.getMapperAdapter().serializeList({3}, CollectionFormat.{4});", + WireType.Name, + _wireName, + clientReference, + source, + CollectionFormat.ToString().ToUpper(CultureInfo.InvariantCulture)); } else { - return clientReference + ".getMapperAdapter().serializeRaw(" + reference + ")"; + return string.Format(CultureInfo.InvariantCulture, "{0} {1} = {2}.getMapperAdapter().serializeRaw({3});", + WireType.Name, + _wireName, + clientReference, + source); } } - else if (WireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + + return convertClientTypeToWireType(WireType, source, _wireName, clientReference); + } + + private string convertClientTypeToWireType(ITypeModel wireType, string source, string target, string clientReference, int level = 0) + { + IndentedStringBuilder builder = new IndentedStringBuilder(); + if (wireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + builder.AppendLine("DateTimeRfc1123 {0} = new DateTimeRfc1123({1});", target, source); + } + else if (wireType.IsPrimaryType(KnownPrimaryType.Stream)) { - return string.Format(CultureInfo.InvariantCulture, "new DateTimeRfc1123({0})", reference); + builder.AppendLine("RequestBody {0} = RequestBody.create(MediaType.parse(\"{1}\"), {2});", + target, _method.RequestContentType, source); } - else if (WireType.IsPrimaryType(KnownPrimaryType.Stream)) + else if (wireType is SequenceTypeModel) { - return string.Format(CultureInfo.InvariantCulture, - "RequestBody.create(MediaType.parse(\"{0}\"), {1})", - _method.RequestContentType, reference); + var sequenceType = wireType as SequenceTypeModel; + var elementType = sequenceType.ElementTypeModel; + var itemName = string.Format("item{0}", level == 0 ? "" : level.ToString()); + var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + builder.AppendLine("{0} {1} = new ArrayList<{2}>();", wireType.Name ,target, elementType.Name) + .AppendLine("for ({0} {1} : {2}) {{", elementType.ParameterVariant.Name, itemName, source) + .Indent().AppendLine(convertClientTypeToWireType(elementType, itemName, itemTarget, clientReference, level + 1)) + .AppendLine("{0}.add({1});", target, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.ArrayList"); + return builder.ToString(); } - else + else if (wireType is DictionaryTypeModel) { - return reference; + var dictionaryType = wireType as DictionaryTypeModel; + var valueType = dictionaryType.ValueTypeModel; + var itemName = string.Format("entry{0}", level == 0 ? "" : level.ToString()); + var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + builder.AppendLine("{0} {1} = new HashMap();", wireType.Name, target, valueType.Name) + .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.ParameterVariant.Name, itemName, source) + .Indent().AppendLine(convertClientTypeToWireType(valueType, itemName + ".getValue()", itemTarget, clientReference, level + 1)) + .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.HashMap"); + return builder.ToString(); } + return builder.ToString(); } public IEnumerable InterfaceImports @@ -115,16 +176,14 @@ public IEnumerable RetrofitImports { imports.AddRange(ClientType.Imports); } - if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - imports.Add("com.microsoft.rest.DateTimeRfc1123"); - } // parameter location imports.Add(LocationImport(this.Location)); return imports; } } + private List _implImports; + public IEnumerable ImplImports { get @@ -141,10 +200,6 @@ public IEnumerable ImplImports imports.Add("com.microsoft.rest.serializer.CollectionFormat"); } } - if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - imports.Add("com.microsoft.rest.DateTimeRfc1123"); - } if (Type.IsPrimaryType(KnownPrimaryType.Stream) && Location == ParameterLocation.Body) { imports.Add("okhttp3.RequestBody"); @@ -173,7 +228,11 @@ private string LocationImport(ParameterLocation parameterLocation) private bool NeedsSpecialSerialization(IType type) { var known = type as PrimaryType; - return (known != null && (known.Name == "LocalDate" || known.Name == "DateTime" || known.Type == KnownPrimaryType.ByteArray)) || + return known != null && + type.IsPrimaryType(KnownPrimaryType.Date) || + type.IsPrimaryType(KnownPrimaryType.DateTime) || + type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123) || + type.IsPrimaryType(KnownPrimaryType.ByteArray) || type is EnumType || type is CompositeType || type is SequenceType || type is DictionaryType; } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs index 9fa9315e31412..18ca704617c6d 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -113,12 +113,12 @@ public ITypeModel HeaderWireType public string ConvertBodyToClientType(string source, string target) { - return converToClientType(BodyWireType, source, target); + return convertToClientType(BodyWireType, source, target); } public string ConvertHeaderToClientType(string source, string target) { - return converToClientType(HeaderWireType, source, target); + return convertToClientType(HeaderWireType, source, target); } #endregion @@ -239,7 +239,7 @@ public IEnumerable ImplImports } } - private string converToClientType(ITypeModel type, string source, string target, int level = 0) + private string convertToClientType(ITypeModel type, string source, string target, int level = 0) { if (type == null) { @@ -259,7 +259,7 @@ private string converToClientType(ITypeModel type, string source, string target, builder.AppendLine("{0} = new ArrayList<{1}>();", target, elementType.ResponseVariant.Name) .AppendLine("for ({0} {1} : {2}) {{", elementType.Name, itemName, source) .Indent().AppendLine("{0} {1};", elementType.ResponseVariant.Name, itemTarget) - .AppendLine(converToClientType(elementType, itemName, itemTarget, level + 1)) + .AppendLine(convertToClientType(elementType, itemName, itemTarget, level + 1)) .AppendLine("{0}.add({1});", target, itemTarget) .Outdent().Append("}"); _implImports.Add("java.util.ArrayList"); @@ -273,7 +273,7 @@ private string converToClientType(ITypeModel type, string source, string target, builder.AppendLine("{0} = new HashMap();", target, valueType.ResponseVariant.Name) .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.Name, itemName, source) .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget) - .AppendLine(converToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1)) + .AppendLine(convertToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1)) .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget) .Outdent().Append("}"); _implImports.Add("java.util.HashMap"); From f32e739f1f9d1ea9cd7b52f2b20dc89c9fa36ac8 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Fri, 25 Mar 2016 17:22:21 -0700 Subject: [PATCH 41/99] fix test compilation errors --- .../fixtures/header/HeaderOperationsImpl.java | 1 - .../java/fixtures/bodyarray/ArrayTests.java | 23 ++++++++++--------- .../bodydictionary/DictionaryTests.java | 19 ++++++++------- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 47310c19f5823..5393bcac557bd 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -11,7 +11,6 @@ package fixtures.header; import com.google.common.reflect.TypeToken; -import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java index fec4046bf5035..03b7e211ba6b3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.exc.InvalidFormatException; -import com.microsoft.rest.DateTimeRfc1123; -import fixtures.bodyarray.models.ErrorException; -import fixtures.bodyarray.models.Product; + import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; @@ -21,6 +19,9 @@ import java.util.Map; import java.util.UUID; +import fixtures.bodyarray.models.ErrorException; +import fixtures.bodyarray.models.Product; + public class ArrayTests { private static AutoRestSwaggerBATArrayService client; @@ -355,11 +356,11 @@ public void getDateTimeInvalidString() throws Exception { @Test public void getDateTimeRfc1123Valid() throws Exception { - List result = client.getArrayOperations().getDateTimeRfc1123Valid().getBody(); - Object[] expected = new DateTimeRfc1123[] { - new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)) + List result = client.getArrayOperations().getDateTimeRfc1123Valid().getBody(); + Object[] expected = new DateTime[] { + new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC), + new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC), + new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC) }; Assert.assertArrayEquals(expected, result.toArray()); } @@ -367,9 +368,9 @@ public void getDateTimeRfc1123Valid() throws Exception { @Test public void putDateTimeRfc1123Valid() throws Exception { client.getArrayOperations().putDateTimeRfc1123Valid(Arrays.asList( - new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)) + new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC), + new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC), + new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC) )); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java index 1847a7a209a8d..688bd71cfa805 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.exc.InvalidFormatException; -import com.microsoft.rest.DateTimeRfc1123; import fixtures.bodydictionary.models.Widget; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -371,20 +370,20 @@ public void getDateTimeInvalidString() throws Exception { @Test public void getDateTimeRfc1123Valid() throws Exception { - Map result = client.getDictionaryOperations().getDateTimeRfc1123Valid().getBody(); - Map expected = new HashMap(); - expected.put("0", new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC))); - expected.put("1", new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC))); - expected.put("2", new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC))); + Map result = client.getDictionaryOperations().getDateTimeRfc1123Valid().getBody(); + Map expected = new HashMap(); + expected.put("0", new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)); + expected.put("1", new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)); + expected.put("2", new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)); Assert.assertEquals(expected, result); } @Test public void putDateTimeRfc1123Valid() throws Exception { - Map testdata = new HashMap(); - testdata.put("0", new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC))); - testdata.put("1", new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC))); - testdata.put("2", new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC))); + Map testdata = new HashMap(); + testdata.put("0", new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)); + testdata.put("1", new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)); + testdata.put("2", new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)); client.getDictionaryOperations().putDateTimeRfc1123Valid(testdata); } From 78c499deb328cd70ece8c0bf3f7ecbab8144a95c Mon Sep 17 00:00:00 2001 From: David Justice Date: Sat, 26 Mar 2016 07:37:26 -0700 Subject: [PATCH 42/99] Update swagger-extensions.json --- schema/swagger-extensions.json | 269 +-------------------------------- 1 file changed, 3 insertions(+), 266 deletions(-) diff --git a/schema/swagger-extensions.json b/schema/swagger-extensions.json index d00484f12ab88..199078f32eee3 100644 --- a/schema/swagger-extensions.json +++ b/schema/swagger-extensions.json @@ -65,10 +65,10 @@ "$ref": "#/definitions/responseDefinitions" }, "security": { - "$ref": "#/definitions/security" + "$ref": "http://json.schemastore.org/swagger-2.0#/definitions/security" }, "securityDefinitions": { - "$ref": "#/definitions/securityDefinitions" + "$ref": "http://json.schemastore.org/swagger-2.0#/definitions/securityDefinitions" }, "tags": { "type": "array", @@ -293,7 +293,7 @@ "default": false }, "security": { - "$ref": "#/definitions/security" + "$ref": "http://json.schemastore.org/swagger-2.0#/definitions/security" }, "x-ms-odata": { "$ref": "#/definitions/xmsOData" @@ -1265,23 +1265,6 @@ } } }, - "security": { - "type": "array", - "items": { - "$ref": "#/definitions/securityRequirement" - }, - "uniqueItems": true - }, - "securityRequirement": { - "type": "object", - "additionalProperties": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - }, "xml": { "type": "object", "additionalProperties": false, @@ -1333,252 +1316,6 @@ } } }, - "securityDefinitions": { - "type": "object", - "additionalProperties": { - "oneOf": [ - { - "$ref": "#/definitions/basicAuthenticationSecurity" - }, - { - "$ref": "#/definitions/apiKeySecurity" - }, - { - "$ref": "#/definitions/oauth2ImplicitSecurity" - }, - { - "$ref": "#/definitions/oauth2PasswordSecurity" - }, - { - "$ref": "#/definitions/oauth2ApplicationSecurity" - }, - { - "$ref": "#/definitions/oauth2AccessCodeSecurity" - } - ] - } - }, - "basicAuthenticationSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "basic" - ] - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "apiKeySecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "name", - "in" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "apiKey" - ] - }, - "name": { - "type": "string" - }, - "in": { - "type": "string", - "enum": [ - "header", - "query" - ] - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2ImplicitSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "authorizationUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "implicit" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "authorizationUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2PasswordSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "password" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2ApplicationSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "application" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2AccessCodeSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "authorizationUrl", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "accessCode" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "authorizationUrl": { - "type": "string", - "format": "uri" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2Scopes": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, "mediaTypeList": { "type": "array", "items": { From 3b59c0f90026183eb73412920db32ce292ee6cb6 Mon Sep 17 00:00:00 2001 From: "Dmitry.Tretyakov" Date: Mon, 28 Mar 2016 17:36:40 +0300 Subject: [PATCH 43/99] Fix status code validation in java client --- .../src/main/java/com/microsoft/azure/AzureClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java index 77c8c6c0e48cf..2f3569fc51c59 100644 --- a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java +++ b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java @@ -355,7 +355,7 @@ public AsyncPollingTask getPostOrDeleteResultAsync(Response } else { responseBody = response.errorBody(); } - if (statusCode != 200 && statusCode != 201 && statusCode != 202) { + if (statusCode != 200 && statusCode != 202 && statusCode != 204) { CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); exception.setResponse(response); try { From e8b8f7d18bc558c94367fc787c35f3242b0f1f8a Mon Sep 17 00:00:00 2001 From: annatisch Date: Mon, 28 Mar 2016 08:51:15 -0700 Subject: [PATCH 44/99] LRO polling fix for status enums --- .../Python/msrestazure/msrestazure/azure_operation.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py index 085082b6ce028..50a8c4e30f5a5 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py @@ -41,14 +41,20 @@ def finished(status): + if hasattr(status, 'value'): + return status.value.lower() in FINISHED return str(status).lower() in FINISHED def failed(status): + if hasattr(status, 'value'): + return status.value.lower() in FAILED return str(status).lower() in FAILED def succeeded(status): + if hasattr(status, 'value'): + return status.value.lower() in SUCCEEDED return str(status).lower() in SUCCEEDED From 32a8ff13bb2222d33067b188e8233731529515ce Mon Sep 17 00:00:00 2001 From: annatisch Date: Mon, 28 Mar 2016 09:00:50 -0700 Subject: [PATCH 45/99] Edited changes --- .../Python/msrestazure/msrestazure/azure_operation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py index 50a8c4e30f5a5..0386b3a30b5cb 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py @@ -42,19 +42,19 @@ def finished(status): if hasattr(status, 'value'): - return status.value.lower() in FINISHED + status = status.value return str(status).lower() in FINISHED def failed(status): if hasattr(status, 'value'): - return status.value.lower() in FAILED + status = status.value return str(status).lower() in FAILED def succeeded(status): if hasattr(status, 'value'): - return status.value.lower() in SUCCEEDED + status = status.value return str(status).lower() in SUCCEEDED From ecb8a4c0bb8c9745f9df1a743fe6a244fb5ea651 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 28 Mar 2016 10:37:01 -0700 Subject: [PATCH 46/99] Remove unnecessary serializations for some primary types --- .../azurespecials/OdataOperationsImpl.java | 10 +-- .../fixtures/bodystring/models/Colors.java | 5 ++ .../fixtures/header/HeaderOperationsImpl.java | 41 +++++------ .../header/models/GreyscaleColors.java | 5 ++ .../AvailabilitySetsOperationsImpl.java | 2 - .../fixtures/url/PathsOperationsImpl.java | 48 +++++-------- .../fixtures/url/QueriesOperationsImpl.java | 72 +++++++------------ .../java/fixtures/url/models/UriColor.java | 5 ++ .../fixtures/validation/models/EnumConst.java | 5 ++ .../test/java/fixtures/url/QueriesTests.java | 2 + .../Java/Java/GlobalSuppressions.cs | 7 ++ .../Java/Java/Templates/EnumTemplate.cshtml | 6 ++ .../Java/Java/TypeModels/ParameterModel.cs | 32 +++------ .../Java/Java/TypeModels/ResponseModel.cs | 8 +-- 14 files changed, 113 insertions(+), 135 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java index d8ff6ea5bd65b..75777653172cf 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java @@ -57,7 +57,7 @@ public OdataOperationsImpl(Retrofit retrofit, AutoRestAzureSpecialParametersTest interface OdataService { @Headers("Content-Type: application/json; charset=utf-8") @GET("azurespecials/odata/filter") - Call getWithFilter(@Query("$filter") String filter, @Query("$top") Integer top, @Query("$orderby") String orderby, @Header("accept-language") String acceptLanguage); + Call getWithFilter(@Query("$filter") OdataFilter filter, @Query("$top") Integer top, @Query("$orderby") String orderby, @Header("accept-language") String acceptLanguage); } @@ -72,7 +72,7 @@ public ServiceResponse getWithFilter() throws ErrorException, IOException final OdataFilter filter = null; final Integer top = null; final String orderby = null; - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); return getWithFilterDelegate(call.execute()); } @@ -90,7 +90,7 @@ public ServiceCall getWithFilterAsync(final ServiceCallback serviceCallbac final OdataFilter filter = null; final Integer top = null; final String orderby = null; - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -117,7 +117,7 @@ public void onResponse(Call call, Response response) */ public ServiceResponse getWithFilter(OdataFilter filter, Integer top, String orderby) throws ErrorException, IOException { Validator.validate(filter); - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); return getWithFilterDelegate(call.execute()); } @@ -136,7 +136,7 @@ public ServiceCall getWithFilterAsync(OdataFilter filter, Integer top, String or throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(filter, serviceCallback); - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java index 920bea2c2474c..d87da877c4845 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java @@ -59,4 +59,9 @@ public static Colors fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 5393bcac557bd..eedde38b0a9e8 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -11,6 +11,7 @@ package fixtures.header; import com.google.common.reflect.TypeToken; +import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; @@ -138,7 +139,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/date") - Call paramDate(@Header("scenario") String scenario, @Header("value") String value); + Call paramDate(@Header("scenario") String scenario, @Header("value") LocalDate value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/date") @@ -146,7 +147,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/datetime") - Call paramDatetime(@Header("scenario") String scenario, @Header("value") String value); + Call paramDatetime(@Header("scenario") String scenario, @Header("value") DateTime value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/datetime") @@ -154,7 +155,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/datetimerfc1123") - Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") String value); + Call paramDatetimeRfc1123(@Header("scenario") String scenario, @Header("value") DateTimeRfc1123 value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/datetimerfc1123") @@ -178,7 +179,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/enum") - Call paramEnum(@Header("scenario") String scenario, @Header("value") String value); + Call paramEnum(@Header("scenario") String scenario, @Header("value") GreyscaleColors value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/enum") @@ -1129,8 +1130,7 @@ public ServiceResponse paramDate(String scenario, LocalDate value) throws if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramDate(scenario, valueConverted); + Call call = service.paramDate(scenario, value); return paramDateDelegate(call.execute()); } @@ -1155,8 +1155,7 @@ public ServiceCall paramDateAsync(String scenario, LocalDate value, final Servic serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramDate(scenario, valueConverted); + Call call = service.paramDate(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1250,8 +1249,7 @@ public ServiceResponse paramDatetime(String scenario, DateTime value) thro if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramDatetime(scenario, valueConverted); + Call call = service.paramDatetime(scenario, value); return paramDatetimeDelegate(call.execute()); } @@ -1276,8 +1274,7 @@ public ServiceCall paramDatetimeAsync(String scenario, DateTime value, final Ser serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramDatetime(scenario, valueConverted); + Call call = service.paramDatetime(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1368,7 +1365,7 @@ public ServiceResponse paramDatetimeRfc1123(String scenario) throws ErrorE throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } final DateTime value = null; - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1390,7 +1387,7 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, final ServiceCallb return null; } final DateTime value = null; - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -1420,7 +1417,7 @@ public ServiceResponse paramDatetimeRfc1123(String scenario, DateTime valu if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1442,7 +1439,7 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, DateTime value, fi serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); + DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -1774,8 +1771,7 @@ public ServiceResponse paramEnum(String scenario) throws ErrorException, I throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } final GreyscaleColors value = null; - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramEnum(scenario, valueConverted); + Call call = service.paramEnum(scenario, value); return paramEnumDelegate(call.execute()); } @@ -1796,8 +1792,7 @@ public ServiceCall paramEnumAsync(String scenario, final ServiceCallback s return null; } final GreyscaleColors value = null; - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramEnum(scenario, valueConverted); + Call call = service.paramEnum(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1826,8 +1821,7 @@ public ServiceResponse paramEnum(String scenario, GreyscaleColors value) t if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramEnum(scenario, valueConverted); + Call call = service.paramEnum(scenario, value); return paramEnumDelegate(call.execute()); } @@ -1848,8 +1842,7 @@ public ServiceCall paramEnumAsync(String scenario, GreyscaleColors value, final serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - String valueConverted = this.client.getMapperAdapter().serializeRaw(value); - Call call = service.paramEnum(scenario, valueConverted); + Call call = service.paramEnum(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java index 957fc5d82c1bc..c69abd1e6071f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java @@ -59,4 +59,9 @@ public static GreyscaleColors fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java index 6654a636532ab..d3193904df5e1 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/parameterflattening/AvailabilitySetsOperationsImpl.java @@ -86,7 +86,6 @@ public ServiceResponse update(String resourceGroupName, String avset, Map< Validator.validate(tags); AvailabilitySetUpdateParameters tags1 = new AvailabilitySetUpdateParameters(); tags1.setTags(tags); - String tagsConverted = this.client.getMapperAdapter().serializeRaw(tags); Call call = service.update(resourceGroupName, avset, tags1); return updateDelegate(call.execute()); } @@ -120,7 +119,6 @@ public ServiceCall updateAsync(String resourceGroupName, String avset, Map call = service.update(resourceGroupName, avset, tags1); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { 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 b8355565b7329..fd3dc3f930d9c 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 @@ -114,11 +114,11 @@ interface PathsService { @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/enum/green%20color/{enumPath}") - Call enumValid(@Path("enumPath") String enumPath); + Call enumValid(@Path("enumPath") UriColor enumPath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/string/null/{enumPath}") - Call enumNull(@Path("enumPath") String enumPath); + Call enumNull(@Path("enumPath") UriColor enumPath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/byte/multibyte/{bytePath}") @@ -134,19 +134,19 @@ interface PathsService { @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/date/2012-01-01/{datePath}") - Call dateValid(@Path("datePath") String datePath); + Call dateValid(@Path("datePath") LocalDate datePath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/date/null/{datePath}") - Call dateNull(@Path("datePath") String datePath); + Call dateNull(@Path("datePath") LocalDate datePath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/datetime/2012-01-01T01%3A01%3A01Z/{dateTimePath}") - Call dateTimeValid(@Path("dateTimePath") String dateTimePath); + Call dateTimeValid(@Path("dateTimePath") DateTime dateTimePath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/datetime/null/{dateTimePath}") - Call dateTimeNull(@Path("dateTimePath") String dateTimePath); + Call dateTimeNull(@Path("dateTimePath") DateTime dateTimePath); } @@ -829,8 +829,7 @@ public ServiceResponse enumValid(UriColor enumPath) throws ErrorException, if (enumPath == null) { throw new IllegalArgumentException("Parameter enumPath is required and cannot be null."); } - String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); - Call call = service.enumValid(enumPathConverted); + Call call = service.enumValid(enumPath); return enumValidDelegate(call.execute()); } @@ -850,8 +849,7 @@ public ServiceCall enumValidAsync(UriColor enumPath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter enumPath is required and cannot be null.")); return null; } - String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); - Call call = service.enumValid(enumPathConverted); + Call call = service.enumValid(enumPath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -886,8 +884,7 @@ public ServiceResponse enumNull(UriColor enumPath) throws ErrorException, if (enumPath == null) { throw new IllegalArgumentException("Parameter enumPath is required and cannot be null."); } - String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); - Call call = service.enumNull(enumPathConverted); + Call call = service.enumNull(enumPath); return enumNullDelegate(call.execute()); } @@ -907,8 +904,7 @@ public ServiceCall enumNullAsync(UriColor enumPath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter enumPath is required and cannot be null.")); return null; } - String enumPathConverted = this.client.getMapperAdapter().serializeRaw(enumPath); - Call call = service.enumNull(enumPathConverted); + Call call = service.enumNull(enumPath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1102,8 +1098,7 @@ private ServiceResponse byteNullDelegate(Response response) */ public ServiceResponse dateValid() throws ErrorException, IOException { final LocalDate datePath = LocalDate.parse("2012-01-01"); - String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); - Call call = service.dateValid(datePathConverted); + Call call = service.dateValid(datePath); return dateValidDelegate(call.execute()); } @@ -1119,8 +1114,7 @@ public ServiceCall dateValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate datePath = LocalDate.parse("2012-01-01"); - String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); - Call call = service.dateValid(datePathConverted); + Call call = service.dateValid(datePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1155,8 +1149,7 @@ public ServiceResponse dateNull(LocalDate datePath) throws ErrorException, if (datePath == null) { throw new IllegalArgumentException("Parameter datePath is required and cannot be null."); } - String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); - Call call = service.dateNull(datePathConverted); + Call call = service.dateNull(datePath); return dateNullDelegate(call.execute()); } @@ -1176,8 +1169,7 @@ public ServiceCall dateNullAsync(LocalDate datePath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter datePath is required and cannot be null.")); return null; } - String datePathConverted = this.client.getMapperAdapter().serializeRaw(datePath); - Call call = service.dateNull(datePathConverted); + Call call = service.dateNull(datePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1208,8 +1200,7 @@ private ServiceResponse dateNullDelegate(Response response) */ public ServiceResponse dateTimeValid() throws ErrorException, IOException { final DateTime dateTimePath = DateTime.parse("2012-01-01T01:01:01Z"); - String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); - Call call = service.dateTimeValid(dateTimePathConverted); + Call call = service.dateTimeValid(dateTimePath); return dateTimeValidDelegate(call.execute()); } @@ -1225,8 +1216,7 @@ public ServiceCall dateTimeValidAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimePath = DateTime.parse("2012-01-01T01:01:01Z"); - String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); - Call call = service.dateTimeValid(dateTimePathConverted); + Call call = service.dateTimeValid(dateTimePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1261,8 +1251,7 @@ public ServiceResponse dateTimeNull(DateTime dateTimePath) throws ErrorExc if (dateTimePath == null) { throw new IllegalArgumentException("Parameter dateTimePath is required and cannot be null."); } - String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); - Call call = service.dateTimeNull(dateTimePathConverted); + Call call = service.dateTimeNull(dateTimePath); return dateTimeNullDelegate(call.execute()); } @@ -1282,8 +1271,7 @@ public ServiceCall dateTimeNullAsync(DateTime dateTimePath, final ServiceCallbac serviceCallback.failure(new IllegalArgumentException("Parameter dateTimePath is required and cannot be null.")); return null; } - String dateTimePathConverted = this.client.getMapperAdapter().serializeRaw(dateTimePath); - Call call = service.dateTimeNull(dateTimePathConverted); + Call call = service.dateTimeNull(dateTimePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java index 248416d5fca13..d55e48618cb8b 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java @@ -137,11 +137,11 @@ interface QueriesService { @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/enum/green%20color") - Call enumValid(@Query("enumQuery") String enumQuery); + Call enumValid(@Query("enumQuery") UriColor enumQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/enum/null") - Call enumNull(@Query("enumQuery") String enumQuery); + Call enumNull(@Query("enumQuery") UriColor enumQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/byte/multibyte") @@ -157,19 +157,19 @@ interface QueriesService { @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/date/2012-01-01") - Call dateValid(@Query("dateQuery") String dateQuery); + Call dateValid(@Query("dateQuery") LocalDate dateQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/date/null") - Call dateNull(@Query("dateQuery") String dateQuery); + Call dateNull(@Query("dateQuery") LocalDate dateQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/datetime/2012-01-01T01%3A01%3A01Z") - Call dateTimeValid(@Query("dateTimeQuery") String dateTimeQuery); + Call dateTimeValid(@Query("dateTimeQuery") DateTime dateTimeQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/datetime/null") - Call dateTimeNull(@Query("dateTimeQuery") String dateTimeQuery); + Call dateTimeNull(@Query("dateTimeQuery") DateTime dateTimeQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/array/csv/string/valid") @@ -1339,8 +1339,7 @@ private ServiceResponse stringNullDelegate(Response response */ public ServiceResponse enumValid() throws ErrorException, IOException { final UriColor enumQuery = null; - String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); - Call call = service.enumValid(enumQueryConverted); + Call call = service.enumValid(enumQuery); return enumValidDelegate(call.execute()); } @@ -1356,8 +1355,7 @@ public ServiceCall enumValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final UriColor enumQuery = null; - String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); - Call call = service.enumValid(enumQueryConverted); + Call call = service.enumValid(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1381,8 +1379,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumValid(UriColor enumQuery) throws ErrorException, IOException { - String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); - Call call = service.enumValid(enumQueryConverted); + Call call = service.enumValid(enumQuery); return enumValidDelegate(call.execute()); } @@ -1398,8 +1395,7 @@ public ServiceCall enumValidAsync(UriColor enumQuery, final ServiceCallback call = service.enumValid(enumQueryConverted); + Call call = service.enumValid(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1430,8 +1426,7 @@ private ServiceResponse enumValidDelegate(Response response) */ public ServiceResponse enumNull() throws ErrorException, IOException { final UriColor enumQuery = null; - String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); - Call call = service.enumNull(enumQueryConverted); + Call call = service.enumNull(enumQuery); return enumNullDelegate(call.execute()); } @@ -1447,8 +1442,7 @@ public ServiceCall enumNullAsync(final ServiceCallback serviceCallback) th throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final UriColor enumQuery = null; - String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); - Call call = service.enumNull(enumQueryConverted); + Call call = service.enumNull(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1472,8 +1466,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumNull(UriColor enumQuery) throws ErrorException, IOException { - String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); - Call call = service.enumNull(enumQueryConverted); + Call call = service.enumNull(enumQuery); return enumNullDelegate(call.execute()); } @@ -1489,8 +1482,7 @@ public ServiceCall enumNullAsync(UriColor enumQuery, final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - String enumQueryConverted = this.client.getMapperAdapter().serializeRaw(enumQuery); - Call call = service.enumNull(enumQueryConverted); + Call call = service.enumNull(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1752,8 +1744,7 @@ private ServiceResponse byteNullDelegate(Response response) */ public ServiceResponse dateValid() throws ErrorException, IOException { final LocalDate dateQuery = LocalDate.parse("2012-01-01"); - String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); - Call call = service.dateValid(dateQueryConverted); + Call call = service.dateValid(dateQuery); return dateValidDelegate(call.execute()); } @@ -1769,8 +1760,7 @@ public ServiceCall dateValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate dateQuery = LocalDate.parse("2012-01-01"); - String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); - Call call = service.dateValid(dateQueryConverted); + Call call = service.dateValid(dateQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1801,8 +1791,7 @@ private ServiceResponse dateValidDelegate(Response response) */ public ServiceResponse dateNull() throws ErrorException, IOException { final LocalDate dateQuery = null; - String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); - Call call = service.dateNull(dateQueryConverted); + Call call = service.dateNull(dateQuery); return dateNullDelegate(call.execute()); } @@ -1818,8 +1807,7 @@ public ServiceCall dateNullAsync(final ServiceCallback serviceCallback) th throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate dateQuery = null; - String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); - Call call = service.dateNull(dateQueryConverted); + Call call = service.dateNull(dateQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1843,8 +1831,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateNull(LocalDate dateQuery) throws ErrorException, IOException { - String dateQueryConverted = this.client.getMapperAdapter().serializeRaw(dateQuery); - Call call = service.dateNull(dateQueryConverted); + Call call = service.dateNull(dateQuery); return dateNullDelegate(call.execute()); } @@ -1860,8 +1847,7 @@ public ServiceCall dateNullAsync(LocalDate dateQuery, final ServiceCallback call = service.dateNull(dateQueryConverted); + Call call = service.dateNull(dateQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1892,8 +1878,7 @@ private ServiceResponse dateNullDelegate(Response response) */ public ServiceResponse dateTimeValid() throws ErrorException, IOException { final DateTime dateTimeQuery = DateTime.parse("2012-01-01T01:01:01Z"); - String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); - Call call = service.dateTimeValid(dateTimeQueryConverted); + Call call = service.dateTimeValid(dateTimeQuery); return dateTimeValidDelegate(call.execute()); } @@ -1909,8 +1894,7 @@ public ServiceCall dateTimeValidAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimeQuery = DateTime.parse("2012-01-01T01:01:01Z"); - String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); - Call call = service.dateTimeValid(dateTimeQueryConverted); + Call call = service.dateTimeValid(dateTimeQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1941,8 +1925,7 @@ private ServiceResponse dateTimeValidDelegate(Response respo */ public ServiceResponse dateTimeNull() throws ErrorException, IOException { final DateTime dateTimeQuery = null; - String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); - Call call = service.dateTimeNull(dateTimeQueryConverted); + Call call = service.dateTimeNull(dateTimeQuery); return dateTimeNullDelegate(call.execute()); } @@ -1958,8 +1941,7 @@ public ServiceCall dateTimeNullAsync(final ServiceCallback serviceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimeQuery = null; - String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); - Call call = service.dateTimeNull(dateTimeQueryConverted); + Call call = service.dateTimeNull(dateTimeQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1983,8 +1965,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateTimeNull(DateTime dateTimeQuery) throws ErrorException, IOException { - String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); - Call call = service.dateTimeNull(dateTimeQueryConverted); + Call call = service.dateTimeNull(dateTimeQuery); return dateTimeNullDelegate(call.execute()); } @@ -2000,8 +1981,7 @@ public ServiceCall dateTimeNullAsync(DateTime dateTimeQuery, final ServiceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - String dateTimeQueryConverted = this.client.getMapperAdapter().serializeRaw(dateTimeQuery); - Call call = service.dateTimeNull(dateTimeQueryConverted); + Call call = service.dateTimeNull(dateTimeQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java index 52d1b406a9d22..3eee3e193106a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java @@ -59,4 +59,9 @@ public static UriColor fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java index a988f2ca28906..ced5c30d1fca2 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java @@ -53,4 +53,9 @@ public static EnumConst fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java index 3f994b736f0cb..a8d1b48161701 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java @@ -9,6 +9,7 @@ import fixtures.url.models.ErrorException; import fixtures.url.models.UriColor; +import okhttp3.logging.HttpLoggingInterceptor; public class QueriesTests { private static AutoRestUrlTestService client; @@ -16,6 +17,7 @@ public class QueriesTests { @BeforeClass public static void setup() { client = new AutoRestUrlTestServiceImpl("http://localhost.:3000"); + client.setLogLevel(HttpLoggingInterceptor.Level.HEADERS); } @Test diff --git a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs index f79d039c95c7e..50c886c5c22d2 100644 --- a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs @@ -167,3 +167,10 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ModelTemplateModel.#PropertyModels")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PropertyModel.#.ctor(Microsoft.Rest.Generator.ClientModel.Property,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PropertyModel.#.ctor(Microsoft.Rest.Generator.ClientModel.Property,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#convertClientTypeToWireType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#convertClientTypeToWireType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_interfaceImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_interfaceImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_implImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_implImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#convertToClientType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.Int32)")] diff --git a/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml index 04e2020a27d58..d974f639c110e 100644 --- a/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml @@ -63,4 +63,10 @@ public enum @(Model.Name) { } return null; } + @EmptyLine + + @@Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs index cd19c894d7c49..6c8ad4d8bd0b2 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs @@ -48,8 +48,7 @@ public ITypeModel WireType { return new PrimaryTypeModel(KnownPrimaryType.Stream) { Name = "RequestBody" }; } - else if ((Location != ParameterLocation.Body) - && NeedsSpecialSerialization(Type)) + else if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData && NeedsSpecialSerialization(ClientType)) { return new PrimaryTypeModel(KnownPrimaryType.String); } @@ -80,14 +79,10 @@ public bool NeedsConversion public string ConvertToWireType(string source, string clientReference) { - if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData) + if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData && NeedsSpecialSerialization(ClientType)) { var primary = ClientType as PrimaryTypeModel; var sequence = ClientType as SequenceTypeModel; - if (primary != null && !NeedsSpecialSerialization(primary)) - { - return source; - } if (primary != null && primary.IsPrimaryType(KnownPrimaryType.ByteArray)) { return string.Format(CultureInfo.InvariantCulture, "{0} {1} = Base64.encodeBase64String({2});", WireType.Name, _wireName, source); @@ -102,14 +97,6 @@ public string ConvertToWireType(string source, string clientReference) source, CollectionFormat.ToString().ToUpper(CultureInfo.InvariantCulture)); } - else - { - return string.Format(CultureInfo.InvariantCulture, "{0} {1} = {2}.getMapperAdapter().serializeRaw({3});", - WireType.Name, - _wireName, - clientReference, - source); - } } return convertClientTypeToWireType(WireType, source, _wireName, clientReference); @@ -131,8 +118,8 @@ private string convertClientTypeToWireType(ITypeModel wireType, string source, s { var sequenceType = wireType as SequenceTypeModel; var elementType = sequenceType.ElementTypeModel; - var itemName = string.Format("item{0}", level == 0 ? "" : level.ToString()); - var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); builder.AppendLine("{0} {1} = new ArrayList<{2}>();", wireType.Name ,target, elementType.Name) .AppendLine("for ({0} {1} : {2}) {{", elementType.ParameterVariant.Name, itemName, source) .Indent().AppendLine(convertClientTypeToWireType(elementType, itemName, itemTarget, clientReference, level + 1)) @@ -145,8 +132,8 @@ private string convertClientTypeToWireType(ITypeModel wireType, string source, s { var dictionaryType = wireType as DictionaryTypeModel; var valueType = dictionaryType.ValueTypeModel; - var itemName = string.Format("entry{0}", level == 0 ? "" : level.ToString()); - var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); builder.AppendLine("{0} {1} = new HashMap();", wireType.Name, target, valueType.Name) .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.ParameterVariant.Name, itemName, source) .Indent().AppendLine(convertClientTypeToWireType(valueType, itemName + ".getValue()", itemTarget, clientReference, level + 1)) @@ -174,7 +161,7 @@ public IEnumerable RetrofitImports // type imports if (this.Location == ParameterLocation.Body || !NeedsSpecialSerialization(Type)) { - imports.AddRange(ClientType.Imports); + imports.AddRange(WireType.Imports); } // parameter location imports.Add(LocationImport(this.Location)); @@ -229,11 +216,8 @@ private bool NeedsSpecialSerialization(IType type) { var known = type as PrimaryType; return known != null && - type.IsPrimaryType(KnownPrimaryType.Date) || - type.IsPrimaryType(KnownPrimaryType.DateTime) || - type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123) || type.IsPrimaryType(KnownPrimaryType.ByteArray) || - type is EnumType || type is CompositeType || type is SequenceType || type is DictionaryType; + type is SequenceType; } } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs index 18ca704617c6d..b7a6164ea5bbe 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -254,8 +254,8 @@ private string convertToClientType(ITypeModel type, string source, string target if (sequenceType != null) { var elementType = sequenceType.ElementTypeModel; - var itemName = string.Format("item{0}", level == 0 ? "" : level.ToString()); - var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); builder.AppendLine("{0} = new ArrayList<{1}>();", target, elementType.ResponseVariant.Name) .AppendLine("for ({0} {1} : {2}) {{", elementType.Name, itemName, source) .Indent().AppendLine("{0} {1};", elementType.ResponseVariant.Name, itemTarget) @@ -268,8 +268,8 @@ private string convertToClientType(ITypeModel type, string source, string target else if (dictionaryType != null) { var valueType = dictionaryType.ValueTypeModel; - var itemName = string.Format("entry{0}", level == 0 ? "" : level.ToString()); - var itemTarget = string.Format("value{1}", target, level == 0 ? "" : level.ToString()); + var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); builder.AppendLine("{0} = new HashMap();", target, valueType.ResponseVariant.Name) .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.Name, itemName, source) .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget) From d0a6e6f5e176f354423c74bc6194a9b03212c90d Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 28 Mar 2016 11:10:06 -0700 Subject: [PATCH 47/99] Add default value support for optional parameters --- .../Java/Azure.Java/Templates/AzureMethodTemplate.cshtml | 4 ++-- AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index 5595b8214911f..dcdd167c9af36 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -60,7 +60,7 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth { if (!parameter.IsRequired) { -@: final @(parameter.Type.Name) @(parameter.Name) = null; +@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.ClientType.DefaultValue); } if (parameter.IsConstant) { @@ -110,7 +110,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW { if (!parameter.IsRequired) { -@: final @(parameter.Type.Name) @(parameter.Name) = null; +@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.ClientType.DefaultValue); } if (parameter.IsConstant) { diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index 8c20b2b88d51c..561ca9fc428dd 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -49,7 +49,7 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth { if (!parameter.IsRequired) { -@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = null; +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.ClientType.DefaultValue); } if (parameter.IsConstant) { @@ -110,7 +110,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW { if (!parameter.IsRequired) { -@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = null; +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.ClientType.DefaultValue); } if (parameter.IsConstant) { From bef80e69a11d95d5c7fc75954106392034f6b90c Mon Sep 17 00:00:00 2001 From: Laurent Mazuel Date: Fri, 25 Mar 2016 12:05:41 -0700 Subject: [PATCH 48/99] msrest-msrestazure 0.2.0 --- ClientRuntimes/Python/msrest/doc/conf.py | 4 ++-- ClientRuntimes/Python/msrest/msrest/version.py | 2 +- ClientRuntimes/Python/msrest/readme.rst | 13 +++++++++++++ ClientRuntimes/Python/msrest/setup.py | 2 +- ClientRuntimes/Python/msrestazure/doc/conf.py | 4 ++-- .../Python/msrestazure/msrestazure/version.py | 2 +- ClientRuntimes/Python/msrestazure/readme.rst | 11 +++++++++++ .../Python/msrestazure/requirements27.txt | 2 +- .../Python/msrestazure/requirements35.txt | 2 +- ClientRuntimes/Python/msrestazure/setup.py | 4 ++-- 10 files changed, 35 insertions(+), 11 deletions(-) diff --git a/ClientRuntimes/Python/msrest/doc/conf.py b/ClientRuntimes/Python/msrest/doc/conf.py index bad75ae0d6139..1dfe56981ffc9 100644 --- a/ClientRuntimes/Python/msrest/doc/conf.py +++ b/ClientRuntimes/Python/msrest/doc/conf.py @@ -57,9 +57,9 @@ # built documents. # # The short X.Y version. -version = '0.1.3' +version = '0.2.0' # The full version, including alpha/beta/rc tags. -release = '0.1.3' +release = '0.2.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/ClientRuntimes/Python/msrest/msrest/version.py b/ClientRuntimes/Python/msrest/msrest/version.py index cb55186422823..11739ebc3606c 100644 --- a/ClientRuntimes/Python/msrest/msrest/version.py +++ b/ClientRuntimes/Python/msrest/msrest/version.py @@ -25,4 +25,4 @@ # -------------------------------------------------------------------------- -msrest_version = "0.1.3" +msrest_version = "0.2.0" diff --git a/ClientRuntimes/Python/msrest/readme.rst b/ClientRuntimes/Python/msrest/readme.rst index 0317e6b8a90b2..77e50e0da4bb2 100644 --- a/ClientRuntimes/Python/msrest/readme.rst +++ b/ClientRuntimes/Python/msrest/readme.rst @@ -15,6 +15,19 @@ To install: Release History --------------- +2016-03-25 Version 0.2.0 +++++++++++++++++++++++++ + +**Bugfixes** + +- Manage integer enum values (https://github.com/Azure/autorest/pull/879) +- Add missing application/json Accept HTTP header (https://github.com/Azure/azure-sdk-for-python/issues/553) + +**Beheviour changes** + +- Needs Autorest > 0.16.0 Nightly 20160324 + + 2016-03-21 Version 0.1.3 ++++++++++++++++++++++++ diff --git a/ClientRuntimes/Python/msrest/setup.py b/ClientRuntimes/Python/msrest/setup.py index 9db7f313040c3..b3dca9089b534 100644 --- a/ClientRuntimes/Python/msrest/setup.py +++ b/ClientRuntimes/Python/msrest/setup.py @@ -28,7 +28,7 @@ setup( name='msrest', - version='0.1.3', + version='0.2.0', author='Microsoft Corporation', packages=['msrest'], url=("https://github.com/xingwu1/autorest/tree/python/" diff --git a/ClientRuntimes/Python/msrestazure/doc/conf.py b/ClientRuntimes/Python/msrestazure/doc/conf.py index 4d22ad0992a90..0c188afe88a4c 100644 --- a/ClientRuntimes/Python/msrestazure/doc/conf.py +++ b/ClientRuntimes/Python/msrestazure/doc/conf.py @@ -58,9 +58,9 @@ # built documents. # # The short X.Y version. -version = '0.1.2' +version = '0.2.0' # The full version, including alpha/beta/rc tags. -release = '0.1.2' +release = '0.2.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/version.py b/ClientRuntimes/Python/msrestazure/msrestazure/version.py index a0f21a3e502d4..afe6b750dc35e 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/version.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/version.py @@ -24,4 +24,4 @@ # # -------------------------------------------------------------------------- -msrestazure_version = "0.1.2" +msrestazure_version = "0.2.0" diff --git a/ClientRuntimes/Python/msrestazure/readme.rst b/ClientRuntimes/Python/msrestazure/readme.rst index 2241e5ce14619..6410f9f335943 100644 --- a/ClientRuntimes/Python/msrestazure/readme.rst +++ b/ClientRuntimes/Python/msrestazure/readme.rst @@ -15,6 +15,17 @@ To install: Release History --------------- +2016-03-25 Version 0.2.0 +++++++++++++++++++++++++ + +Update msrest dependency to 0.2.0 + +**Behaviour change** + +- async methods called with raw=True don't return anymore AzureOperationPoller but ClientRawResponse +- Needs Autorest > 0.16.0 Nightly 20160324 + + 2016-03-21 Version 0.1.2 ++++++++++++++++++++++++ diff --git a/ClientRuntimes/Python/msrestazure/requirements27.txt b/ClientRuntimes/Python/msrestazure/requirements27.txt index 26aa9d0fa73a6..4c6368baf850a 100644 --- a/ClientRuntimes/Python/msrestazure/requirements27.txt +++ b/ClientRuntimes/Python/msrestazure/requirements27.txt @@ -12,4 +12,4 @@ requests==2.7.0 requests-oauthlib==0.5.0 six==1.10.0 chardet==2.3.0 -msrest==0.1.1 +msrest==0.2.0 diff --git a/ClientRuntimes/Python/msrestazure/requirements35.txt b/ClientRuntimes/Python/msrestazure/requirements35.txt index e400edf782878..76fe44ba95f1c 100644 --- a/ClientRuntimes/Python/msrestazure/requirements35.txt +++ b/ClientRuntimes/Python/msrestazure/requirements35.txt @@ -10,4 +10,4 @@ requests==2.7.0 requests-oauthlib==0.5.0 six==1.10.0 chardet==2.3.0 -msrest==0.1.1 +msrest==0.2.0 diff --git a/ClientRuntimes/Python/msrestazure/setup.py b/ClientRuntimes/Python/msrestazure/setup.py index d723f963d1d0b..170ea10a30aa9 100644 --- a/ClientRuntimes/Python/msrestazure/setup.py +++ b/ClientRuntimes/Python/msrestazure/setup.py @@ -28,7 +28,7 @@ setup( name='msrestazure', - version='0.1.2', + version='0.2.0', author='Microsoft Corporation', packages=['msrestazure'], url=('https://github.com/xingwu1/autorest/tree/python/' @@ -49,5 +49,5 @@ 'License :: OSI Approved :: MIT License', 'Topic :: Software Development'], install_requires=[ - "msrest>=0.1.3"], + "msrest>=0.2.0"], ) From b5163a93be1c04593c154fabc7e832b59d3de5a0 Mon Sep 17 00:00:00 2001 From: tbombach Date: Mon, 28 Mar 2016 12:18:44 -0700 Subject: [PATCH 49/99] Adding test case for accepting a base64url encoded string in the path --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 1 + .../Expected/AcceptanceTests/Url/IPaths.cs | 13 +++ .../Expected/AcceptanceTests/Url/Paths.cs | 110 ++++++++++++++++++ .../AcceptanceTests/Url/PathsExtensions.cs | 31 +++++ AutoRest/TestServer/server/app.js | 1 + AutoRest/TestServer/server/routes/paths.js | 8 +- AutoRest/TestServer/swagger/url.json | 30 +++++ 7 files changed, 191 insertions(+), 3 deletions(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 3b7b3cfba0867..5646edbaa40f2 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -1347,6 +1347,7 @@ public void UrlPathTests() Assert.Throws(() => client.Paths.StringNull(null)); client.Paths.StringUrlEncoded(); client.Paths.EnumValid(UriColor.Greencolor); + client.Paths.Base64Url(Encoding.UTF8.GetBytes("lorem")); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs index 518a34aeade57..093efcf2646be 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs @@ -277,5 +277,18 @@ public partial interface IPaths /// The cancellation token. /// Task DateTimeNullWithHttpMessagesAsync(DateTime dateTimePath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// base64url encoded value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task Base64UrlWithHttpMessagesAsync(byte[] base64UrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs index b68b6a5103255..6cf4f380818bd 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs @@ -2470,5 +2470,115 @@ public Paths(AutoRestUrlTestService client) return _result; } + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// base64url encoded value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task Base64UrlWithHttpMessagesAsync(byte[] base64UrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (base64UrlPath == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "base64UrlPath"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("base64UrlPath", base64UrlPath); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "Base64Url", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "paths/string/bG9yZW0/{base64UrlPath}").ToString(); + _url = _url.Replace("{base64UrlPath}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(base64UrlPath, new Base64UrlJsonConverter()).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs index 253b845261892..6bb57c30dc6ef 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs @@ -646,5 +646,36 @@ public static void DateTimeNull(this IPaths operations, DateTime dateTimePath) await operations.DateTimeNullWithHttpMessagesAsync(dateTimePath, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// The operations group for this extension method. + /// + /// + /// base64url encoded value + /// + public static void Base64Url(this IPaths operations, byte[] base64UrlPath) + { + Task.Factory.StartNew(s => ((IPaths)s).Base64UrlAsync(base64UrlPath), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// The operations group for this extension method. + /// + /// + /// base64url encoded value + /// + /// + /// The cancellation token. + /// + public static async Task Base64UrlAsync(this IPaths operations, byte[] base64UrlPath, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.Base64UrlWithHttpMessagesAsync(base64UrlPath, null, cancellationToken).ConfigureAwait(false); + } + } } diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index c82f6f4d90dc9..f1220bc06ff16 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -202,6 +202,7 @@ var coverage = { "getStringNullBase64UrlEncoding": 1, "getArrayBase64Url": 1, "getDictionaryBase64Url": 1, + "UrlPathsStringBase64Url": 1, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, diff --git a/AutoRest/TestServer/server/routes/paths.js b/AutoRest/TestServer/server/routes/paths.js index cb4f8569b0bb2..15eaa93885a43 100644 --- a/AutoRest/TestServer/server/routes/paths.js +++ b/AutoRest/TestServer/server/routes/paths.js @@ -21,7 +21,8 @@ var scenarioMap = { "null": "Null", "2012-01-01": "Valid", "2012-01-01T01:01:01Z": "Valid", - "green color" : "Valid" + "green color" : "Valid", + "bG9yZW0" : "Base64Url" }; var typeMap = { @@ -82,14 +83,15 @@ var paths = function (coverage) { type === 'datetime' || scenario === 'multibyte' || (type === 'string' && - scenario.indexOf('begin') === 0)) { + scenario.indexOf('begin') === 0) || + scenario === 'bG9yZW0') { scenario = '"' + scenario + '"'; wireParameter = '"' + wireParameter + '"'; } scenario = JSON.parse(scenario); wireParameter = JSON.parse(wireParameter); - + if (test === null) { console.log("test was null\n"); utils.send400(res, next, 'Unable to parse scenario \"\/paths\/' + type + '\/' + scenario + '\"'); diff --git a/AutoRest/TestServer/swagger/url.json b/AutoRest/TestServer/swagger/url.json index 6a8ab8f526e17..00da5fdfc2a94 100644 --- a/AutoRest/TestServer/swagger/url.json +++ b/AutoRest/TestServer/swagger/url.json @@ -710,6 +710,36 @@ } } }, + "/paths/string/bG9yZW0/{base64UrlPath}": { + "get": { + "operationId": "paths_base64Url", + "description": "Get 'lorem' encoded value as 'bG9yZW0' (base64url)", + "tags": [ + "Path Operations" + ], + "parameters": [ + { + "name": "base64UrlPath", + "in": "path", + "description": "base64url encoded value", + "type": "string", + "format": "base64url", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully Received 'lorem' encoded value as 'bG9yZW0' (base64url)" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/queries/bool/true": { "get": { "operationId": "queries_getBooleanTrue", From bf5456aff9902064545e8cf4fa839be9f43cfb26 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 28 Mar 2016 14:20:30 -0700 Subject: [PATCH 50/99] #889: Fix credentials setup in service client --- .../Generators/Java/Java/Templates/ServiceClientTemplate.cshtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml index d96fdae31b76c..cb2b13b88d8c3 100644 --- a/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml @@ -131,7 +131,7 @@ else { @: if (this.credentials != null) @: { -@: this.credentials.applyCredentialsFilter(this.client); +@: this.credentials.applyCredentialsFilter(clientBuilder); @: } } super.initialize(); From d468bfcd3075b8bfc03376dc04cf97397accac41 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 28 Mar 2016 14:30:38 -0700 Subject: [PATCH 51/99] Fix parameter conversion --- .../Java/Azure.Java/Templates/AzureMethodTemplate.cshtml | 4 ++-- .../Java/Java/TemplateModels/MethodTemplateModel.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index dcdd167c9af36..9de6087ceb14b 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -68,7 +68,7 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth } } @Model.BuildInputMappings() - + @Model.ParameterConversion Response result = service.@(Model.Name)(@Model.MethodParameterApiInvocation).execute(); return client.getAzureClient().@(Model.PollingMethod)(result, @Model.PollingResourceTypeArgs); } @@ -230,7 +230,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb } } @Model.BuildInputMappings() - + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback<@Model.CallType>() { diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 5367aac11395a..ff3c8740dd115 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -198,7 +198,7 @@ public string ParameterConversion get { IndentedStringBuilder builder = new IndentedStringBuilder(); - foreach (var p in ParameterModels) { + foreach (var p in RetrofitParameters) { if (p.NeedsConversion) { builder.Append(p.ConvertToWireType(p.Name, ClientReference)); From 5732fa59ed766b54fdd5ebfee0c5c98bb7ae8b30 Mon Sep 17 00:00:00 2001 From: Denis Stankovski Date: Mon, 28 Mar 2016 15:48:29 -0700 Subject: [PATCH 52/99] Update swagger-extensions.md --- Documentation/swagger-extensions.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentation/swagger-extensions.md b/Documentation/swagger-extensions.md index cef0b89a0c3d4..c31503552dc15 100644 --- a/Documentation/swagger-extensions.md +++ b/Documentation/swagger-extensions.md @@ -385,6 +385,7 @@ When used, replaces the standard Swagger "host" attribute with a host that conta **Parent element**: [Info Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject) **Schema**: + Field Name | Type | Description ---|:---:|--- hostTemplate | `string` | **Required**. Specifies the parameterized template for the host. @@ -595,4 +596,4 @@ When set, specifies the header parameter to be used instead of `x-ms-client-requ } } } -``` \ No newline at end of file +``` From 24a74a08bb75837406d4f91377b20ecbd1eafa59 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Mon, 28 Mar 2016 17:29:52 -0700 Subject: [PATCH 53/99] Fix type normalization [stackoverflow in network] --- .../Java/Azure.Java/AzureJavaCodeNamer.cs | 4 +- .../AzureMethodTemplateModel.cs | 2 +- .../models/Datetimerfc1123Wrapper.java | 6 +++ .../fixtures/bodycomplex/models/Fish.java | 2 +- .../fixtures/bodycomplex/models/Shark.java | 2 +- .../modelflattening/models/Resource.java | 2 +- .../fixtures/url/QueriesOperationsImpl.java | 8 ++-- .../Generators/Java/Java/JavaCodeNamer.cs | 39 ++++++++++++++----- .../Java/Java/Templates/ModelTemplate.cshtml | 2 +- 9 files changed, 47 insertions(+), 20 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs index bfeaa978fb465..9f73d3f513ea3 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs @@ -110,9 +110,9 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet(convertedTypes.Keys.Cast().Select(t => t.Name))); } - protected override IType NormalizeCompositeType(CompositeType compositeType) + protected override CompositeTypeModel NewCompositeTypeModel(CompositeType compositeType) { - return new AzureCompositeTypeModel((CompositeTypeModel) base.NormalizeCompositeType(compositeType)); + return new AzureCompositeTypeModel(compositeType, _package); } #endregion diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index ce89f3e81498d..c3ae9afc5126e 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -579,7 +579,7 @@ public override List ImplImports } if (this.IsPagingNonPollingOperation) { - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportSafe()); + imports.AddRange(new CompositeTypeModel(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } return imports; } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java index 73e3b74ff6268..6136a56f86b1f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java @@ -33,6 +33,9 @@ public class Datetimerfc1123Wrapper { * @return the field value */ public DateTime getField() { + if (this.field == null) { + return null; + } return this.field.getDateTime(); } @@ -51,6 +54,9 @@ public void setField(DateTime field) { * @return the now value */ public DateTime getNow() { + if (this.now == null) { + return null; + } return this.now.getDateTime(); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java index c820edca131a7..cdb598998e1c0 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java @@ -10,8 +10,8 @@ package fixtures.bodycomplex.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonSubTypes; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java index 9b0aa2344cf7f..2c1f2eaa58a37 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java @@ -10,8 +10,8 @@ package fixtures.bodycomplex.models; -import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonSubTypes; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java index 2fec07db12f71..b838cc58de139 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java @@ -10,8 +10,8 @@ package fixtures.modelflattening.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The Resource model. diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java index d55e48618cb8b..47bd29d144dd3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java @@ -1512,7 +1512,7 @@ private ServiceResponse enumNullDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteMultiByte() throws ErrorException, IOException { - final byte[] byteQuery = null; + final byte[] byteQuery = new byte[0]; String byteQueryConverted = Base64.encodeBase64String(byteQuery); Call call = service.byteMultiByte(byteQueryConverted); return byteMultiByteDelegate(call.execute()); @@ -1529,7 +1529,7 @@ public ServiceCall byteMultiByteAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final byte[] byteQuery = null; + final byte[] byteQuery = new byte[0]; String byteQueryConverted = Base64.encodeBase64String(byteQuery); Call call = service.byteMultiByte(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); @@ -1652,7 +1652,7 @@ private ServiceResponse byteEmptyDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteNull() throws ErrorException, IOException { - final byte[] byteQuery = null; + final byte[] byteQuery = new byte[0]; String byteQueryConverted = Base64.encodeBase64String(byteQuery); Call call = service.byteNull(byteQueryConverted); return byteNullDelegate(call.execute()); @@ -1669,7 +1669,7 @@ public ServiceCall byteNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final byte[] byteQuery = null; + final byte[] byteQuery = new byte[0]; String byteQueryConverted = Base64.encodeBase64String(byteQuery); Call call = service.byteNull(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index 3c02c6471bda6..c8d58b1031848 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -14,6 +14,8 @@ namespace Microsoft.Rest.Generator.Java { public class JavaCodeNamer : CodeNamer { + private Dictionary _visited = new Dictionary(); + public const string ExternalExtension = "x-ms-external"; public static HashSet PrimaryTypes { get; private set; } @@ -268,25 +270,39 @@ public override IType NormalizeTypeReference(IType type) type = new PrimaryTypeModel(KnownPrimaryType.String); } + if (_visited.ContainsKey(type)) + { + return _visited[type]; + } + if (type is PrimaryType) { - return NormalizePrimaryType(type as PrimaryType); + _visited[type] = new PrimaryTypeModel(type as PrimaryType); + return _visited[type]; } if (type is SequenceType) { - return NormalizeSequenceType(type as SequenceType); + SequenceTypeModel model = new SequenceTypeModel(type as SequenceType); + _visited[type] = model; + return NormalizeSequenceType(model); } if (type is DictionaryType) { - return NormalizeDictionaryType(type as DictionaryType); + DictionaryTypeModel model = new DictionaryTypeModel(type as DictionaryType); + _visited[type] = model; + return NormalizeDictionaryType(model); } if (type is CompositeType) { - return NormalizeCompositeType(type as CompositeType); + CompositeTypeModel model = NewCompositeTypeModel(type as CompositeType); + _visited[type] = model; + return NormalizeCompositeType(model); } if (type is EnumType) { - return NormalizeEnumType(type as EnumType); + EnumTypeModel model = new EnumTypeModel(type as EnumType, _package); + _visited[type] = model; + return NormalizeEnumType(model); } @@ -309,7 +325,12 @@ private IType NormalizeEnumType(EnumType enumType) { enumType.Values[i].Name = GetEnumMemberName(enumType.Values[i].Name); } - return new EnumTypeModel(enumType, _package); + return enumType; + } + + protected virtual CompositeTypeModel NewCompositeTypeModel(CompositeType compositeType) + { + return new CompositeTypeModel(compositeType as CompositeType, _package); } protected virtual IType NormalizeCompositeType(CompositeType compositeType) @@ -326,7 +347,7 @@ protected virtual IType NormalizeCompositeType(CompositeType compositeType) } } - return new CompositeTypeModel(compositeType, _package); + return compositeType; } public static PrimaryTypeModel NormalizePrimaryType(PrimaryType primaryType) @@ -343,14 +364,14 @@ private IType NormalizeSequenceType(SequenceType sequenceType) { sequenceType.ElementType = WrapPrimitiveType(NormalizeTypeReference(sequenceType.ElementType)); sequenceType.NameFormat = "List<{0}>"; - return new SequenceTypeModel(sequenceType); + return sequenceType; } private IType NormalizeDictionaryType(DictionaryType dictionaryType) { dictionaryType.ValueType = WrapPrimitiveType(NormalizeTypeReference(dictionaryType.ValueType)); dictionaryType.NameFormat = "Map"; - return new DictionaryTypeModel(dictionaryType); + return dictionaryType; } #endregion diff --git a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml index 5dd8b297b4726..8ae9ece254ac2 100644 --- a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml @@ -43,7 +43,7 @@ var type = types[i]; { @:@@JsonFlatten } -public class @(Model.Name)@(Model.BaseModelType != null ? " extends " + Model.BaseModelType.Name : "") { +public class @(Model.Name)@(Model.BaseModelType != null ? " extends " + Model.BaseModelType.Name.ToPascalCase() : "") { @foreach (var property in Model.Properties) { @: /** From 1aab052fff15cfc03b5ff45e97870749cbd83081 Mon Sep 17 00:00:00 2001 From: tbombach Date: Mon, 28 Mar 2016 17:37:11 -0700 Subject: [PATCH 54/99] Updating the client runtime package version --- .../Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs | 2 +- AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs | 2 +- .../Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs | 2 +- AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs | 2 +- AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj | 2 +- AutoRest/NugetPackageTest/packages.config | 2 +- .../Properties/AssemblyInfo.cs | 2 +- .../CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json | 2 +- .../Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs | 2 +- ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs b/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs index 6ec3ab05bd8c4..5c7f0b5bb3809 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs @@ -18,7 +18,7 @@ public class AzureCSharpCodeGenerator : CSharpCodeGenerator { private readonly AzureCSharpCodeNamer _namer; - private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.Azure.3.1.0"; + private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.Azure.3.2.0"; // page extensions class dictionary. private IDictionary, string> pageClasses; diff --git a/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs b/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs index b0a43b1bc5431..b43de08e365b0 100644 --- a/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs +++ b/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs @@ -14,7 +14,7 @@ namespace Microsoft.Rest.Generator.CSharp public class CSharpCodeGenerator : CodeGenerator { private readonly CSharpCodeNamer _namer; - private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.2.1.0"; + private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.2.2.0"; public CSharpCodeGenerator(Settings settings) : base(settings) { diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs b/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs index cddd7a2adba46..839991bea7e2f 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs @@ -18,7 +18,7 @@ namespace Microsoft.Rest.Generator.Azure.NodeJS { public class AzureNodeJSCodeGenerator : NodeJSCodeGenerator { - private const string ClientRuntimePackage = "ms-rest-azure version 1.10.0"; + private const string ClientRuntimePackage = "ms-rest-azure version 1.11.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 bdc9153f1ca06..c8b4f2669e1c2 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs @@ -16,7 +16,7 @@ namespace Microsoft.Rest.Generator.NodeJS { public class NodeJSCodeGenerator : CodeGenerator { - private const string ClientRuntimePackage = "ms-rest version 1.10.0"; + private const string ClientRuntimePackage = "ms-rest version 1.11.0"; public NodeJsCodeNamer Namer { get; private set; } diff --git a/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj b/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj index ac46023f2570a..b2e0451a3fb47 100644 --- a/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj +++ b/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj @@ -39,7 +39,7 @@ - packages\Microsoft.Rest.ClientRuntime.2.1.0\lib\net45\Microsoft.Rest.ClientRuntime.dll + packages\Microsoft.Rest.ClientRuntime.2.2.0\lib\net45\Microsoft.Rest.ClientRuntime.dll True diff --git a/AutoRest/NugetPackageTest/packages.config b/AutoRest/NugetPackageTest/packages.config index 38ea62de43340..356cf06d88364 100644 --- a/AutoRest/NugetPackageTest/packages.config +++ b/AutoRest/NugetPackageTest/packages.config @@ -1,6 +1,6 @@ - + diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs index 727ccfd166cca..501abc07659ad 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs @@ -9,7 +9,7 @@ [assembly: AssemblyTitle("Microsoft Rest Azure Client Runtime")] [assembly: AssemblyDescription("Client infrastructure for Azure client libraries.")] [assembly: AssemblyVersion("3.0.0.0")] -[assembly: AssemblyFileVersion("3.1.0.0")] +[assembly: AssemblyFileVersion("3.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json index 6f416ef8ea5b4..6a24bd8b0ca07 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json @@ -1,5 +1,5 @@ { - "version": "3.1.0", + "version": "3.2.0", "copyright": "Copyright (c) Microsoft Corporation", "iconUrl": "http://go.microsoft.com/fwlink/?LinkID=288890", "title": "Client Runtime for Microsoft Azure Libraries", diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs index 896b8469346f6..14749d7e07285 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs @@ -9,7 +9,7 @@ [assembly: AssemblyTitle("Microsoft Rest Client Runtime")] [assembly: AssemblyDescription("Client infrastructure for client libraries generated by AutoRest.")] [assembly: AssemblyVersion("2.0.0.0")] -[assembly: AssemblyFileVersion("2.1.0.0")] +[assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json index 59c06562130e3..82724c95bf56c 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json @@ -1,5 +1,5 @@ { - "version": "2.1.0", + "version": "2.2.0", "copyright": "Copyright (c) Microsoft Corporation", "iconUrl": "https://cdn.rawgit.com/Azure/AutoRest/7c1576dfb56974176223545cfac5762d168ded5f/Documentation/images/autorest-small-flat.png", "title": "Client Runtime Library for Microsoft AutoRest Generated Clients", From b37fc5ecc1f2c3851fc8b86028043b23514271e4 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Tue, 29 Mar 2016 12:24:44 -0700 Subject: [PATCH 55/99] Add option for license header w/o codgen info --- AutoRest/AutoRest.Core/Settings.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AutoRest/AutoRest.Core/Settings.cs b/AutoRest/AutoRest.Core/Settings.cs index a014456a63bca..df99585e02d31 100644 --- a/AutoRest/AutoRest.Core/Settings.cs +++ b/AutoRest/AutoRest.Core/Settings.cs @@ -157,6 +157,10 @@ public string Header { _header = MicrosoftApacheLicenseHeader + Environment.NewLine + DefaultCodeGenerationHeaderWithoutVersion; } + else if (value == "MICROSOFT_MIT_NO_CODEGEN") + { + _header = MicrosoftMitLicenseHeader; + } else if (value == "NONE") { _header = String.Empty; From c174932c9588c79a1eb0c9d7f20eb989a9f66a2b Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Tue, 29 Mar 2016 12:25:03 -0700 Subject: [PATCH 56/99] update paging extension documentation. --- Documentation/swagger-extensions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/swagger-extensions.md b/Documentation/swagger-extensions.md index c31503552dc15..cb3bed17ab585 100644 --- a/Documentation/swagger-extensions.md +++ b/Documentation/swagger-extensions.md @@ -464,7 +464,7 @@ The REST API guidelines define a common pattern for paging through lists of data Field Name | Type | Description ---|:---:|--- -nextLinkName| `string` | Specifies the name of the property that provides the nextLink. If the model does not have the nextLink property then specify null. +nextLinkName| `string` | Specifies the name of the property that provides the nextLink. **If the model does not have the nextLink property then specify null. This will be useful for the services that return an object that has an array referenced by the itemName. The object is flattened in a way that the array is directly returned. Since the nextLinkName is explicitly specified to null, the generated code will not implement paging. However, you get the benefit of flattening. Thus providing a better client side API to the end user.** itemName | `string` | Specifies the name of the property that provides the collection of pageable items. Default value is 'value'.{Postfix}`. operationName | `string` | Specifies the name of the Next operation. Default value is 'XXXNext' where XXX is the name of the operation From 3b3c78837912c83f7d503f7a8af84ae8772a2253 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Tue, 29 Mar 2016 14:37:01 -0700 Subject: [PATCH 57/99] Fix head response with headers --- .../main/java/com/microsoft/rest/ServiceResponseBuilder.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java b/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java index e94a166cd1765..1fae7e4e9fe51 100644 --- a/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java +++ b/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java @@ -239,7 +239,9 @@ public ServiceResponseWithHeaders buildEmptyWithHeaders(Re THeader headers = mapperAdapter.deserialize( mapperAdapter.serialize(response.headers()), headerType); - return new ServiceResponseWithHeaders<>(headers, bodyResponse.getHeadResponse()); + ServiceResponseWithHeaders serviceResponse = new ServiceResponseWithHeaders<>(headers, bodyResponse.getHeadResponse()); + serviceResponse.setBody(bodyResponse.getBody()); + return serviceResponse; } /** From ab982acc9e4571372536393b9f661304672c8b5e Mon Sep 17 00:00:00 2001 From: begoldsm Date: Tue, 29 Mar 2016 15:45:49 -0700 Subject: [PATCH 58/99] Escape data strings for odata queries. --- .../Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs | 6 +++--- .../CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs index 252c7739db668..99fed407ca114 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs @@ -146,17 +146,17 @@ public override string ToString() if (!string.IsNullOrEmpty(Filter)) { queryStringList.Add(string.Format(CultureInfo.InvariantCulture, - "$filter={0}", Filter)); + "$filter={0}", Uri.EscapeDataString(Filter))); } if (!string.IsNullOrEmpty(OrderBy)) { queryStringList.Add(string.Format(CultureInfo.InvariantCulture, - "$orderby={0}", OrderBy)); + "$orderby={0}", Uri.EscapeDataString(OrderBy))); } if (!string.IsNullOrEmpty(Expand)) { queryStringList.Add(string.Format(CultureInfo.InvariantCulture, - "$expand={0}", Expand)); + "$expand={0}", Uri.EscapeDataString(Expand))); } if (Top != null) { diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json index 6f416ef8ea5b4..6a24bd8b0ca07 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json @@ -1,5 +1,5 @@ { - "version": "3.1.0", + "version": "3.2.0", "copyright": "Copyright (c) Microsoft Corporation", "iconUrl": "http://go.microsoft.com/fwlink/?LinkID=288890", "title": "Client Runtime for Microsoft Azure Libraries", From 6daa5ef26982630d6c8091986d0450b5181f0d6e Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Tue, 29 Mar 2016 17:51:55 -0700 Subject: [PATCH 59/99] Remove useless nulls when input is optional --- .../ParameterGroupingOperationsImpl.java | 84 +------ ...RestResourceFlatteningTestServiceImpl.java | 18 +- .../ApiVersionLocalOperationsImpl.java | 6 +- .../azurespecials/OdataOperationsImpl.java | 10 +- .../SkipUrlEncodingOperationsImpl.java | 6 +- .../fixtures/lro/LRORetrysOperationsImpl.java | 40 ++- .../fixtures/lro/LROSADsOperationsImpl.java | 170 ++++++------- .../lro/LROsCustomHeaderOperationsImpl.java | 40 ++- .../java/fixtures/lro/LROsOperationsImpl.java | 230 +++++++----------- .../fixtures/paging/PagingOperationsImpl.java | 82 ++----- .../AzureMethodTemplateModel.cs | 205 ++++++++-------- .../Templates/AzureMethodTemplate.cshtml | 8 +- .../bodystring/StringOperationsImpl.java | 6 +- .../fixtures/header/HeaderOperationsImpl.java | 20 +- .../http/HttpClientFailureOperationsImpl.java | 78 ++---- .../http/HttpRedirectsOperationsImpl.java | 42 ++-- .../http/HttpRetryOperationsImpl.java | 36 +-- .../http/HttpServerFailureOperationsImpl.java | 12 +- .../http/HttpSuccessOperationsImpl.java | 84 +++---- ...RestResourceFlatteningTestServiceImpl.java | 54 ++-- .../ExplicitOperationsImpl.java | 68 ++---- .../ImplicitOperationsImpl.java | 18 +- .../fixtures/url/PathItemsOperationsImpl.java | 32 +-- .../fixtures/url/QueriesOperationsImpl.java | 124 +++------- .../AutoRestValidationTestImpl.java | 12 +- .../TemplateModels/MethodTemplateModel.cs | 145 ++++++++--- .../Java/Java/Templates/MethodTemplate.cshtml | 28 +-- 27 files changed, 642 insertions(+), 1016 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java index c9daca73b5a07..cc9f7fc54c8f8 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java @@ -151,16 +151,7 @@ private ServiceResponse postRequiredDelegate(Response respon * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse postOptional() throws ErrorException, IOException { - final ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = null; - String customHeader = null; - if (parameterGroupingPostOptionalParameters != null) { - customHeader = parameterGroupingPostOptionalParameters.getCustomHeader(); - } - Integer query = null; - if (parameterGroupingPostOptionalParameters != null) { - query = parameterGroupingPostOptionalParameters.getQuery(); - } - Call call = service.postOptional(this.client.getAcceptLanguage(), customHeader, query); + Call call = service.postOptional(null, null, null); return postOptionalDelegate(call.execute()); } @@ -175,16 +166,7 @@ public ServiceCall postOptionalAsync(final ServiceCallback serviceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = null; - String customHeader = null; - if (parameterGroupingPostOptionalParameters != null) { - customHeader = parameterGroupingPostOptionalParameters.getCustomHeader(); - } - Integer query = null; - if (parameterGroupingPostOptionalParameters != null) { - query = parameterGroupingPostOptionalParameters.getQuery(); - } - Call call = service.postOptional(this.client.getAcceptLanguage(), customHeader, query); + Call call = service.postOptional(null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -272,25 +254,7 @@ private ServiceResponse postOptionalDelegate(Response respon * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse postMultiParamGroups() throws ErrorException, IOException { - final FirstParameterGroup firstParameterGroup = null; - final ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = null; - String headerOne = null; - if (firstParameterGroup != null) { - headerOne = firstParameterGroup.getHeaderOne(); - } - Integer queryOne = null; - if (firstParameterGroup != null) { - queryOne = firstParameterGroup.getQueryOne(); - } - String headerTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getHeaderTwo(); - } - Integer queryTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getQueryTwo(); - } - Call call = service.postMultiParamGroups(this.client.getAcceptLanguage(), headerOne, queryOne, headerTwo, queryTwo); + Call call = service.postMultiParamGroups(null, null, null, null, null); return postMultiParamGroupsDelegate(call.execute()); } @@ -305,25 +269,7 @@ public ServiceCall postMultiParamGroupsAsync(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final FirstParameterGroup firstParameterGroup = null; - final ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = null; - String headerOne = null; - if (firstParameterGroup != null) { - headerOne = firstParameterGroup.getHeaderOne(); - } - Integer queryOne = null; - if (firstParameterGroup != null) { - queryOne = firstParameterGroup.getQueryOne(); - } - String headerTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getHeaderTwo(); - } - Integer queryTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getQueryTwo(); - } - Call call = service.postMultiParamGroups(this.client.getAcceptLanguage(), headerOne, queryOne, headerTwo, queryTwo); + Call call = service.postMultiParamGroups(null, null, null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -431,16 +377,7 @@ private ServiceResponse postMultiParamGroupsDelegate(Response postSharedParameterGroupObject() throws ErrorException, IOException { - final FirstParameterGroup firstParameterGroup = null; - String headerOne = null; - if (firstParameterGroup != null) { - headerOne = firstParameterGroup.getHeaderOne(); - } - Integer queryOne = null; - if (firstParameterGroup != null) { - queryOne = firstParameterGroup.getQueryOne(); - } - Call call = service.postSharedParameterGroupObject(this.client.getAcceptLanguage(), headerOne, queryOne); + Call call = service.postSharedParameterGroupObject(null, null, null); return postSharedParameterGroupObjectDelegate(call.execute()); } @@ -455,16 +392,7 @@ public ServiceCall postSharedParameterGroupObjectAsync(final ServiceCallback call = service.postSharedParameterGroupObject(this.client.getAcceptLanguage(), headerOne, queryOne); + Call call = service.postSharedParameterGroupObject(null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java index ef682bf3f44be..f2d42e20cf69d 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java @@ -254,8 +254,7 @@ interface AutoRestResourceFlatteningTestServiceService { * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putArray() throws ErrorException, IOException { - final List resourceArray = null; - Call call = service.putArray(resourceArray, this.getAcceptLanguage()); + Call call = service.putArray(null, null); return putArrayDelegate(call.execute()); } @@ -270,8 +269,7 @@ public ServiceCall putArrayAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List resourceArray = null; - Call call = service.putArray(resourceArray, this.getAcceptLanguage()); + Call call = service.putArray(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -388,8 +386,7 @@ private ServiceResponse> getArrayDelegate(Response putDictionary() throws ErrorException, IOException { - final Map resourceDictionary = null; - Call call = service.putDictionary(resourceDictionary, this.getAcceptLanguage()); + Call call = service.putDictionary(null, null); return putDictionaryDelegate(call.execute()); } @@ -404,8 +401,7 @@ public ServiceCall putDictionaryAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Map resourceDictionary = null; - Call call = service.putDictionary(resourceDictionary, this.getAcceptLanguage()); + Call call = service.putDictionary(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -522,8 +518,7 @@ private ServiceResponse> getDictionaryDelegate(Res * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putResourceCollection() throws ErrorException, IOException { - final ResourceCollection resourceComplexObject = null; - Call call = service.putResourceCollection(resourceComplexObject, this.getAcceptLanguage()); + Call call = service.putResourceCollection(null, null); return putResourceCollectionDelegate(call.execute()); } @@ -538,8 +533,7 @@ public ServiceCall putResourceCollectionAsync(final ServiceCallback servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final ResourceCollection resourceComplexObject = null; - Call call = service.putResourceCollection(resourceComplexObject, this.getAcceptLanguage()); + Call call = service.putResourceCollection(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java index fd1bad46b33d2..6022d91bac001 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java @@ -126,8 +126,7 @@ private ServiceResponse getMethodLocalValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getMethodLocalNull() throws ErrorException, IOException { - final String apiVersion = null; - Call call = service.getMethodLocalNull(apiVersion, this.client.getAcceptLanguage()); + Call call = service.getMethodLocalNull(null, null); return getMethodLocalNullDelegate(call.execute()); } @@ -142,8 +141,7 @@ public ServiceCall getMethodLocalNullAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String apiVersion = null; - Call call = service.getMethodLocalNull(apiVersion, this.client.getAcceptLanguage()); + Call call = service.getMethodLocalNull(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java index 75777653172cf..2282166c91803 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java @@ -69,10 +69,7 @@ interface OdataService { * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getWithFilter() throws ErrorException, IOException { - final OdataFilter filter = null; - final Integer top = null; - final String orderby = null; - Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(null, null, null, null); return getWithFilterDelegate(call.execute()); } @@ -87,10 +84,7 @@ public ServiceCall getWithFilterAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final OdataFilter filter = null; - final Integer top = null; - final String orderby = null; - Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(null, null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java index 20d997c5006be..7512746ef41c0 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java @@ -304,8 +304,7 @@ private ServiceResponse getMethodQueryValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getMethodQueryNull() throws ErrorException, IOException { - final String q1 = null; - Call call = service.getMethodQueryNull(q1, this.client.getAcceptLanguage()); + Call call = service.getMethodQueryNull(null, null); return getMethodQueryNullDelegate(call.execute()); } @@ -320,8 +319,7 @@ public ServiceCall getMethodQueryNullAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String q1 = null; - Call call = service.getMethodQueryNull(q1, this.client.getAcceptLanguage()); + Call call = service.getMethodQueryNull(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java index 7dc45ef9871d4..d3a75886e7967 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java @@ -133,7 +133,7 @@ interface LRORetrysService { */ public ServiceResponse put201CreatingSucceeded200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put201CreatingSucceeded200(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -149,7 +149,7 @@ public ServiceCall put201CreatingSucceeded200Async(final ServiceCallback call = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.put201CreatingSucceeded200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -214,8 +214,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingSucceeded200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingSucceeded200(null, null); return beginPut201CreatingSucceeded200Delegate(call.execute()); } @@ -230,8 +229,7 @@ public ServiceCall beginPut201CreatingSucceeded200Async(final ServiceCallback call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingSucceeded200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -306,7 +304,7 @@ private ServiceResponse beginPut201CreatingSucceeded200Delegate(Respons */ public ServiceResponseWithHeaders putAsyncRelativeRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRelativeRetrySucceeded(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LRORetrysPutAsyncRelativeRetrySucceededHeaders.class); } @@ -322,7 +320,7 @@ public ServiceCall putAsyncRelativeRetrySucceededAsync(final ServiceCallback call = service.putAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRelativeRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -387,8 +385,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetrySucceeded(null, null); return beginPutAsyncRelativeRetrySucceededDelegate(call.execute()); } @@ -403,8 +400,7 @@ public ServiceCall beginPutAsyncRelativeRetrySucceededAsync(final ServiceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -731,7 +727,7 @@ private ServiceResponseWithHeaders post202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202Retry200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.post202Retry200(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LRORetrysPost202Retry200Headers.class); } @@ -747,7 +743,7 @@ public ServiceCall post202Retry200Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.post202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -812,8 +808,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202Retry200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202Retry200(null, null); return beginPost202Retry200Delegate(call.execute()); } @@ -828,8 +823,7 @@ public ServiceCall beginPost202Retry200Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -903,7 +897,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRelativeRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRelativeRetrySucceeded(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LRORetrysPostAsyncRelativeRetrySucceededHeaders.class); } @@ -919,7 +913,7 @@ public ServiceCall postAsyncRelativeRetrySucceededAsync(final ServiceCallback call = service.postAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRelativeRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -984,8 +978,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetrySucceeded(null, null); return beginPostAsyncRelativeRetrySucceededDelegate(call.execute()); } @@ -1000,8 +993,7 @@ public ServiceCall beginPostAsyncRelativeRetrySucceededAsync(final ServiceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java index a00b4293ab132..952f8bdccd5a4 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 @@ -291,7 +291,7 @@ interface LROSADsService { */ public ServiceResponse putNonRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putNonRetry400(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putNonRetry400(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -307,7 +307,7 @@ public ServiceCall putNonRetry400Async(final ServiceCallback serviceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putNonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.putNonRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -372,8 +372,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutNonRetry400() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutNonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPutNonRetry400(null, null); return beginPutNonRetry400Delegate(call.execute()); } @@ -388,8 +387,7 @@ public ServiceCall beginPutNonRetry400Async(final ServiceCallback servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutNonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPutNonRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -464,7 +462,7 @@ private ServiceResponse beginPutNonRetry400Delegate(Response putNonRetry201Creating400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putNonRetry201Creating400(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putNonRetry201Creating400(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -480,7 +478,7 @@ public ServiceCall putNonRetry201Creating400Async(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putNonRetry201Creating400(product, this.client.getAcceptLanguage()); + Call call = service.putNonRetry201Creating400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -545,8 +543,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutNonRetry201Creating400() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutNonRetry201Creating400(product, this.client.getAcceptLanguage()); + Call call = service.beginPutNonRetry201Creating400(null, null); return beginPutNonRetry201Creating400Delegate(call.execute()); } @@ -561,8 +558,7 @@ public ServiceCall beginPutNonRetry201Creating400Async(final ServiceCallback call = service.beginPutNonRetry201Creating400(product, this.client.getAcceptLanguage()); + Call call = service.beginPutNonRetry201Creating400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -637,7 +633,7 @@ private ServiceResponse beginPutNonRetry201Creating400Delegate(Response */ public ServiceResponseWithHeaders putAsyncRelativeRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetry400(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRelativeRetry400(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetry400Headers.class); } @@ -653,7 +649,7 @@ public ServiceCall putAsyncRelativeRetry400Async(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRelativeRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -718,8 +714,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetry400() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetry400(null, null); return beginPutAsyncRelativeRetry400Delegate(call.execute()); } @@ -734,8 +729,7 @@ public ServiceCall beginPutAsyncRelativeRetry400Async(final ServiceCallback call = service.beginPutAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1061,7 +1055,7 @@ private ServiceResponseWithHeaders postNonRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postNonRetry400(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postNonRetry400(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostNonRetry400Headers.class); } @@ -1077,7 +1071,7 @@ public ServiceCall postNonRetry400Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postNonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.postNonRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1142,8 +1136,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostNonRetry400() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostNonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPostNonRetry400(null, null); return beginPostNonRetry400Delegate(call.execute()); } @@ -1158,8 +1151,7 @@ public ServiceCall beginPostNonRetry400Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostNonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPostNonRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1233,7 +1225,7 @@ private ServiceResponseWithHeaders beginPos */ public ServiceResponseWithHeaders post202NonRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202NonRetry400(product, this.client.getAcceptLanguage()).execute(); + Response result = service.post202NonRetry400(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPost202NonRetry400Headers.class); } @@ -1249,7 +1241,7 @@ public ServiceCall post202NonRetry400Async(final ServiceCallback serviceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202NonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.post202NonRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1314,8 +1306,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202NonRetry400() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPost202NonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202NonRetry400(null, null); return beginPost202NonRetry400Delegate(call.execute()); } @@ -1330,8 +1321,7 @@ public ServiceCall beginPost202NonRetry400Async(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPost202NonRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202NonRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1405,7 +1395,7 @@ private ServiceResponseWithHeaders begin */ public ServiceResponseWithHeaders postAsyncRelativeRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetry400(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRelativeRetry400(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetry400Headers.class); } @@ -1421,7 +1411,7 @@ public ServiceCall postAsyncRelativeRetry400Async(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRelativeRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1486,8 +1476,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetry400() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetry400(null, null); return beginPostAsyncRelativeRetry400Delegate(call.execute()); } @@ -1502,8 +1491,7 @@ public ServiceCall beginPostAsyncRelativeRetry400Async(final ServiceCallback call = service.beginPostAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetry400(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1577,7 +1565,7 @@ private ServiceResponseWithHeaders putError201NoProvisioningStatePayload() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putError201NoProvisioningStatePayload(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1593,7 +1581,7 @@ public ServiceCall putError201NoProvisioningStatePayloadAsync(final ServiceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()); + Call call = service.putError201NoProvisioningStatePayload(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1658,8 +1646,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutError201NoProvisioningStatePayload() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()); + Call call = service.beginPutError201NoProvisioningStatePayload(null, null); return beginPutError201NoProvisioningStatePayloadDelegate(call.execute()); } @@ -1674,8 +1661,7 @@ public ServiceCall beginPutError201NoProvisioningStatePayloadAsync(final Service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()); + Call call = service.beginPutError201NoProvisioningStatePayload(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1750,7 +1736,7 @@ private ServiceResponse beginPutError201NoProvisioningStatePayloadDeleg */ public ServiceResponseWithHeaders putAsyncRelativeRetryNoStatus() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRelativeRetryNoStatus(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryNoStatusHeaders.class); } @@ -1766,7 +1752,7 @@ public ServiceCall putAsyncRelativeRetryNoStatusAsync(final ServiceCallback call = service.putAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRelativeRetryNoStatus(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1831,8 +1817,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryNoStatus() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryNoStatus(null, null); return beginPutAsyncRelativeRetryNoStatusDelegate(call.execute()); } @@ -1847,8 +1832,7 @@ public ServiceCall beginPutAsyncRelativeRetryNoStatusAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryNoStatus(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1922,7 +1906,7 @@ private ServiceResponseWithHeaders putAsyncRelativeRetryNoStatusPayload() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRelativeRetryNoStatusPayload(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryNoStatusPayloadHeaders.class); } @@ -1938,7 +1922,7 @@ public ServiceCall putAsyncRelativeRetryNoStatusPayloadAsync(final ServiceCallba throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRelativeRetryNoStatusPayload(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2003,8 +1987,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryNoStatusPayload() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(null, null); return beginPutAsyncRelativeRetryNoStatusPayloadDelegate(call.execute()); } @@ -2019,8 +2002,7 @@ public ServiceCall beginPutAsyncRelativeRetryNoStatusPayloadAsync(final ServiceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2262,7 +2244,7 @@ private ServiceResponseWithHeaders post202NoLocation() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202NoLocation(product, this.client.getAcceptLanguage()).execute(); + Response result = service.post202NoLocation(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPost202NoLocationHeaders.class); } @@ -2278,7 +2260,7 @@ public ServiceCall post202NoLocationAsync(final ServiceCallback serviceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202NoLocation(product, this.client.getAcceptLanguage()); + Call call = service.post202NoLocation(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2343,8 +2325,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202NoLocation() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPost202NoLocation(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202NoLocation(null, null); return beginPost202NoLocationDelegate(call.execute()); } @@ -2359,8 +2340,7 @@ public ServiceCall beginPost202NoLocationAsync(final ServiceCallback servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPost202NoLocation(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202NoLocation(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2434,7 +2414,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRelativeRetryNoPayload() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRelativeRetryNoPayload(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetryNoPayloadHeaders.class); } @@ -2450,7 +2430,7 @@ public ServiceCall postAsyncRelativeRetryNoPayloadAsync(final ServiceCallback call = service.postAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRelativeRetryNoPayload(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2515,8 +2495,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetryNoPayload() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetryNoPayload(null, null); return beginPostAsyncRelativeRetryNoPayloadDelegate(call.execute()); } @@ -2531,8 +2510,7 @@ public ServiceCall beginPostAsyncRelativeRetryNoPayloadAsync(final ServiceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetryNoPayload(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2606,7 +2584,7 @@ private ServiceResponseWithHeaders put200InvalidJson() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200InvalidJson(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put200InvalidJson(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2622,7 +2600,7 @@ public ServiceCall put200InvalidJsonAsync(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200InvalidJson(product, this.client.getAcceptLanguage()); + Call call = service.put200InvalidJson(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2687,8 +2665,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200InvalidJson() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut200InvalidJson(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200InvalidJson(null, null); return beginPut200InvalidJsonDelegate(call.execute()); } @@ -2703,8 +2680,7 @@ public ServiceCall beginPut200InvalidJsonAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPut200InvalidJson(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200InvalidJson(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2779,7 +2755,7 @@ private ServiceResponse beginPut200InvalidJsonDelegate(Response putAsyncRelativeRetryInvalidHeader() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRelativeRetryInvalidHeader(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryInvalidHeaderHeaders.class); } @@ -2795,7 +2771,7 @@ public ServiceCall putAsyncRelativeRetryInvalidHeaderAsync(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRelativeRetryInvalidHeader(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2860,8 +2836,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryInvalidHeader() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryInvalidHeader(null, null); return beginPutAsyncRelativeRetryInvalidHeaderDelegate(call.execute()); } @@ -2876,8 +2851,7 @@ public ServiceCall beginPutAsyncRelativeRetryInvalidHeaderAsync(final ServiceCal if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryInvalidHeader(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2951,7 +2925,7 @@ private ServiceResponseWithHeaders putAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRelativeRetryInvalidJsonPolling(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryInvalidJsonPollingHeaders.class); } @@ -2967,7 +2941,7 @@ public ServiceCall putAsyncRelativeRetryInvalidJsonPollingAsync(final ServiceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRelativeRetryInvalidJsonPolling(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3032,8 +3006,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(null, null); return beginPutAsyncRelativeRetryInvalidJsonPollingDelegate(call.execute()); } @@ -3048,8 +3021,7 @@ public ServiceCall beginPutAsyncRelativeRetryInvalidJsonPollingAsync(final Servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3375,7 +3347,7 @@ private ServiceResponseWithHeaders post202RetryInvalidHeader() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202RetryInvalidHeader(product, this.client.getAcceptLanguage()).execute(); + Response result = service.post202RetryInvalidHeader(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPost202RetryInvalidHeaderHeaders.class); } @@ -3391,7 +3363,7 @@ public ServiceCall post202RetryInvalidHeaderAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202RetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.post202RetryInvalidHeader(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3456,8 +3428,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202RetryInvalidHeader() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPost202RetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202RetryInvalidHeader(null, null); return beginPost202RetryInvalidHeaderDelegate(call.execute()); } @@ -3472,8 +3443,7 @@ public ServiceCall beginPost202RetryInvalidHeaderAsync(final ServiceCallback call = service.beginPost202RetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202RetryInvalidHeader(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3547,7 +3517,7 @@ private ServiceResponseWithHeaders postAsyncRelativeRetryInvalidHeader() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRelativeRetryInvalidHeader(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetryInvalidHeaderHeaders.class); } @@ -3563,7 +3533,7 @@ public ServiceCall postAsyncRelativeRetryInvalidHeaderAsync(final ServiceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRelativeRetryInvalidHeader(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3628,8 +3598,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetryInvalidHeader() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetryInvalidHeader(null, null); return beginPostAsyncRelativeRetryInvalidHeaderDelegate(call.execute()); } @@ -3644,8 +3613,7 @@ public ServiceCall beginPostAsyncRelativeRetryInvalidHeaderAsync(final ServiceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetryInvalidHeader(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3719,7 +3687,7 @@ private ServiceResponseWithHeaders postAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRelativeRetryInvalidJsonPolling(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetryInvalidJsonPollingHeaders.class); } @@ -3735,7 +3703,7 @@ public ServiceCall postAsyncRelativeRetryInvalidJsonPollingAsync(final ServiceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRelativeRetryInvalidJsonPolling(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3800,8 +3768,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(null, null); return beginPostAsyncRelativeRetryInvalidJsonPollingDelegate(call.execute()); } @@ -3816,8 +3783,7 @@ public ServiceCall beginPostAsyncRelativeRetryInvalidJsonPollingAsync(final Serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java index d5d7fa473ed3e..ab6e8801e1615 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java @@ -105,7 +105,7 @@ interface LROsCustomHeaderService { */ public ServiceResponseWithHeaders putAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRetrySucceeded(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsCustomHeaderPutAsyncRetrySucceededHeaders.class); } @@ -121,7 +121,7 @@ public ServiceCall putAsyncRetrySucceededAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -186,8 +186,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRetrySucceeded(null, null); return beginPutAsyncRetrySucceededDelegate(call.execute()); } @@ -202,8 +201,7 @@ public ServiceCall beginPutAsyncRetrySucceededAsync(final ServiceCallback call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -277,7 +275,7 @@ private ServiceResponseWithHeaders put201CreatingSucceeded200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put201CreatingSucceeded200(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -293,7 +291,7 @@ public ServiceCall put201CreatingSucceeded200Async(final ServiceCallback call = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.put201CreatingSucceeded200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -358,8 +356,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingSucceeded200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingSucceeded200(null, null); return beginPut201CreatingSucceeded200Delegate(call.execute()); } @@ -374,8 +371,7 @@ public ServiceCall beginPut201CreatingSucceeded200Async(final ServiceCallback call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingSucceeded200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -450,7 +446,7 @@ private ServiceResponse beginPut201CreatingSucceeded200Delegate(Respons */ public ServiceResponseWithHeaders post202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202Retry200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.post202Retry200(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsCustomHeaderPost202Retry200Headers.class); } @@ -466,7 +462,7 @@ public ServiceCall post202Retry200Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.post202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -531,8 +527,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202Retry200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202Retry200(null, null); return beginPost202Retry200Delegate(call.execute()); } @@ -547,8 +542,7 @@ public ServiceCall beginPost202Retry200Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -622,7 +616,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders postAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRetrySucceeded(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsCustomHeaderPostAsyncRetrySucceededHeaders.class); } @@ -638,7 +632,7 @@ public ServiceCall postAsyncRetrySucceededAsync(final ServiceCallback serv throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -703,8 +697,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetrySucceeded(null, null); return beginPostAsyncRetrySucceededDelegate(call.execute()); } @@ -719,8 +712,7 @@ public ServiceCall beginPostAsyncRetrySucceededAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java index 6d2e6b6124a47..61229851edae6 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java @@ -384,7 +384,7 @@ interface LROsService { */ public ServiceResponse put200Succeeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200Succeeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put200Succeeded(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -400,7 +400,7 @@ public ServiceCall put200SucceededAsync(final ServiceCallback serviceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200Succeeded(product, this.client.getAcceptLanguage()); + Call call = service.put200Succeeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -465,8 +465,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200Succeeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut200Succeeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200Succeeded(null, null); return beginPut200SucceededDelegate(call.execute()); } @@ -481,8 +480,7 @@ public ServiceCall beginPut200SucceededAsync(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPut200Succeeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200Succeeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -557,7 +555,7 @@ private ServiceResponse beginPut200SucceededDelegate(Response put200SucceededNoState() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200SucceededNoState(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put200SucceededNoState(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -573,7 +571,7 @@ public ServiceCall put200SucceededNoStateAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200SucceededNoState(product, this.client.getAcceptLanguage()); + Call call = service.put200SucceededNoState(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -638,8 +636,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200SucceededNoState() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut200SucceededNoState(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200SucceededNoState(null, null); return beginPut200SucceededNoStateDelegate(call.execute()); } @@ -654,8 +651,7 @@ public ServiceCall beginPut200SucceededNoStateAsync(final ServiceCallback call = service.beginPut200SucceededNoState(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200SucceededNoState(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -729,7 +725,7 @@ private ServiceResponse beginPut200SucceededNoStateDelegate(Response put202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put202Retry200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put202Retry200(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -745,7 +741,7 @@ public ServiceCall put202Retry200Async(final ServiceCallback serviceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.put202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -810,8 +806,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut202Retry200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut202Retry200(null, null); return beginPut202Retry200Delegate(call.execute()); } @@ -826,8 +821,7 @@ public ServiceCall beginPut202Retry200Async(final ServiceCallback servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPut202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -901,7 +895,7 @@ private ServiceResponse beginPut202Retry200Delegate(Response put201CreatingSucceeded200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put201CreatingSucceeded200(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -917,7 +911,7 @@ public ServiceCall put201CreatingSucceeded200Async(final ServiceCallback call = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.put201CreatingSucceeded200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -982,8 +976,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingSucceeded200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingSucceeded200(null, null); return beginPut201CreatingSucceeded200Delegate(call.execute()); } @@ -998,8 +991,7 @@ public ServiceCall beginPut201CreatingSucceeded200Async(final ServiceCallback call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingSucceeded200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1074,7 +1066,7 @@ private ServiceResponse beginPut201CreatingSucceeded200Delegate(Respons */ public ServiceResponse put200UpdatingSucceeded204() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200UpdatingSucceeded204(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put200UpdatingSucceeded204(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1090,7 +1082,7 @@ public ServiceCall put200UpdatingSucceeded204Async(final ServiceCallback call = service.put200UpdatingSucceeded204(product, this.client.getAcceptLanguage()); + Call call = service.put200UpdatingSucceeded204(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1155,8 +1147,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200UpdatingSucceeded204() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut200UpdatingSucceeded204(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200UpdatingSucceeded204(null, null); return beginPut200UpdatingSucceeded204Delegate(call.execute()); } @@ -1171,8 +1162,7 @@ public ServiceCall beginPut200UpdatingSucceeded204Async(final ServiceCallback call = service.beginPut200UpdatingSucceeded204(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200UpdatingSucceeded204(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1246,7 +1236,7 @@ private ServiceResponse beginPut200UpdatingSucceeded204Delegate(Respons */ public ServiceResponse put201CreatingFailed200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingFailed200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put201CreatingFailed200(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1262,7 +1252,7 @@ public ServiceCall put201CreatingFailed200Async(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put201CreatingFailed200(product, this.client.getAcceptLanguage()); + Call call = service.put201CreatingFailed200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1327,8 +1317,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingFailed200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut201CreatingFailed200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingFailed200(null, null); return beginPut201CreatingFailed200Delegate(call.execute()); } @@ -1343,8 +1332,7 @@ public ServiceCall beginPut201CreatingFailed200Async(final ServiceCallback call = service.beginPut201CreatingFailed200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut201CreatingFailed200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1419,7 +1407,7 @@ private ServiceResponse beginPut201CreatingFailed200Delegate(Response put200Acceptedcanceled200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200Acceptedcanceled200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.put200Acceptedcanceled200(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1435,7 +1423,7 @@ public ServiceCall put200Acceptedcanceled200Async(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200Acceptedcanceled200(product, this.client.getAcceptLanguage()); + Call call = service.put200Acceptedcanceled200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1500,8 +1488,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200Acceptedcanceled200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPut200Acceptedcanceled200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200Acceptedcanceled200(null, null); return beginPut200Acceptedcanceled200Delegate(call.execute()); } @@ -1516,8 +1503,7 @@ public ServiceCall beginPut200Acceptedcanceled200Async(final ServiceCallback call = service.beginPut200Acceptedcanceled200(product, this.client.getAcceptLanguage()); + Call call = service.beginPut200Acceptedcanceled200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1591,7 +1577,7 @@ private ServiceResponse beginPut200Acceptedcanceled200Delegate(Response */ public ServiceResponseWithHeaders putNoHeaderInRetry() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putNoHeaderInRetry(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putNoHeaderInRetry(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutNoHeaderInRetryHeaders.class); } @@ -1607,7 +1593,7 @@ public ServiceCall putNoHeaderInRetryAsync(final ServiceCallback servic throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putNoHeaderInRetry(product, this.client.getAcceptLanguage()); + Call call = service.putNoHeaderInRetry(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1672,8 +1658,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutNoHeaderInRetry() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutNoHeaderInRetry(product, this.client.getAcceptLanguage()); + Call call = service.beginPutNoHeaderInRetry(null, null); return beginPutNoHeaderInRetryDelegate(call.execute()); } @@ -1688,8 +1673,7 @@ public ServiceCall beginPutNoHeaderInRetryAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutNoHeaderInRetry(product, this.client.getAcceptLanguage()); + Call call = service.beginPutNoHeaderInRetry(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1763,7 +1747,7 @@ private ServiceResponseWithHeaders begin */ public ServiceResponseWithHeaders putAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRetrySucceeded(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncRetrySucceededHeaders.class); } @@ -1779,7 +1763,7 @@ public ServiceCall putAsyncRetrySucceededAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1844,8 +1828,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRetrySucceeded(null, null); return beginPutAsyncRetrySucceededDelegate(call.execute()); } @@ -1860,8 +1843,7 @@ public ServiceCall beginPutAsyncRetrySucceededAsync(final ServiceCallback call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1935,7 +1917,7 @@ private ServiceResponseWithHeaders b */ public ServiceResponseWithHeaders putAsyncNoRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncNoRetrySucceeded(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncNoRetrySucceededHeaders.class); } @@ -1951,7 +1933,7 @@ public ServiceCall putAsyncNoRetrySucceededAsync(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncNoRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2016,8 +1998,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncNoRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNoRetrySucceeded(null, null); return beginPutAsyncNoRetrySucceededDelegate(call.execute()); } @@ -2032,8 +2013,7 @@ public ServiceCall beginPutAsyncNoRetrySucceededAsync(final ServiceCallback call = service.beginPutAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNoRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2107,7 +2087,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders putAsyncRetryFailed() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRetryFailed(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncRetryFailed(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncRetryFailedHeaders.class); } @@ -2123,7 +2103,7 @@ public ServiceCall putAsyncRetryFailedAsync(final ServiceCallback servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRetryFailed(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncRetryFailed(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2188,8 +2168,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRetryFailed() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncRetryFailed(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRetryFailed(null, null); return beginPutAsyncRetryFailedDelegate(call.execute()); } @@ -2204,8 +2183,7 @@ public ServiceCall beginPutAsyncRetryFailedAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPutAsyncRetryFailed(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncRetryFailed(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2279,7 +2257,7 @@ private ServiceResponseWithHeaders begi */ public ServiceResponseWithHeaders putAsyncNoRetrycanceled() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncNoRetrycanceled(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncNoRetrycanceledHeaders.class); } @@ -2295,7 +2273,7 @@ public ServiceCall putAsyncNoRetrycanceledAsync(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncNoRetrycanceled(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2360,8 +2338,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncNoRetrycanceled() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNoRetrycanceled(null, null); return beginPutAsyncNoRetrycanceledDelegate(call.execute()); } @@ -2376,8 +2353,7 @@ public ServiceCall beginPutAsyncNoRetrycanceledAsync(final ServiceCallback call = service.beginPutAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNoRetrycanceled(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2451,7 +2427,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders putAsyncNoHeaderInRetry() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncNoHeaderInRetry(null, null).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncNoHeaderInRetryHeaders.class); } @@ -2467,7 +2443,7 @@ public ServiceCall putAsyncNoHeaderInRetryAsync(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncNoHeaderInRetry(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2532,8 +2508,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncNoHeaderInRetry() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPutAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNoHeaderInRetry(null, null); return beginPutAsyncNoHeaderInRetryDelegate(call.execute()); } @@ -2548,8 +2523,7 @@ public ServiceCall beginPutAsyncNoHeaderInRetryAsync(final ServiceCallback call = service.beginPutAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNoHeaderInRetry(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2623,7 +2597,7 @@ private ServiceResponseWithHeaders */ public ServiceResponse putNonResource() throws CloudException, IOException, InterruptedException { final Sku sku = null; - Response result = service.putNonResource(sku, this.client.getAcceptLanguage()).execute(); + Response result = service.putNonResource(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2639,7 +2613,7 @@ public ServiceCall putNonResourceAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Sku sku = null; - Call call = service.putNonResource(sku, this.client.getAcceptLanguage()); + Call call = service.putNonResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2704,8 +2678,7 @@ public void onResponse(Call call, Response response) * @return the Sku object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutNonResource() throws CloudException, IOException { - final Sku sku = null; - Call call = service.beginPutNonResource(sku, this.client.getAcceptLanguage()); + Call call = service.beginPutNonResource(null, null); return beginPutNonResourceDelegate(call.execute()); } @@ -2720,8 +2693,7 @@ public ServiceCall beginPutNonResourceAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Sku sku = null; - Call call = service.beginPutNonResource(sku, this.client.getAcceptLanguage()); + Call call = service.beginPutNonResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2795,7 +2767,7 @@ private ServiceResponse beginPutNonResourceDelegate(Response */ public ServiceResponse putAsyncNonResource() throws CloudException, IOException, InterruptedException { final Sku sku = null; - Response result = service.putAsyncNonResource(sku, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncNonResource(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2811,7 +2783,7 @@ public ServiceCall putAsyncNonResourceAsync(final ServiceCallback serviceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Sku sku = null; - Call call = service.putAsyncNonResource(sku, this.client.getAcceptLanguage()); + Call call = service.putAsyncNonResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2876,8 +2848,7 @@ public void onResponse(Call call, Response response) * @return the Sku object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutAsyncNonResource() throws CloudException, IOException { - final Sku sku = null; - Call call = service.beginPutAsyncNonResource(sku, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNonResource(null, null); return beginPutAsyncNonResourceDelegate(call.execute()); } @@ -2892,8 +2863,7 @@ public ServiceCall beginPutAsyncNonResourceAsync(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Sku sku = null; - Call call = service.beginPutAsyncNonResource(sku, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncNonResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2967,7 +2937,7 @@ private ServiceResponse beginPutAsyncNonResourceDelegate(Response putSubResource() throws CloudException, IOException, InterruptedException { final SubProduct product = null; - Response result = service.putSubResource(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putSubResource(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2983,7 +2953,7 @@ public ServiceCall putSubResourceAsync(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final SubProduct product = null; - Call call = service.putSubResource(product, this.client.getAcceptLanguage()); + Call call = service.putSubResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3048,8 +3018,7 @@ public void onResponse(Call call, Response response) * @return the SubProduct object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutSubResource() throws CloudException, IOException { - final SubProduct product = null; - Call call = service.beginPutSubResource(product, this.client.getAcceptLanguage()); + Call call = service.beginPutSubResource(null, null); return beginPutSubResourceDelegate(call.execute()); } @@ -3064,8 +3033,7 @@ public ServiceCall beginPutSubResourceAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final SubProduct product = null; - Call call = service.beginPutSubResource(product, this.client.getAcceptLanguage()); + Call call = service.beginPutSubResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3139,7 +3107,7 @@ private ServiceResponse beginPutSubResourceDelegate(Response putAsyncSubResource() throws CloudException, IOException, InterruptedException { final SubProduct product = null; - Response result = service.putAsyncSubResource(product, this.client.getAcceptLanguage()).execute(); + Response result = service.putAsyncSubResource(null, null).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -3155,7 +3123,7 @@ public ServiceCall putAsyncSubResourceAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final SubProduct product = null; - Call call = service.putAsyncSubResource(product, this.client.getAcceptLanguage()); + Call call = service.putAsyncSubResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3220,8 +3188,7 @@ public void onResponse(Call call, Response response) * @return the SubProduct object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutAsyncSubResource() throws CloudException, IOException { - final SubProduct product = null; - Call call = service.beginPutAsyncSubResource(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncSubResource(null, null); return beginPutAsyncSubResourceDelegate(call.execute()); } @@ -3236,8 +3203,7 @@ public ServiceCall beginPutAsyncSubResourceAsync(final ServiceCallback call = service.beginPutAsyncSubResource(product, this.client.getAcceptLanguage()); + Call call = service.beginPutAsyncSubResource(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4411,7 +4377,7 @@ private ServiceResponse beginPost200WithPayloadDelegate(Response post202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202Retry200(product, this.client.getAcceptLanguage()).execute(); + Response result = service.post202Retry200(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPost202Retry200Headers.class); } @@ -4427,7 +4393,7 @@ public ServiceCall post202Retry200Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.post202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -4492,8 +4458,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202Retry200() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202Retry200(null, null); return beginPost202Retry200Delegate(call.execute()); } @@ -4508,8 +4473,7 @@ public ServiceCall beginPost202Retry200Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202Retry200(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4583,7 +4547,7 @@ private ServiceResponseWithHeaders beginPost20 */ public ServiceResponseWithHeaders post202NoRetry204() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202NoRetry204(product, this.client.getAcceptLanguage()).execute(); + Response result = service.post202NoRetry204(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPost202NoRetry204Headers.class); } @@ -4599,7 +4563,7 @@ public ServiceCall post202NoRetry204Async(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202NoRetry204(product, this.client.getAcceptLanguage()); + Call call = service.post202NoRetry204(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -4664,8 +4628,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPost202NoRetry204() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPost202NoRetry204(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202NoRetry204(null, null); return beginPost202NoRetry204Delegate(call.execute()); } @@ -4680,8 +4643,7 @@ public ServiceCall beginPost202NoRetry204Async(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPost202NoRetry204(product, this.client.getAcceptLanguage()); + Call call = service.beginPost202NoRetry204(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4755,7 +4717,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRetrySucceeded(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncRetrySucceededHeaders.class); } @@ -4771,7 +4733,7 @@ public ServiceCall postAsyncRetrySucceededAsync(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -4836,8 +4798,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetrySucceeded(null, null); return beginPostAsyncRetrySucceededDelegate(call.execute()); } @@ -4852,8 +4813,7 @@ public ServiceCall beginPostAsyncRetrySucceededAsync(final ServiceCallback call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4928,7 +4888,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders postAsyncNoRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncNoRetrySucceeded(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncNoRetrySucceededHeaders.class); } @@ -4944,7 +4904,7 @@ public ServiceCall postAsyncNoRetrySucceededAsync(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncNoRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -5009,8 +4969,7 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPostAsyncNoRetrySucceeded() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncNoRetrySucceeded(null, null); return beginPostAsyncNoRetrySucceededDelegate(call.execute()); } @@ -5025,8 +4984,7 @@ public ServiceCall beginPostAsyncNoRetrySucceededAsync(final ServiceCallback call = service.beginPostAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncNoRetrySucceeded(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -5101,7 +5059,7 @@ private ServiceResponseWithHeaders postAsyncRetryFailed() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetryFailed(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRetryFailed(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncRetryFailedHeaders.class); } @@ -5117,7 +5075,7 @@ public ServiceCall postAsyncRetryFailedAsync(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetryFailed(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRetryFailed(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -5182,8 +5140,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetryFailed() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRetryFailed(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetryFailed(null, null); return beginPostAsyncRetryFailedDelegate(call.execute()); } @@ -5198,8 +5155,7 @@ public ServiceCall beginPostAsyncRetryFailedAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostAsyncRetryFailed(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetryFailed(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -5273,7 +5229,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRetrycanceled() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetrycanceled(product, this.client.getAcceptLanguage()).execute(); + Response result = service.postAsyncRetrycanceled(null, null).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncRetrycanceledHeaders.class); } @@ -5289,7 +5245,7 @@ public ServiceCall postAsyncRetrycanceledAsync(final ServiceCallback servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetrycanceled(product, this.client.getAcceptLanguage()); + Call call = service.postAsyncRetrycanceled(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -5354,8 +5310,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetrycanceled() throws CloudException, IOException { - final Product product = null; - Call call = service.beginPostAsyncRetrycanceled(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetrycanceled(null, null); return beginPostAsyncRetrycanceledDelegate(call.execute()); } @@ -5370,8 +5325,7 @@ public ServiceCall beginPostAsyncRetrycanceledAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product product = null; - Call call = service.beginPostAsyncRetrycanceled(product, this.client.getAcceptLanguage()); + Call call = service.beginPostAsyncRetrycanceled(null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java index 04e7b511039b5..96d3cb4f9ccf0 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java @@ -196,22 +196,12 @@ private ServiceResponse> getSinglePagesDelegate(Response> getMultiplePages() throws CloudException, IOException { - final String clientRequestId = null; - final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; - Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } - Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } - Call call = service.getMultiplePages(clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePages(null, null, null, null); ServiceResponse> response = getMultiplePagesDelegate(call.execute()); PagedList result = new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws CloudException, IOException { - return getMultiplePagesNext(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions).getBody(); + return getMultiplePagesNext(nextPageLink, null, null).getBody(); } }; return new ServiceResponse<>(result, response.getResponse()); @@ -228,17 +218,7 @@ public ServiceCall getMultiplePagesAsync(final ListOperationCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String clientRequestId = null; - final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; - Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } - Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } - Call call = service.getMultiplePages(clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePages(null, null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -248,7 +228,7 @@ public void onResponse(Call call, Response response) serviceCallback.load(result.getBody().getItems()); if (result.getBody().getNextPageLink() != null && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getMultiplePagesNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesOptions, serviceCall, serviceCallback); + getMultiplePagesNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } @@ -355,11 +335,8 @@ public ServiceResponse> getMultiplePagesWithOffset(final Pagi throw new IllegalArgumentException("Parameter pagingGetMultiplePagesWithOffsetOptions is required and cannot be null."); } Validator.validate(pagingGetMultiplePagesWithOffsetOptions); - final String clientRequestId = null; - Integer maxresults = pagingGetMultiplePagesWithOffsetOptions.getMaxresults(); int offset = pagingGetMultiplePagesWithOffsetOptions.getOffset(); - Integer timeout = pagingGetMultiplePagesWithOffsetOptions.getTimeout(); - Call call = service.getMultiplePagesWithOffset(offset, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePagesWithOffset(offset, null, null, null, null); ServiceResponse> response = getMultiplePagesWithOffsetDelegate(call.execute()); PagedList result = new PagedList(response.getBody()) { @Override @@ -367,7 +344,7 @@ public Page nextPage(String nextPageLink) throws CloudException, IOExce PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = new PagingGetMultiplePagesWithOffsetNextOptions(); pagingGetMultiplePagesWithOffsetNextOptions.setMaxresults(pagingGetMultiplePagesWithOffsetOptions.getMaxresults()); pagingGetMultiplePagesWithOffsetNextOptions.setTimeout(pagingGetMultiplePagesWithOffsetOptions.getTimeout()); - return getMultiplePagesWithOffsetNext(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions).getBody(); + return getMultiplePagesWithOffsetNext(nextPageLink, null, null).getBody(); } }; return new ServiceResponse<>(result, response.getResponse()); @@ -390,11 +367,8 @@ public ServiceCall getMultiplePagesWithOffsetAsync(final PagingGetMultiplePagesW return null; } Validator.validate(pagingGetMultiplePagesWithOffsetOptions, serviceCallback); - final String clientRequestId = null; - Integer maxresults = pagingGetMultiplePagesWithOffsetOptions.getMaxresults(); int offset = pagingGetMultiplePagesWithOffsetOptions.getOffset(); - Integer timeout = pagingGetMultiplePagesWithOffsetOptions.getTimeout(); - Call call = service.getMultiplePagesWithOffset(offset, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePagesWithOffset(offset, null, null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -407,7 +381,7 @@ public void onResponse(Call call, Response response) PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = new PagingGetMultiplePagesWithOffsetNextOptions(); pagingGetMultiplePagesWithOffsetNextOptions.setMaxresults(pagingGetMultiplePagesWithOffsetOptions.getMaxresults()); pagingGetMultiplePagesWithOffsetNextOptions.setTimeout(pagingGetMultiplePagesWithOffsetOptions.getTimeout()); - getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, serviceCall, serviceCallback); + getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } @@ -875,17 +849,7 @@ public ServiceResponse> getMultiplePagesNext(final String next if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - final String clientRequestId = null; - final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; - Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } - Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } - Call call = service.getMultiplePagesNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePagesNext(nextPageLink, null, null, null, null); return getMultiplePagesNextDelegate(call.execute()); } @@ -906,17 +870,7 @@ public ServiceCall getMultiplePagesNextAsync(final String nextPageLink, final Se serviceCallback.failure(new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.")); return null; } - final String clientRequestId = null; - final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; - Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } - Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } - Call call = service.getMultiplePagesNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePagesNext(nextPageLink, null, null, null, null); serviceCall.newCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -926,7 +880,7 @@ public void onResponse(Call call, Response response) serviceCallback.load(result.getBody().getItems()); if (result.getBody().getNextPageLink() != null && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getMultiplePagesNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesOptions, serviceCall, serviceCallback); + getMultiplePagesNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } @@ -1036,11 +990,7 @@ public ServiceResponse> getMultiplePagesWithOffsetNext(final S if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - final String clientRequestId = null; - final PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = null; - Integer maxresults = pagingGetMultiplePagesWithOffsetNextOptions.getMaxresults(); - Integer timeout = pagingGetMultiplePagesWithOffsetNextOptions.getTimeout(); - Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, null, null, null, null); return getMultiplePagesWithOffsetNextDelegate(call.execute()); } @@ -1061,11 +1011,7 @@ public ServiceCall getMultiplePagesWithOffsetNextAsync(final String nextPageLink serviceCallback.failure(new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.")); return null; } - final String clientRequestId = null; - final PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = null; - Integer maxresults = pagingGetMultiplePagesWithOffsetNextOptions.getMaxresults(); - Integer timeout = pagingGetMultiplePagesWithOffsetNextOptions.getTimeout(); - Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); + Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, null, null, null, null); serviceCall.newCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -1075,7 +1021,7 @@ public void onResponse(Call call, Response response) serviceCallback.load(result.getBody().getItems()); if (result.getBody().getNextPageLink() != null && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, serviceCall, serviceCallback); + getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index c3ae9afc5126e..993bb1f56af6a 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -225,6 +225,18 @@ public override string MethodParameterInvocationWithCallback } } + public override string MethodRequiredParameterInvocationWithCallback + { + get + { + if (this.IsPagingOperation || this.IsPagingNextOperation) + { + return base.MethodRequiredParameterInvocationWithCallback.Replace("serviceCallback", "serviceCall, serviceCallback"); + } + return base.MethodRequiredParameterInvocationWithCallback; + } + } + public override IEnumerable Exceptions { get @@ -297,43 +309,41 @@ public override string ResponseBuilder } } - public override string ResponseGeneration + public override string ResponseGeneration(bool filterRequired = false) { - get + if (this.IsPagingOperation && !this.IsPagingNextOperation) { - if (this.IsPagingOperation && !this.IsPagingNextOperation) - { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0} response = {1}Delegate(call.execute());", - ReturnTypeModel.WireResponseTypeString, this.Name); + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0} response = {1}Delegate(call.execute());", + ReturnTypeModel.WireResponseTypeString, this.Name); - string invocation; - AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation); - - builder.AppendLine("PagedList<{0}> result = new PagedList<{0}>(response.getBody()) {{", ((SequenceType)ReturnType.Body).ElementType.Name) - .Indent().AppendLine("@Override") - .AppendLine("public Page<{0}> nextPage(String nextPageLink) throws {1}, IOException {{", - ((SequenceType)ReturnType.Body).ElementType.Name, - OperationExceptionTypeString) - .Indent(); - TransformPagingGroupedParameter(builder, nextMethod); - builder.AppendLine("return {0}({1}).getBody();", invocation, nextMethod.MethodParameterInvocation) - .Outdent().AppendLine("}") - .Outdent().AppendLine("};"); - return builder.ToString(); - } - else if (this.IsPagingNonPollingOperation) - { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0}> response = {2}Delegate(call.execute());", - ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); - builder.AppendLine("{0} result = response.getBody().getItems();", this.ReturnType.Body.Name); - return builder.ToString(); - } - else - { - return base.ResponseGeneration; - } + string invocation; + AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation); + + builder.AppendLine("PagedList<{0}> result = new PagedList<{0}>(response.getBody()) {{", ((SequenceType)ReturnType.Body).ElementType.Name) + .Indent().AppendLine("@Override") + .AppendLine("public Page<{0}> nextPage(String nextPageLink) throws {1}, IOException {{", + ((SequenceType)ReturnType.Body).ElementType.Name, + OperationExceptionTypeString) + .Indent(); + TransformPagingGroupedParameter(builder, nextMethod, filterRequired); + builder.AppendLine("return {0}({1}).getBody();", + invocation, filterRequired ? nextMethod.MethodRequiredParameterInvocation : nextMethod.MethodParameterInvocation) + .Outdent().AppendLine("}") + .Outdent().AppendLine("};"); + return builder.ToString(); + } + else if (this.IsPagingNonPollingOperation) + { + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0}> response = {2}Delegate(call.execute());", + ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + builder.AppendLine("{0} result = response.getBody().getItems();", this.ReturnType.Body.Name); + return builder.ToString(); + } + else + { + return base.ResponseGeneration(); } } @@ -361,77 +371,74 @@ public override string ReturnValue } } - public override string SuccessCallback + public override string SuccessCallback(bool filterRequired = false) { - get + if (this.IsPagingOperation) + { + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0} result = {1}Delegate(response);", + ReturnTypeModel.WireResponseTypeString, this.Name); + builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); + builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent() + .AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); + string invocation; + AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation, true); + TransformPagingGroupedParameter(builder, nextMethod, filterRequired); + var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}(result.getBody().getNextPageLink(), {1});", + invocation, + filterRequired ? nextMethod.MethodRequiredParameterInvocationWithCallback : nextMethod.MethodParameterInvocationWithCallback); + builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); + builder.AppendLine("} else {").Indent(); + if (ReturnType.Headers == null) + { + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); + } + else + { + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); + } + builder.Outdent().AppendLine("}"); + return builder.ToString(); + } + else if (this.IsPagingNextOperation) { - if (this.IsPagingOperation) + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0} result = {1}Delegate(response);", ReturnTypeModel.WireResponseTypeString, this.Name); + builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); + builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent(); + builder.AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); + var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}Async(result.getBody().getNextPageLink(), {1});", + this.Name, + filterRequired ? MethodRequiredParameterInvocationWithCallback : MethodParameterInvocationWithCallback); + builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); + builder.AppendLine("} else {").Indent(); + if (ReturnType.Headers == null) { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0} result = {1}Delegate(response);", - ReturnTypeModel.WireResponseTypeString, this.Name); - builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); - builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent() - .AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); - string invocation; - AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation, true); - TransformPagingGroupedParameter(builder, nextMethod); - var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}(result.getBody().getNextPageLink(), {1});", - invocation, - nextMethod.MethodParameterInvocationWithCallback); - builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); - builder.AppendLine("} else {").Indent(); - if (ReturnType.Headers == null) - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); - } - else - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); - } - builder.Outdent().AppendLine("}"); - return builder.ToString(); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } - else if (this.IsPagingNextOperation) + else { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0} result = {1}Delegate(response);", ReturnTypeModel.WireResponseTypeString, this.Name); - builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); - builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent(); - builder.AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); - var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}Async(result.getBody().getNextPageLink(), {1});", - this.Name, - this.MethodParameterInvocationWithCallback); - builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); - builder.AppendLine("} else {").Indent(); - if (ReturnType.Headers == null) - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); - } - else - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); - } - builder.Outdent().AppendLine("}"); - return builder.ToString(); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); + } + builder.Outdent().AppendLine("}"); + return builder.ToString(); + } + else if (this.IsPagingNonPollingOperation) + { + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0}> result = {2}Delegate(response);", + ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + if (ReturnType.Headers == null) + { + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } - else if (this.IsPagingNonPollingOperation) + else { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0}> result = {2}Delegate(response);", - ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); - if (ReturnType.Headers == null) - { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", ReturnTypeModel.ClientResponseType); - } - else - { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); - } - return builder.ToString(); + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } - return base.SuccessCallback; + return builder.ToString(); } + return base.SuccessCallback(); } private AzureMethodTemplateModel GetPagingNextMethod(out string invocation, bool async = false) @@ -462,7 +469,7 @@ private AzureMethodTemplateModel GetPagingNextMethod(out string invocation, bool return methodModel; } - private void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod) + private void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod, bool filterRequired = false) { if (this.InputParameterTransformation.IsNullOrEmpty()) { @@ -474,6 +481,10 @@ private void TransformPagingGroupedParameter(IndentedStringBuilder builder, Azur { return; } + if (filterRequired && !nextGroupType.IsRequired) + { + return; + } if (!groupedType.IsRequired) { builder.AppendLine("{0} {1} = null;", nextGroupType.Name.ToPascalCase(), nextGroupType.Name.ToCamelCase()); diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index 9de6087ceb14b..9d7a181f3d2a6 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -68,8 +68,8 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth } } @Model.BuildInputMappings() - @Model.ParameterConversion - Response result = service.@(Model.Name)(@Model.MethodParameterApiInvocation).execute(); + @Model.RequiredParameterConversion + Response result = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation).execute(); return client.getAzureClient().@(Model.PollingMethod)(result, @Model.PollingResourceTypeArgs); } @EmptyLine @@ -118,8 +118,8 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW } } @Model.BuildInputMappings() - @Model.ParameterConversion - Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); + @Model.RequiredParameterConversion + Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback<@Model.CallType>() { @@Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java index d4b1368b107ae..7389355d46475 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java @@ -144,8 +144,7 @@ private ServiceResponse getNullDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putNull() throws ErrorException, IOException { - final String stringBody = null; - Call call = service.putNull(stringBody); + Call call = service.putNull(null); return putNullDelegate(call.execute()); } @@ -160,8 +159,7 @@ public ServiceCall putNullAsync(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String stringBody = null; - Call call = service.putNull(stringBody); + Call call = service.putNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index eedde38b0a9e8..1af871dd1d83d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -964,8 +964,7 @@ public ServiceResponse paramString(String scenario) throws ErrorException, if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - final String value = null; - Call call = service.paramString(scenario, value); + Call call = service.paramString(scenario, null); return paramStringDelegate(call.execute()); } @@ -985,8 +984,7 @@ public ServiceCall paramStringAsync(String scenario, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - final String value = null; - Call call = service.paramString(scenario, value); + Call call = service.paramString(scenario, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1364,9 +1362,7 @@ public ServiceResponse paramDatetimeRfc1123(String scenario) throws ErrorE if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - final DateTime value = null; - DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); - Call call = service.paramDatetimeRfc1123(scenario, valueConverted); + Call call = service.paramDatetimeRfc1123(scenario, null); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1386,9 +1382,7 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, final ServiceCallb serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - final DateTime value = null; - DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); - Call call = service.paramDatetimeRfc1123(scenario, valueConverted); + Call call = service.paramDatetimeRfc1123(scenario, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1770,8 +1764,7 @@ public ServiceResponse paramEnum(String scenario) throws ErrorException, I if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - final GreyscaleColors value = null; - Call call = service.paramEnum(scenario, value); + Call call = service.paramEnum(scenario, null); return paramEnumDelegate(call.execute()); } @@ -1791,8 +1784,7 @@ public ServiceCall paramEnumAsync(String scenario, final ServiceCallback s serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - final GreyscaleColors value = null; - Call call = service.paramEnum(scenario, value); + Call call = service.paramEnum(scenario, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java index bd6d6718be372..665480b5dc2cb 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java @@ -248,8 +248,7 @@ private ServiceResponse get400Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put400() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put400(booleanValue); + Call call = service.put400(null); return put400Delegate(call.execute()); } @@ -264,8 +263,7 @@ public ServiceCall put400Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put400(booleanValue); + Call call = service.put400(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -334,8 +332,7 @@ private ServiceResponse put400Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse patch400() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch400(booleanValue); + Call call = service.patch400(null); return patch400Delegate(call.execute()); } @@ -350,8 +347,7 @@ public ServiceCall patch400Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch400(booleanValue); + Call call = service.patch400(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -420,8 +416,7 @@ private ServiceResponse patch400Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post400() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post400(booleanValue); + Call call = service.post400(null); return post400Delegate(call.execute()); } @@ -436,8 +431,7 @@ public ServiceCall post400Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post400(booleanValue); + Call call = service.post400(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -506,8 +500,7 @@ private ServiceResponse post400Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete400() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete400(booleanValue); + Call call = service.delete400(null); return delete400Delegate(call.execute()); } @@ -522,8 +515,7 @@ public ServiceCall delete400Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete400(booleanValue); + Call call = service.delete400(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -724,8 +716,7 @@ private ServiceResponse get403Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put404() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put404(booleanValue); + Call call = service.put404(null); return put404Delegate(call.execute()); } @@ -740,8 +731,7 @@ public ServiceCall put404Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put404(booleanValue); + Call call = service.put404(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -810,8 +800,7 @@ private ServiceResponse put404Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse patch405() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch405(booleanValue); + Call call = service.patch405(null); return patch405Delegate(call.execute()); } @@ -826,8 +815,7 @@ public ServiceCall patch405Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch405(booleanValue); + Call call = service.patch405(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -896,8 +884,7 @@ private ServiceResponse patch405Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post406() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post406(booleanValue); + Call call = service.post406(null); return post406Delegate(call.execute()); } @@ -912,8 +899,7 @@ public ServiceCall post406Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post406(booleanValue); + Call call = service.post406(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -982,8 +968,7 @@ private ServiceResponse post406Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete407() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete407(booleanValue); + Call call = service.delete407(null); return delete407Delegate(call.execute()); } @@ -998,8 +983,7 @@ public ServiceCall delete407Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete407(booleanValue); + Call call = service.delete407(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1068,8 +1052,7 @@ private ServiceResponse delete407Delegate(Response response * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put409() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put409(booleanValue); + Call call = service.put409(null); return put409Delegate(call.execute()); } @@ -1084,8 +1067,7 @@ public ServiceCall put409Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put409(booleanValue); + Call call = service.put409(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1286,8 +1268,7 @@ private ServiceResponse get412Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put413() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put413(booleanValue); + Call call = service.put413(null); return put413Delegate(call.execute()); } @@ -1302,8 +1283,7 @@ public ServiceCall put413Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put413(booleanValue); + Call call = service.put413(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1372,8 +1352,7 @@ private ServiceResponse put413Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse patch414() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch414(booleanValue); + Call call = service.patch414(null); return patch414Delegate(call.execute()); } @@ -1388,8 +1367,7 @@ public ServiceCall patch414Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch414(booleanValue); + Call call = service.patch414(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1458,8 +1436,7 @@ private ServiceResponse patch414Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post415() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post415(booleanValue); + Call call = service.post415(null); return post415Delegate(call.execute()); } @@ -1474,8 +1451,7 @@ public ServiceCall post415Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post415(booleanValue); + Call call = service.post415(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1588,8 +1564,7 @@ private ServiceResponse get416Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete417() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete417(booleanValue); + Call call = service.delete417(null); return delete417Delegate(call.execute()); } @@ -1604,8 +1579,7 @@ public ServiceCall delete417Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete417(booleanValue); + Call call = service.delete417(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java index d422aab756c84..0c2eb12a0639a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java @@ -328,8 +328,7 @@ private ServiceResponseWithHeaders get301Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders put301() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put301(booleanValue); + Call call = service.put301(null); return put301Delegate(call.execute()); } @@ -344,8 +343,7 @@ public ServiceCall put301Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put301(booleanValue); + Call call = service.put301(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -507,8 +505,7 @@ private ServiceResponseWithHeaders get302Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders patch302() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch302(booleanValue); + Call call = service.patch302(null); return patch302Delegate(call.execute()); } @@ -523,8 +520,7 @@ public ServiceCall patch302Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch302(booleanValue); + Call call = service.patch302(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -594,8 +590,7 @@ private ServiceResponseWithHeaders patch302D * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders post303() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post303(booleanValue); + Call call = service.post303(null); return post303Delegate(call.execute()); } @@ -610,8 +605,7 @@ public ServiceCall post303Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post303(booleanValue); + Call call = service.post303(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -774,8 +768,7 @@ private ServiceResponseWithHeaders get307Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders put307() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put307(booleanValue); + Call call = service.put307(null); return put307Delegate(call.execute()); } @@ -790,8 +783,7 @@ public ServiceCall put307Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put307(booleanValue); + Call call = service.put307(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -862,8 +854,7 @@ private ServiceResponseWithHeaders put307Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders patch307() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch307(booleanValue); + Call call = service.patch307(null); return patch307Delegate(call.execute()); } @@ -878,8 +869,7 @@ public ServiceCall patch307Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch307(booleanValue); + Call call = service.patch307(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -950,8 +940,7 @@ private ServiceResponseWithHeaders patch307D * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders post307() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post307(booleanValue); + Call call = service.post307(null); return post307Delegate(call.execute()); } @@ -966,8 +955,7 @@ public ServiceCall post307Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post307(booleanValue); + Call call = service.post307(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1038,8 +1026,7 @@ private ServiceResponseWithHeaders post307Del * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders delete307() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete307(booleanValue); + Call call = service.delete307(null); return delete307Delegate(call.execute()); } @@ -1054,8 +1041,7 @@ public ServiceCall delete307Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete307(booleanValue); + Call call = service.delete307(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java index d3ba17ef439c6..d05003ef66d57 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java @@ -145,8 +145,7 @@ private ServiceResponse head408Delegate(Response response) throws Er * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put500() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put500(booleanValue); + Call call = service.put500(null); return put500Delegate(call.execute()); } @@ -161,8 +160,7 @@ public ServiceCall put500Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put500(booleanValue); + Call call = service.put500(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -232,8 +230,7 @@ private ServiceResponse put500Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch500() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch500(booleanValue); + Call call = service.patch500(null); return patch500Delegate(call.execute()); } @@ -248,8 +245,7 @@ public ServiceCall patch500Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch500(booleanValue); + Call call = service.patch500(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -364,8 +360,7 @@ private ServiceResponse get502Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post503() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post503(booleanValue); + Call call = service.post503(null); return post503Delegate(call.execute()); } @@ -380,8 +375,7 @@ public ServiceCall post503Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post503(booleanValue); + Call call = service.post503(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -451,8 +445,7 @@ private ServiceResponse post503Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete503() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete503(booleanValue); + Call call = service.delete503(null); return delete503Delegate(call.execute()); } @@ -467,8 +460,7 @@ public ServiceCall delete503Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete503(booleanValue); + Call call = service.delete503(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -538,8 +530,7 @@ private ServiceResponse delete503Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put504() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put504(booleanValue); + Call call = service.put504(null); return put504Delegate(call.execute()); } @@ -554,8 +545,7 @@ public ServiceCall put504Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put504(booleanValue); + Call call = service.put504(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -625,8 +615,7 @@ private ServiceResponse put504Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch504() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch504(booleanValue); + Call call = service.patch504(null); return patch504Delegate(call.execute()); } @@ -641,8 +630,7 @@ public ServiceCall patch504Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch504(booleanValue); + Call call = service.patch504(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java index 1ea87e8af11a7..d77f6a9fb77b7 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java @@ -170,8 +170,7 @@ private ServiceResponse get501Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post505() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post505(booleanValue); + Call call = service.post505(null); return post505Delegate(call.execute()); } @@ -186,8 +185,7 @@ public ServiceCall post505Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post505(booleanValue); + Call call = service.post505(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -256,8 +254,7 @@ private ServiceResponse post505Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete505() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete505(booleanValue); + Call call = service.delete505(null); return delete505Delegate(call.execute()); } @@ -272,8 +269,7 @@ public ServiceCall delete505Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete505(booleanValue); + Call call = service.delete505(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java index 09ab15c84944e..496ba12e8376c 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java @@ -230,8 +230,7 @@ private ServiceResponse get200Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put200() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put200(booleanValue); + Call call = service.put200(null); return put200Delegate(call.execute()); } @@ -246,8 +245,7 @@ public ServiceCall put200Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put200(booleanValue); + Call call = service.put200(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -317,8 +315,7 @@ private ServiceResponse put200Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch200() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch200(booleanValue); + Call call = service.patch200(null); return patch200Delegate(call.execute()); } @@ -333,8 +330,7 @@ public ServiceCall patch200Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch200(booleanValue); + Call call = service.patch200(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -404,8 +400,7 @@ private ServiceResponse patch200Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post200() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post200(booleanValue); + Call call = service.post200(null); return post200Delegate(call.execute()); } @@ -420,8 +415,7 @@ public ServiceCall post200Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post200(booleanValue); + Call call = service.post200(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -491,8 +485,7 @@ private ServiceResponse post200Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete200() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete200(booleanValue); + Call call = service.delete200(null); return delete200Delegate(call.execute()); } @@ -507,8 +500,7 @@ public ServiceCall delete200Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete200(booleanValue); + Call call = service.delete200(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -578,8 +570,7 @@ private ServiceResponse delete200Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put201() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put201(booleanValue); + Call call = service.put201(null); return put201Delegate(call.execute()); } @@ -594,8 +585,7 @@ public ServiceCall put201Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put201(booleanValue); + Call call = service.put201(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -665,8 +655,7 @@ private ServiceResponse put201Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post201() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post201(booleanValue); + Call call = service.post201(null); return post201Delegate(call.execute()); } @@ -681,8 +670,7 @@ public ServiceCall post201Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post201(booleanValue); + Call call = service.post201(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -752,8 +740,7 @@ private ServiceResponse post201Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put202() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put202(booleanValue); + Call call = service.put202(null); return put202Delegate(call.execute()); } @@ -768,8 +755,7 @@ public ServiceCall put202Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put202(booleanValue); + Call call = service.put202(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -839,8 +825,7 @@ private ServiceResponse put202Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch202() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch202(booleanValue); + Call call = service.patch202(null); return patch202Delegate(call.execute()); } @@ -855,8 +840,7 @@ public ServiceCall patch202Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch202(booleanValue); + Call call = service.patch202(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -926,8 +910,7 @@ private ServiceResponse patch202Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post202() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post202(booleanValue); + Call call = service.post202(null); return post202Delegate(call.execute()); } @@ -942,8 +925,7 @@ public ServiceCall post202Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post202(booleanValue); + Call call = service.post202(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1013,8 +995,7 @@ private ServiceResponse post202Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete202() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete202(booleanValue); + Call call = service.delete202(null); return delete202Delegate(call.execute()); } @@ -1029,8 +1010,7 @@ public ServiceCall delete202Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete202(booleanValue); + Call call = service.delete202(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1145,8 +1125,7 @@ private ServiceResponse head204Delegate(Response response) throws Er * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put204() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.put204(booleanValue); + Call call = service.put204(null); return put204Delegate(call.execute()); } @@ -1161,8 +1140,7 @@ public ServiceCall put204Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.put204(booleanValue); + Call call = service.put204(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1232,8 +1210,7 @@ private ServiceResponse put204Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch204() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.patch204(booleanValue); + Call call = service.patch204(null); return patch204Delegate(call.execute()); } @@ -1248,8 +1225,7 @@ public ServiceCall patch204Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.patch204(booleanValue); + Call call = service.patch204(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1319,8 +1295,7 @@ private ServiceResponse patch204Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post204() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.post204(booleanValue); + Call call = service.post204(null); return post204Delegate(call.execute()); } @@ -1335,8 +1310,7 @@ public ServiceCall post204Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.post204(booleanValue); + Call call = service.post204(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1406,8 +1380,7 @@ private ServiceResponse post204Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete204() throws ErrorException, IOException { - final Boolean booleanValue = null; - Call call = service.delete204(booleanValue); + Call call = service.delete204(null); return delete204Delegate(call.execute()); } @@ -1422,8 +1395,7 @@ public ServiceCall delete204Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean booleanValue = null; - Call call = service.delete204(booleanValue); + Call call = service.delete204(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java index a85d96f940b26..a49d8d7625da1 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java @@ -169,8 +169,7 @@ interface AutoRestResourceFlatteningTestServiceService { * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putArray() throws ErrorException, IOException { - final List resourceArray = null; - Call call = service.putArray(resourceArray); + Call call = service.putArray(null); return putArrayDelegate(call.execute()); } @@ -185,8 +184,7 @@ public ServiceCall putArrayAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List resourceArray = null; - Call call = service.putArray(resourceArray); + Call call = service.putArray(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -303,8 +301,7 @@ private ServiceResponse> getArrayDelegate(Response putDictionary() throws ErrorException, IOException { - final Map resourceDictionary = null; - Call call = service.putDictionary(resourceDictionary); + Call call = service.putDictionary(null); return putDictionaryDelegate(call.execute()); } @@ -319,8 +316,7 @@ public ServiceCall putDictionaryAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Map resourceDictionary = null; - Call call = service.putDictionary(resourceDictionary); + Call call = service.putDictionary(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -437,8 +433,7 @@ private ServiceResponse> getDictionaryDelegate(Res * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putResourceCollection() throws ErrorException, IOException { - final ResourceCollection resourceComplexObject = null; - Call call = service.putResourceCollection(resourceComplexObject); + Call call = service.putResourceCollection(null); return putResourceCollectionDelegate(call.execute()); } @@ -453,8 +448,7 @@ public ServiceCall putResourceCollectionAsync(final ServiceCallback servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final ResourceCollection resourceComplexObject = null; - Call call = service.putResourceCollection(resourceComplexObject); + Call call = service.putResourceCollection(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -571,8 +565,7 @@ private ServiceResponse getResourceCollectionDelegate(Respon * @return the SimpleProduct object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse putSimpleProduct() throws ErrorException, IOException { - final SimpleProduct simpleBodyProduct = null; - Call call = service.putSimpleProduct(simpleBodyProduct); + Call call = service.putSimpleProduct(null); return putSimpleProductDelegate(call.execute()); } @@ -587,8 +580,7 @@ public ServiceCall putSimpleProductAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final SimpleProduct simpleBodyProduct = null; - Call call = service.putSimpleProduct(simpleBodyProduct); + Call call = service.putSimpleProduct(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -669,17 +661,10 @@ public ServiceResponse postFlattenedSimpleProduct(String productI if (maxProductDisplayName == null) { throw new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null."); } - final String description = null; - final String odatavalue = null; - SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { - simpleBodyProduct = new SimpleProduct(); - simpleBodyProduct.setProductId(productId); - simpleBodyProduct.setDescription(description); - simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); - simpleBodyProduct.setOdatavalue(odatavalue); - } - Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); + SimpleProduct simpleBodyProduct = new SimpleProduct(); + simpleBodyProduct.setProductId(productId); + simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + Call call = service.postFlattenedSimpleProduct(null); return postFlattenedSimpleProductDelegate(call.execute()); } @@ -704,17 +689,10 @@ public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxP serviceCallback.failure(new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null.")); return null; } - final String description = null; - final String odatavalue = null; - SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { - simpleBodyProduct = new SimpleProduct(); - simpleBodyProduct.setProductId(productId); - simpleBodyProduct.setDescription(description); - simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); - simpleBodyProduct.setOdatavalue(odatavalue); - } - Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); + SimpleProduct simpleBodyProduct = new SimpleProduct(); + simpleBodyProduct.setProductId(productId); + simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + Call call = service.postFlattenedSimpleProduct(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java index eb8ab498ffdfd..8cabd82bca5a0 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java @@ -210,8 +210,7 @@ private ServiceResponse postRequiredIntegerParameterDelegate(Response postOptionalIntegerParameter() throws ErrorException, IOException { - final Integer bodyParameter = null; - Call call = service.postOptionalIntegerParameter(bodyParameter); + Call call = service.postOptionalIntegerParameter(null); return postOptionalIntegerParameterDelegate(call.execute()); } @@ -226,8 +225,7 @@ public ServiceCall postOptionalIntegerParameterAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Integer bodyParameter = null; - Call call = service.postOptionalIntegerParameter(bodyParameter); + Call call = service.postOptionalIntegerParameter(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -353,8 +351,7 @@ private ServiceResponse postRequiredIntegerPropertyDelegate(Response postOptionalIntegerProperty() throws ErrorException, IOException { - final IntOptionalWrapper bodyParameter = null; - Call call = service.postOptionalIntegerProperty(bodyParameter); + Call call = service.postOptionalIntegerProperty(null); return postOptionalIntegerPropertyDelegate(call.execute()); } @@ -369,8 +366,7 @@ public ServiceCall postOptionalIntegerPropertyAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final IntOptionalWrapper bodyParameter = null; - Call call = service.postOptionalIntegerProperty(bodyParameter); + Call call = service.postOptionalIntegerProperty(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -488,8 +484,7 @@ private ServiceResponse postRequiredIntegerHeaderDelegate(Response postOptionalIntegerHeader() throws ErrorException, IOException { - final Integer headerParameter = null; - Call call = service.postOptionalIntegerHeader(headerParameter); + Call call = service.postOptionalIntegerHeader(null); return postOptionalIntegerHeaderDelegate(call.execute()); } @@ -504,8 +499,7 @@ public ServiceCall postOptionalIntegerHeaderAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Integer headerParameter = null; - Call call = service.postOptionalIntegerHeader(headerParameter); + Call call = service.postOptionalIntegerHeader(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -629,8 +623,7 @@ private ServiceResponse postRequiredStringParameterDelegate(Response postOptionalStringParameter() throws ErrorException, IOException { - final String bodyParameter = null; - Call call = service.postOptionalStringParameter(bodyParameter); + Call call = service.postOptionalStringParameter(null); return postOptionalStringParameterDelegate(call.execute()); } @@ -645,8 +638,7 @@ public ServiceCall postOptionalStringParameterAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String bodyParameter = null; - Call call = service.postOptionalStringParameter(bodyParameter); + Call call = service.postOptionalStringParameter(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -772,8 +764,7 @@ private ServiceResponse postRequiredStringPropertyDelegate(Response postOptionalStringProperty() throws ErrorException, IOException { - final StringOptionalWrapper bodyParameter = null; - Call call = service.postOptionalStringProperty(bodyParameter); + Call call = service.postOptionalStringProperty(null); return postOptionalStringPropertyDelegate(call.execute()); } @@ -788,8 +779,7 @@ public ServiceCall postOptionalStringPropertyAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final StringOptionalWrapper bodyParameter = null; - Call call = service.postOptionalStringProperty(bodyParameter); + Call call = service.postOptionalStringProperty(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -915,8 +905,7 @@ private ServiceResponse postRequiredStringHeaderDelegate(Response postOptionalStringHeader() throws ErrorException, IOException { - final String bodyParameter = null; - Call call = service.postOptionalStringHeader(bodyParameter); + Call call = service.postOptionalStringHeader(null); return postOptionalStringHeaderDelegate(call.execute()); } @@ -931,8 +920,7 @@ public ServiceCall postOptionalStringHeaderAsync(final ServiceCallback ser if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String bodyParameter = null; - Call call = service.postOptionalStringHeader(bodyParameter); + Call call = service.postOptionalStringHeader(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1058,8 +1046,7 @@ private ServiceResponse postRequiredClassParameterDelegate(Response postOptionalClassParameter() throws ErrorException, IOException { - final Product bodyParameter = null; - Call call = service.postOptionalClassParameter(bodyParameter); + Call call = service.postOptionalClassParameter(null); return postOptionalClassParameterDelegate(call.execute()); } @@ -1074,8 +1061,7 @@ public ServiceCall postOptionalClassParameterAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Product bodyParameter = null; - Call call = service.postOptionalClassParameter(bodyParameter); + Call call = service.postOptionalClassParameter(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1203,8 +1189,7 @@ private ServiceResponse postRequiredClassPropertyDelegate(Response postOptionalClassProperty() throws ErrorException, IOException { - final ClassOptionalWrapper bodyParameter = null; - Call call = service.postOptionalClassProperty(bodyParameter); + Call call = service.postOptionalClassProperty(null); return postOptionalClassPropertyDelegate(call.execute()); } @@ -1219,8 +1204,7 @@ public ServiceCall postOptionalClassPropertyAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final ClassOptionalWrapper bodyParameter = null; - Call call = service.postOptionalClassProperty(bodyParameter); + Call call = service.postOptionalClassProperty(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1348,8 +1332,7 @@ private ServiceResponse postRequiredArrayParameterDelegate(Response postOptionalArrayParameter() throws ErrorException, IOException { - final List bodyParameter = null; - Call call = service.postOptionalArrayParameter(bodyParameter); + Call call = service.postOptionalArrayParameter(null); return postOptionalArrayParameterDelegate(call.execute()); } @@ -1364,8 +1347,7 @@ public ServiceCall postOptionalArrayParameterAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List bodyParameter = null; - Call call = service.postOptionalArrayParameter(bodyParameter); + Call call = service.postOptionalArrayParameter(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1493,8 +1475,7 @@ private ServiceResponse postRequiredArrayPropertyDelegate(Response postOptionalArrayProperty() throws ErrorException, IOException { - final ArrayOptionalWrapper bodyParameter = null; - Call call = service.postOptionalArrayProperty(bodyParameter); + Call call = service.postOptionalArrayProperty(null); return postOptionalArrayPropertyDelegate(call.execute()); } @@ -1509,8 +1490,7 @@ public ServiceCall postOptionalArrayPropertyAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final ArrayOptionalWrapper bodyParameter = null; - Call call = service.postOptionalArrayProperty(bodyParameter); + Call call = service.postOptionalArrayProperty(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1640,9 +1620,7 @@ private ServiceResponse postRequiredArrayHeaderDelegate(Response postOptionalArrayHeader() throws ErrorException, IOException { - final List headerParameter = null; - String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); - Call call = service.postOptionalArrayHeader(headerParameterConverted); + Call call = service.postOptionalArrayHeader(null); return postOptionalArrayHeaderDelegate(call.execute()); } @@ -1657,9 +1635,7 @@ public ServiceCall postOptionalArrayHeaderAsync(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List headerParameter = null; - String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); - Call call = service.postOptionalArrayHeader(headerParameterConverted); + Call call = service.postOptionalArrayHeader(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java index 4b8c4626cc9f5..a854b28e527d3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java @@ -149,8 +149,7 @@ private ServiceResponse getRequiredPathDelegate(Response re * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putOptionalQuery() throws ErrorException, IOException { - final String queryParameter = null; - Call call = service.putOptionalQuery(queryParameter); + Call call = service.putOptionalQuery(null); return putOptionalQueryDelegate(call.execute()); } @@ -165,8 +164,7 @@ public ServiceCall putOptionalQueryAsync(final ServiceCallback serviceCall if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String queryParameter = null; - Call call = service.putOptionalQuery(queryParameter); + Call call = service.putOptionalQuery(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -236,8 +234,7 @@ private ServiceResponse putOptionalQueryDelegate(Response re * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putOptionalHeader() throws ErrorException, IOException { - final String queryParameter = null; - Call call = service.putOptionalHeader(queryParameter); + Call call = service.putOptionalHeader(null); return putOptionalHeaderDelegate(call.execute()); } @@ -252,8 +249,7 @@ public ServiceCall putOptionalHeaderAsync(final ServiceCallback serviceCal if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String queryParameter = null; - Call call = service.putOptionalHeader(queryParameter); + Call call = service.putOptionalHeader(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -323,8 +319,7 @@ private ServiceResponse putOptionalHeaderDelegate(Response r * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putOptionalBody() throws ErrorException, IOException { - final String bodyParameter = null; - Call call = service.putOptionalBody(bodyParameter); + Call call = service.putOptionalBody(null); return putOptionalBodyDelegate(call.execute()); } @@ -339,8 +334,7 @@ public ServiceCall putOptionalBodyAsync(final ServiceCallback serviceCallb if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String bodyParameter = null; - Call call = service.putOptionalBody(bodyParameter); + Call call = service.putOptionalBody(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java index c7085c350749f..357ea0ea755ea 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java @@ -91,9 +91,7 @@ public ServiceResponse getAllWithValues(String localStringPath, String pat if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); return getAllWithValuesDelegate(call.execute()); } @@ -122,9 +120,7 @@ public ServiceCall getAllWithValuesAsync(String localStringPath, String pathItem serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -234,9 +230,7 @@ public ServiceResponse getGlobalQueryNull(String localStringPath, String p if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); return getGlobalQueryNullDelegate(call.execute()); } @@ -265,9 +259,7 @@ public ServiceCall getGlobalQueryNullAsync(String localStringPath, String pathIt serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -377,9 +369,7 @@ public ServiceResponse getGlobalAndLocalQueryNull(String localStringPath, if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); return getGlobalAndLocalQueryNullDelegate(call.execute()); } @@ -408,9 +398,7 @@ public ServiceCall getGlobalAndLocalQueryNullAsync(String localStringPath, Strin serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -520,9 +508,7 @@ public ServiceResponse getLocalPathItemQueryNull(String localStringPath, S if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); return getLocalPathItemQueryNullDelegate(call.execute()); } @@ -551,9 +537,7 @@ public ServiceCall getLocalPathItemQueryNullAsync(String localStringPath, String serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - final String localStringQuery = null; - final String pathItemStringQuery = null; - Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); + Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java index 47bd29d144dd3..1e189f1ff4c6b 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java @@ -299,8 +299,7 @@ private ServiceResponse getBooleanFalseDelegate(Response res * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getBooleanNull() throws ErrorException, IOException { - final Boolean boolQuery = null; - Call call = service.getBooleanNull(boolQuery); + Call call = service.getBooleanNull(null); return getBooleanNullDelegate(call.execute()); } @@ -315,8 +314,7 @@ public ServiceCall getBooleanNullAsync(final ServiceCallback serviceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Boolean boolQuery = null; - Call call = service.getBooleanNull(boolQuery); + Call call = service.getBooleanNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -480,8 +478,7 @@ private ServiceResponse getIntNegativeOneMillionDelegate(Response getIntNull() throws ErrorException, IOException { - final Integer intQuery = null; - Call call = service.getIntNull(intQuery); + Call call = service.getIntNull(null); return getIntNullDelegate(call.execute()); } @@ -496,8 +493,7 @@ public ServiceCall getIntNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Integer intQuery = null; - Call call = service.getIntNull(intQuery); + Call call = service.getIntNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -661,8 +657,7 @@ private ServiceResponse getNegativeTenBillionDelegate(Response getLongNull() throws ErrorException, IOException { - final Long longQuery = null; - Call call = service.getLongNull(longQuery); + Call call = service.getLongNull(null); return getLongNullDelegate(call.execute()); } @@ -677,8 +672,7 @@ public ServiceCall getLongNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Long longQuery = null; - Call call = service.getLongNull(longQuery); + Call call = service.getLongNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -842,8 +836,7 @@ private ServiceResponse floatScientificNegativeDelegate(Response floatNull() throws ErrorException, IOException { - final Double floatQuery = null; - Call call = service.floatNull(floatQuery); + Call call = service.floatNull(null); return floatNullDelegate(call.execute()); } @@ -858,8 +851,7 @@ public ServiceCall floatNullAsync(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Double floatQuery = null; - Call call = service.floatNull(floatQuery); + Call call = service.floatNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1023,8 +1015,7 @@ private ServiceResponse doubleDecimalNegativeDelegate(Response doubleNull() throws ErrorException, IOException { - final Double doubleQuery = null; - Call call = service.doubleNull(doubleQuery); + Call call = service.doubleNull(null); return doubleNullDelegate(call.execute()); } @@ -1039,8 +1030,7 @@ public ServiceCall doubleNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final Double doubleQuery = null; - Call call = service.doubleNull(doubleQuery); + Call call = service.doubleNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1251,8 +1241,7 @@ private ServiceResponse stringEmptyDelegate(Response respons * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse stringNull() throws ErrorException, IOException { - final String stringQuery = null; - Call call = service.stringNull(stringQuery); + Call call = service.stringNull(null); return stringNullDelegate(call.execute()); } @@ -1267,8 +1256,7 @@ public ServiceCall stringNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final String stringQuery = null; - Call call = service.stringNull(stringQuery); + Call call = service.stringNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1338,8 +1326,7 @@ private ServiceResponse stringNullDelegate(Response response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumValid() throws ErrorException, IOException { - final UriColor enumQuery = null; - Call call = service.enumValid(enumQuery); + Call call = service.enumValid(null); return enumValidDelegate(call.execute()); } @@ -1354,8 +1341,7 @@ public ServiceCall enumValidAsync(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final UriColor enumQuery = null; - Call call = service.enumValid(enumQuery); + Call call = service.enumValid(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1425,8 +1411,7 @@ private ServiceResponse enumValidDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumNull() throws ErrorException, IOException { - final UriColor enumQuery = null; - Call call = service.enumNull(enumQuery); + Call call = service.enumNull(null); return enumNullDelegate(call.execute()); } @@ -1441,8 +1426,7 @@ public ServiceCall enumNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final UriColor enumQuery = null; - Call call = service.enumNull(enumQuery); + Call call = service.enumNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1512,9 +1496,7 @@ private ServiceResponse enumNullDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteMultiByte() throws ErrorException, IOException { - final byte[] byteQuery = new byte[0]; - String byteQueryConverted = Base64.encodeBase64String(byteQuery); - Call call = service.byteMultiByte(byteQueryConverted); + Call call = service.byteMultiByte(null); return byteMultiByteDelegate(call.execute()); } @@ -1529,9 +1511,7 @@ public ServiceCall byteMultiByteAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final byte[] byteQuery = new byte[0]; - String byteQueryConverted = Base64.encodeBase64String(byteQuery); - Call call = service.byteMultiByte(byteQueryConverted); + Call call = service.byteMultiByte(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1652,9 +1632,7 @@ private ServiceResponse byteEmptyDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteNull() throws ErrorException, IOException { - final byte[] byteQuery = new byte[0]; - String byteQueryConverted = Base64.encodeBase64String(byteQuery); - Call call = service.byteNull(byteQueryConverted); + Call call = service.byteNull(null); return byteNullDelegate(call.execute()); } @@ -1669,9 +1647,7 @@ public ServiceCall byteNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final byte[] byteQuery = new byte[0]; - String byteQueryConverted = Base64.encodeBase64String(byteQuery); - Call call = service.byteNull(byteQueryConverted); + Call call = service.byteNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1790,8 +1766,7 @@ private ServiceResponse dateValidDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateNull() throws ErrorException, IOException { - final LocalDate dateQuery = null; - Call call = service.dateNull(dateQuery); + Call call = service.dateNull(null); return dateNullDelegate(call.execute()); } @@ -1806,8 +1781,7 @@ public ServiceCall dateNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final LocalDate dateQuery = null; - Call call = service.dateNull(dateQuery); + Call call = service.dateNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1924,8 +1898,7 @@ private ServiceResponse dateTimeValidDelegate(Response respo * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateTimeNull() throws ErrorException, IOException { - final DateTime dateTimeQuery = null; - Call call = service.dateTimeNull(dateTimeQuery); + Call call = service.dateTimeNull(null); return dateTimeNullDelegate(call.execute()); } @@ -1940,8 +1913,7 @@ public ServiceCall dateTimeNullAsync(final ServiceCallback serviceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final DateTime dateTimeQuery = null; - Call call = service.dateTimeNull(dateTimeQuery); + Call call = service.dateTimeNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2011,9 +1983,7 @@ private ServiceResponse dateTimeNullDelegate(Response respon * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvValid() throws ErrorException, IOException { - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); - Call call = service.arrayStringCsvValid(arrayQueryConverted); + Call call = service.arrayStringCsvValid(null); return arrayStringCsvValidDelegate(call.execute()); } @@ -2028,9 +1998,7 @@ public ServiceCall arrayStringCsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); - Call call = service.arrayStringCsvValid(arrayQueryConverted); + Call call = service.arrayStringCsvValid(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2104,9 +2072,7 @@ private ServiceResponse arrayStringCsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvNull() throws ErrorException, IOException { - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); - Call call = service.arrayStringCsvNull(arrayQueryConverted); + Call call = service.arrayStringCsvNull(null); return arrayStringCsvNullDelegate(call.execute()); } @@ -2121,9 +2087,7 @@ public ServiceCall arrayStringCsvNullAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); - Call call = service.arrayStringCsvNull(arrayQueryConverted); + Call call = service.arrayStringCsvNull(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2197,9 +2161,7 @@ private ServiceResponse arrayStringCsvNullDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvEmpty() throws ErrorException, IOException { - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); - Call call = service.arrayStringCsvEmpty(arrayQueryConverted); + Call call = service.arrayStringCsvEmpty(null); return arrayStringCsvEmptyDelegate(call.execute()); } @@ -2214,9 +2176,7 @@ public ServiceCall arrayStringCsvEmptyAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); - Call call = service.arrayStringCsvEmpty(arrayQueryConverted); + Call call = service.arrayStringCsvEmpty(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2290,9 +2250,7 @@ private ServiceResponse arrayStringCsvEmptyDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringSsvValid() throws ErrorException, IOException { - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); - Call call = service.arrayStringSsvValid(arrayQueryConverted); + Call call = service.arrayStringSsvValid(null); return arrayStringSsvValidDelegate(call.execute()); } @@ -2307,9 +2265,7 @@ public ServiceCall arrayStringSsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); - Call call = service.arrayStringSsvValid(arrayQueryConverted); + Call call = service.arrayStringSsvValid(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2383,9 +2339,7 @@ private ServiceResponse arrayStringSsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringTsvValid() throws ErrorException, IOException { - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); - Call call = service.arrayStringTsvValid(arrayQueryConverted); + Call call = service.arrayStringTsvValid(null); return arrayStringTsvValidDelegate(call.execute()); } @@ -2400,9 +2354,7 @@ public ServiceCall arrayStringTsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); - Call call = service.arrayStringTsvValid(arrayQueryConverted); + Call call = service.arrayStringTsvValid(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2476,9 +2428,7 @@ private ServiceResponse arrayStringTsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringPipesValid() throws ErrorException, IOException { - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); - Call call = service.arrayStringPipesValid(arrayQueryConverted); + Call call = service.arrayStringPipesValid(null); return arrayStringPipesValidDelegate(call.execute()); } @@ -2493,9 +2443,7 @@ public ServiceCall arrayStringPipesValidAsync(final ServiceCallback servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); - Call call = service.arrayStringPipesValid(arrayQueryConverted); + Call call = service.arrayStringPipesValid(null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java index e063d58222d8e..7a46a9788f3f4 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java @@ -270,8 +270,7 @@ public ServiceResponse validationOfBody(String resourceGroupName, int i if (this.getApiVersion() == null) { throw new IllegalArgumentException("Parameter this.getApiVersion() is required and cannot be null."); } - final Product body = null; - Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, body, this.getApiVersion()); + Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, null, this.getApiVersion()); return validationOfBodyDelegate(call.execute()); } @@ -300,8 +299,7 @@ public ServiceCall validationOfBodyAsync(String resourceGroupName, int id, final serviceCallback.failure(new IllegalArgumentException("Parameter this.getApiVersion() is required and cannot be null.")); return null; } - final Product body = null; - Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, body, this.getApiVersion()); + Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, null, this.getApiVersion()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -443,8 +441,7 @@ private ServiceResponse getWithConstantInPathDelegate(Response postWithConstantInBody() throws ServiceException, IOException { final String constantParam = "constant"; - final Product body = null; - Call call = service.postWithConstantInBody(constantParam, body); + Call call = service.postWithConstantInBody(constantParam, null); return postWithConstantInBodyDelegate(call.execute()); } @@ -459,8 +456,7 @@ public ServiceCall postWithConstantInBodyAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final String constantParam = "constant"; - final Product body = null; - Call call = service.postWithConstantInBody(constantParam, body); + Call call = service.postWithConstantInBody(constantParam, null); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index ff3c8740dd115..38d0bfd70ed8a 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -178,6 +178,28 @@ public string MethodParameterInvocation } } + public string MethodRequiredParameterInvocation + { + get + { + List invocations = new List(); + foreach (var parameter in LocalParameters) + { + if (parameter.IsRequired) + { + invocations.Add(parameter.Name); + } + else + { + invocations.Add("null"); + } + } + + var declaration = string.Join(", ", invocations); + return declaration; + } + } + public string MethodParameterApiInvocation { get @@ -193,12 +215,51 @@ public string MethodParameterApiInvocation } } + public string MethodRequiredParameterApiInvocation + { + get + { + List invocations = new List(); + foreach (var parameter in OrderedRetrofitParameters) + { + if (parameter.IsRequired) + { + invocations.Add(parameter.WireName); + } + else + { + invocations.Add(parameter.WireType.DefaultValue); + } + } + + var declaration = string.Join(", ", invocations); + return declaration; + } + } + public string ParameterConversion { get { IndentedStringBuilder builder = new IndentedStringBuilder(); - foreach (var p in RetrofitParameters) { + foreach (var p in RetrofitParameters) + { + if (p.NeedsConversion) + { + builder.Append(p.ConvertToWireType(p.Name, ClientReference)); + } + } + return builder.ToString(); + } + } + + public string RequiredParameterConversion + { + get + { + IndentedStringBuilder builder = new IndentedStringBuilder(); + foreach (var p in RetrofitParameters.Where(p => p.IsRequired)) + { if (p.NeedsConversion) { builder.Append(p.ConvertToWireType(p.Name, ClientReference)); @@ -212,13 +273,18 @@ public string ParameterConversion /// Generates input mapping code block. /// /// - public virtual string BuildInputMappings() + public virtual string BuildInputMappings(bool filterRequired = false) { var builder = new IndentedStringBuilder(); - foreach (var transformation in InputParameterTransformation) + var transformations = InputParameterTransformation; + if (filterRequired) + { + transformations = transformations.Where(t => t.OutputParameter.IsRequired).ToList(); + } + foreach (var transformation in transformations) { var nullCheck = BuildNullCheckExpression(transformation); - bool conditionalAssignment = !string.IsNullOrEmpty(nullCheck) && !transformation.OutputParameter.IsRequired; + bool conditionalAssignment = !string.IsNullOrEmpty(nullCheck) && !transformation.OutputParameter.IsRequired && !filterRequired; if (conditionalAssignment) { builder.AppendLine("{0} {1} = null;", @@ -236,7 +302,12 @@ public virtual string BuildInputMappings() transformation.OutputParameter.Type.Name); } - foreach (var mapping in transformation.ParameterMappings) + var mappings = transformation.ParameterMappings; + if (filterRequired) + { + mappings = mappings.Where(m => m.InputParameter.IsRequired).ToList(); + } + foreach (var mapping in mappings) { builder.AppendLine("{0}{1}{2};", !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? @@ -395,6 +466,20 @@ public virtual string MethodParameterInvocationWithCallback } } + public virtual string MethodRequiredParameterInvocationWithCallback + { + get + { + var parameters = MethodRequiredParameterInvocation; + if (!parameters.IsNullOrEmpty()) + { + parameters += ", "; + } + parameters += "serviceCallback"; + return parameters; + } + } + /// /// Get the parameters that are actually method parameters in the order they appear in the method signature /// exclude global parameters @@ -519,23 +604,20 @@ public virtual string RuntimeBasePackage } } - public virtual string ResponseGeneration + public virtual string ResponseGeneration(bool filterRequired = false) { - get + if (ReturnTypeModel.NeedsConversion) { - if (ReturnTypeModel.NeedsConversion) - { - IndentedStringBuilder builder= new IndentedStringBuilder(); - builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());", - ReturnTypeModel.GenericBodyWireTypeString, this.Name.ToCamelCase()); - builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType.Name) - .AppendLine("if (response.getBody() != null) {") - .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("response.getBody()", "body")) - .Outdent().AppendLine("}"); - return builder.ToString(); - } - return ""; + IndentedStringBuilder builder= new IndentedStringBuilder(); + builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());", + ReturnTypeModel.GenericBodyWireTypeString, this.Name.ToCamelCase()); + builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType.Name) + .AppendLine("if (response.getBody() != null) {") + .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("response.getBody()", "body")) + .Outdent().AppendLine("}"); + return builder.ToString(); } + return ""; } public virtual string ReturnValue @@ -550,23 +632,20 @@ public virtual string ReturnValue } } - public virtual string SuccessCallback + public virtual string SuccessCallback(bool filterRequired = false) { - get + if (ReturnTypeModel.NeedsConversion) { - if (ReturnTypeModel.NeedsConversion) - { - IndentedStringBuilder builder = new IndentedStringBuilder(); - builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeModel.GenericBodyWireTypeString, this.Name); - builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) - .AppendLine("if (result.getBody() != null) {") - .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("result.getBody()", "body")) - .Outdent().AppendLine("}"); - builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", ReturnTypeModel.GenericBodyClientTypeString); - return builder.ToString(); - } - return string.Format(CultureInfo.InvariantCulture, "serviceCallback.success({0}Delegate(response));", this.Name); + IndentedStringBuilder builder = new IndentedStringBuilder(); + builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeModel.GenericBodyWireTypeString, this.Name); + builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) + .AppendLine("if (result.getBody() != null) {") + .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("result.getBody()", "body")) + .Outdent().AppendLine("}"); + builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", ReturnTypeModel.GenericBodyClientTypeString); + return builder.ToString(); } + return string.Format(CultureInfo.InvariantCulture, "serviceCallback.success({0}Delegate(response));", this.Name); } public virtual string ServiceCallConstruction diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index 561ca9fc428dd..68770ed199c52 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -47,17 +47,13 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth } @foreach (ParameterModel parameter in Model.LocalParameters) { - if (!parameter.IsRequired) - { -@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.ClientType.DefaultValue); - } if (parameter.IsConstant) { @: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() + @Model.BuildInputMappings(true) @if (Model.ServiceClient.Extensions.ContainsKey(Microsoft.Rest.Generator.Extensions.ParameterizedHostExtension)) { @@ -66,9 +62,9 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } - @Model.ParameterConversion - Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); - @Model.ResponseGeneration + @Model.RequiredParameterConversion + Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation); + @Model.ResponseGeneration(true) return @Model.ReturnValue; } @EmptyLine @@ -108,16 +104,12 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @foreach (ParameterModel parameter in Model.LocalParameters) { - if (!parameter.IsRequired) - { -@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.ClientType.DefaultValue); - } if (parameter.IsConstant) { @: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() + @Model.BuildInputMappings(true) @if (Model.ServiceClient.Extensions.ContainsKey(Microsoft.Rest.Generator.Extensions.ParameterizedHostExtension)) { @@ -126,14 +118,14 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } - @Model.ParameterConversion - Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); + @Model.RequiredParameterConversion + Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation); @Model.ServiceCallConstruction call.enqueue(new @Model.InternalCallback<@(Model.ReturnTypeModel.ClientCallbackTypeString)>(serviceCallback) { @@Override public void onResponse(Call<@Model.CallType> call, Response<@Model.CallType> response) { try { - @Model.SuccessCallback + @Model.SuccessCallback(true) } catch (@Model.OperationExceptionTypeString | IOException exception) { serviceCallback.failure(exception); } @@ -200,7 +192,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host } @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); - @Model.ResponseGeneration + @Model.ResponseGeneration() return @Model.ReturnValue; } @EmptyLine @@ -261,7 +253,7 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @@Override public void onResponse(Call<@Model.CallType> call, Response<@Model.CallType> response) { try { - @Model.SuccessCallback + @Model.SuccessCallback() } catch (@Model.OperationExceptionTypeString | IOException exception) { serviceCallback.failure(exception); } From 8ab297ffaaa55ee7fcc7dde239cfa9e33da8cf07 Mon Sep 17 00:00:00 2001 From: tbombach Date: Tue, 29 Mar 2016 22:53:53 -0700 Subject: [PATCH 60/99] Fixing merge conflict for renaming base64url type in Java --- AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs index 892c4abc0b28d..14c9011cc8690 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs @@ -143,6 +143,10 @@ private void Initialize(PrimaryType primaryType) { Name = "void"; } + else if (primaryType.Type == KnownPrimaryType.Base64Url) + { + Name = "String"; + } else if (primaryType.Type == KnownPrimaryType.Boolean) { Name = "boolean"; From e941db631a1f41c962c3b059f6c2e38dd7667169 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 30 Mar 2016 10:53:22 -0700 Subject: [PATCH 61/99] bring variable declarations back --- .../ParameterGroupingOperationsImpl.java | 36 ++- ...RestResourceFlatteningTestServiceImpl.java | 18 +- .../ApiVersionLocalOperationsImpl.java | 6 +- .../azurespecials/OdataOperationsImpl.java | 10 +- .../SkipUrlEncodingOperationsImpl.java | 6 +- .../fixtures/lro/LRORetrysOperationsImpl.java | 40 +-- .../fixtures/lro/LROSADsOperationsImpl.java | 170 +++++++------ .../lro/LROsCustomHeaderOperationsImpl.java | 40 +-- .../java/fixtures/lro/LROsOperationsImpl.java | 230 +++++++++++------- .../fixtures/paging/PagingOperationsImpl.java | 46 +++- .../Templates/AzureMethodTemplate.cshtml | 8 +- .../bodystring/StringOperationsImpl.java | 6 +- .../fixtures/header/HeaderOperationsImpl.java | 18 +- .../http/HttpClientFailureOperationsImpl.java | 78 ++++-- .../http/HttpRedirectsOperationsImpl.java | 42 ++-- .../http/HttpRetryOperationsImpl.java | 36 ++- .../http/HttpServerFailureOperationsImpl.java | 12 +- .../http/HttpSuccessOperationsImpl.java | 84 ++++--- ...RestResourceFlatteningTestServiceImpl.java | 36 ++- .../ExplicitOperationsImpl.java | 66 +++-- .../ImplicitOperationsImpl.java | 18 +- .../fixtures/url/PathItemsOperationsImpl.java | 32 ++- .../fixtures/url/QueriesOperationsImpl.java | 108 +++++--- .../AutoRestValidationTestImpl.java | 12 +- .../TemplateModels/MethodTemplateModel.cs | 44 ++-- .../Java/Java/Templates/MethodTemplate.cshtml | 8 + .../Java/TypeModels/CompositeTypeModel.cs | 7 +- .../Java/TypeModels/DictionaryTypeModel.cs | 7 +- .../Java/Java/TypeModels/EnumTypeModel.cs | 7 +- .../Java/Java/TypeModels/ITypeModel.cs | 4 +- .../Java/Java/TypeModels/PrimaryTypeModel.cs | 39 +-- .../Java/Java/TypeModels/SequenceTypeModel.cs | 7 +- 32 files changed, 815 insertions(+), 466 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java index cc9f7fc54c8f8..26385d6c09481 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java @@ -151,7 +151,10 @@ private ServiceResponse postRequiredDelegate(Response respon * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse postOptional() throws ErrorException, IOException { - Call call = service.postOptional(null, null, null); + final ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = null; + String customHeader = null; + Integer query = null; + Call call = service.postOptional(this.client.getAcceptLanguage(), customHeader, query); return postOptionalDelegate(call.execute()); } @@ -166,7 +169,10 @@ public ServiceCall postOptionalAsync(final ServiceCallback serviceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptional(null, null, null); + final ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = null; + String customHeader = null; + Integer query = null; + Call call = service.postOptional(this.client.getAcceptLanguage(), customHeader, query); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -254,7 +260,13 @@ private ServiceResponse postOptionalDelegate(Response respon * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse postMultiParamGroups() throws ErrorException, IOException { - Call call = service.postMultiParamGroups(null, null, null, null, null); + final FirstParameterGroup firstParameterGroup = null; + final ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = null; + String headerOne = null; + Integer queryOne = null; + String headerTwo = null; + Integer queryTwo = null; + Call call = service.postMultiParamGroups(this.client.getAcceptLanguage(), headerOne, queryOne, headerTwo, queryTwo); return postMultiParamGroupsDelegate(call.execute()); } @@ -269,7 +281,13 @@ public ServiceCall postMultiParamGroupsAsync(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postMultiParamGroups(null, null, null, null, null); + final FirstParameterGroup firstParameterGroup = null; + final ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = null; + String headerOne = null; + Integer queryOne = null; + String headerTwo = null; + Integer queryTwo = null; + Call call = service.postMultiParamGroups(this.client.getAcceptLanguage(), headerOne, queryOne, headerTwo, queryTwo); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -377,7 +395,10 @@ private ServiceResponse postMultiParamGroupsDelegate(Response postSharedParameterGroupObject() throws ErrorException, IOException { - Call call = service.postSharedParameterGroupObject(null, null, null); + final FirstParameterGroup firstParameterGroup = null; + String headerOne = null; + Integer queryOne = null; + Call call = service.postSharedParameterGroupObject(this.client.getAcceptLanguage(), headerOne, queryOne); return postSharedParameterGroupObjectDelegate(call.execute()); } @@ -392,7 +413,10 @@ public ServiceCall postSharedParameterGroupObjectAsync(final ServiceCallback call = service.postSharedParameterGroupObject(null, null, null); + final FirstParameterGroup firstParameterGroup = null; + String headerOne = null; + Integer queryOne = null; + Call call = service.postSharedParameterGroupObject(this.client.getAcceptLanguage(), headerOne, queryOne); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java index f2d42e20cf69d..ef682bf3f44be 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureresource/AutoRestResourceFlatteningTestServiceImpl.java @@ -254,7 +254,8 @@ interface AutoRestResourceFlatteningTestServiceService { * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putArray() throws ErrorException, IOException { - Call call = service.putArray(null, null); + final List resourceArray = null; + Call call = service.putArray(resourceArray, this.getAcceptLanguage()); return putArrayDelegate(call.execute()); } @@ -269,7 +270,8 @@ public ServiceCall putArrayAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putArray(null, null); + final List resourceArray = null; + Call call = service.putArray(resourceArray, this.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -386,7 +388,8 @@ private ServiceResponse> getArrayDelegate(Response putDictionary() throws ErrorException, IOException { - Call call = service.putDictionary(null, null); + final Map resourceDictionary = null; + Call call = service.putDictionary(resourceDictionary, this.getAcceptLanguage()); return putDictionaryDelegate(call.execute()); } @@ -401,7 +404,8 @@ public ServiceCall putDictionaryAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putDictionary(null, null); + final Map resourceDictionary = null; + Call call = service.putDictionary(resourceDictionary, this.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -518,7 +522,8 @@ private ServiceResponse> getDictionaryDelegate(Res * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putResourceCollection() throws ErrorException, IOException { - Call call = service.putResourceCollection(null, null); + final ResourceCollection resourceComplexObject = null; + Call call = service.putResourceCollection(resourceComplexObject, this.getAcceptLanguage()); return putResourceCollectionDelegate(call.execute()); } @@ -533,7 +538,8 @@ public ServiceCall putResourceCollectionAsync(final ServiceCallback servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putResourceCollection(null, null); + final ResourceCollection resourceComplexObject = null; + Call call = service.putResourceCollection(resourceComplexObject, this.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java index 6022d91bac001..fd1bad46b33d2 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/ApiVersionLocalOperationsImpl.java @@ -126,7 +126,8 @@ private ServiceResponse getMethodLocalValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getMethodLocalNull() throws ErrorException, IOException { - Call call = service.getMethodLocalNull(null, null); + final String apiVersion = null; + Call call = service.getMethodLocalNull(apiVersion, this.client.getAcceptLanguage()); return getMethodLocalNullDelegate(call.execute()); } @@ -141,7 +142,8 @@ public ServiceCall getMethodLocalNullAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.getMethodLocalNull(null, null); + final String apiVersion = null; + Call call = service.getMethodLocalNull(apiVersion, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java index 2282166c91803..75777653172cf 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java @@ -69,7 +69,10 @@ interface OdataService { * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getWithFilter() throws ErrorException, IOException { - Call call = service.getWithFilter(null, null, null, null); + final OdataFilter filter = null; + final Integer top = null; + final String orderby = null; + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); return getWithFilterDelegate(call.execute()); } @@ -84,7 +87,10 @@ public ServiceCall getWithFilterAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.getWithFilter(null, null, null, null); + final OdataFilter filter = null; + final Integer top = null; + final String orderby = null; + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java index 7512746ef41c0..20d997c5006be 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/SkipUrlEncodingOperationsImpl.java @@ -304,7 +304,8 @@ private ServiceResponse getMethodQueryValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getMethodQueryNull() throws ErrorException, IOException { - Call call = service.getMethodQueryNull(null, null); + final String q1 = null; + Call call = service.getMethodQueryNull(q1, this.client.getAcceptLanguage()); return getMethodQueryNullDelegate(call.execute()); } @@ -319,7 +320,8 @@ public ServiceCall getMethodQueryNullAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.getMethodQueryNull(null, null); + final String q1 = null; + Call call = service.getMethodQueryNull(q1, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java index d3a75886e7967..7dc45ef9871d4 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LRORetrysOperationsImpl.java @@ -133,7 +133,7 @@ interface LRORetrysService { */ public ServiceResponse put201CreatingSucceeded200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingSucceeded200(null, null).execute(); + Response result = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -149,7 +149,7 @@ public ServiceCall put201CreatingSucceeded200Async(final ServiceCallback call = service.put201CreatingSucceeded200(null, null); + Call call = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -214,7 +214,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingSucceeded200() throws CloudException, IOException { - Call call = service.beginPut201CreatingSucceeded200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); return beginPut201CreatingSucceeded200Delegate(call.execute()); } @@ -229,7 +230,8 @@ public ServiceCall beginPut201CreatingSucceeded200Async(final ServiceCallback call = service.beginPut201CreatingSucceeded200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -304,7 +306,7 @@ private ServiceResponse beginPut201CreatingSucceeded200Delegate(Respons */ public ServiceResponseWithHeaders putAsyncRelativeRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetrySucceeded(null, null).execute(); + Response result = service.putAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LRORetrysPutAsyncRelativeRetrySucceededHeaders.class); } @@ -320,7 +322,7 @@ public ServiceCall putAsyncRelativeRetrySucceededAsync(final ServiceCallback call = service.putAsyncRelativeRetrySucceeded(null, null); + Call call = service.putAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -385,7 +387,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPutAsyncRelativeRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPutAsyncRelativeRetrySucceededDelegate(call.execute()); } @@ -400,7 +403,8 @@ public ServiceCall beginPutAsyncRelativeRetrySucceededAsync(final ServiceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutAsyncRelativeRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -727,7 +731,7 @@ private ServiceResponseWithHeaders post202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202Retry200(null, null).execute(); + Response result = service.post202Retry200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LRORetrysPost202Retry200Headers.class); } @@ -743,7 +747,7 @@ public ServiceCall post202Retry200Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202Retry200(null, null); + Call call = service.post202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -808,7 +812,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202Retry200() throws CloudException, IOException { - Call call = service.beginPost202Retry200(null, null); + final Product product = null; + Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); return beginPost202Retry200Delegate(call.execute()); } @@ -823,7 +828,8 @@ public ServiceCall beginPost202Retry200Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPost202Retry200(null, null); + final Product product = null; + Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -897,7 +903,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRelativeRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetrySucceeded(null, null).execute(); + Response result = service.postAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LRORetrysPostAsyncRelativeRetrySucceededHeaders.class); } @@ -913,7 +919,7 @@ public ServiceCall postAsyncRelativeRetrySucceededAsync(final ServiceCallback call = service.postAsyncRelativeRetrySucceeded(null, null); + Call call = service.postAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -978,7 +984,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPostAsyncRelativeRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPostAsyncRelativeRetrySucceededDelegate(call.execute()); } @@ -993,7 +1000,8 @@ public ServiceCall beginPostAsyncRelativeRetrySucceededAsync(final ServiceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostAsyncRelativeRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java index 952f8bdccd5a4..a00b4293ab132 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 @@ -291,7 +291,7 @@ interface LROSADsService { */ public ServiceResponse putNonRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putNonRetry400(null, null).execute(); + Response result = service.putNonRetry400(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -307,7 +307,7 @@ public ServiceCall putNonRetry400Async(final ServiceCallback serviceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putNonRetry400(null, null); + Call call = service.putNonRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -372,7 +372,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutNonRetry400() throws CloudException, IOException { - Call call = service.beginPutNonRetry400(null, null); + final Product product = null; + Call call = service.beginPutNonRetry400(product, this.client.getAcceptLanguage()); return beginPutNonRetry400Delegate(call.execute()); } @@ -387,7 +388,8 @@ public ServiceCall beginPutNonRetry400Async(final ServiceCallback servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutNonRetry400(null, null); + final Product product = null; + Call call = service.beginPutNonRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -462,7 +464,7 @@ private ServiceResponse beginPutNonRetry400Delegate(Response putNonRetry201Creating400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putNonRetry201Creating400(null, null).execute(); + Response result = service.putNonRetry201Creating400(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -478,7 +480,7 @@ public ServiceCall putNonRetry201Creating400Async(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putNonRetry201Creating400(null, null); + Call call = service.putNonRetry201Creating400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -543,7 +545,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutNonRetry201Creating400() throws CloudException, IOException { - Call call = service.beginPutNonRetry201Creating400(null, null); + final Product product = null; + Call call = service.beginPutNonRetry201Creating400(product, this.client.getAcceptLanguage()); return beginPutNonRetry201Creating400Delegate(call.execute()); } @@ -558,7 +561,8 @@ public ServiceCall beginPutNonRetry201Creating400Async(final ServiceCallback call = service.beginPutNonRetry201Creating400(null, null); + final Product product = null; + Call call = service.beginPutNonRetry201Creating400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -633,7 +637,7 @@ private ServiceResponse beginPutNonRetry201Creating400Delegate(Response */ public ServiceResponseWithHeaders putAsyncRelativeRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetry400(null, null).execute(); + Response result = service.putAsyncRelativeRetry400(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetry400Headers.class); } @@ -649,7 +653,7 @@ public ServiceCall putAsyncRelativeRetry400Async(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetry400(null, null); + Call call = service.putAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -714,7 +718,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetry400() throws CloudException, IOException { - Call call = service.beginPutAsyncRelativeRetry400(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); return beginPutAsyncRelativeRetry400Delegate(call.execute()); } @@ -729,7 +734,8 @@ public ServiceCall beginPutAsyncRelativeRetry400Async(final ServiceCallback call = service.beginPutAsyncRelativeRetry400(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1055,7 +1061,7 @@ private ServiceResponseWithHeaders postNonRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postNonRetry400(null, null).execute(); + Response result = service.postNonRetry400(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostNonRetry400Headers.class); } @@ -1071,7 +1077,7 @@ public ServiceCall postNonRetry400Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postNonRetry400(null, null); + Call call = service.postNonRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1136,7 +1142,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostNonRetry400() throws CloudException, IOException { - Call call = service.beginPostNonRetry400(null, null); + final Product product = null; + Call call = service.beginPostNonRetry400(product, this.client.getAcceptLanguage()); return beginPostNonRetry400Delegate(call.execute()); } @@ -1151,7 +1158,8 @@ public ServiceCall beginPostNonRetry400Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostNonRetry400(null, null); + final Product product = null; + Call call = service.beginPostNonRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1225,7 +1233,7 @@ private ServiceResponseWithHeaders beginPos */ public ServiceResponseWithHeaders post202NonRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202NonRetry400(null, null).execute(); + Response result = service.post202NonRetry400(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPost202NonRetry400Headers.class); } @@ -1241,7 +1249,7 @@ public ServiceCall post202NonRetry400Async(final ServiceCallback serviceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202NonRetry400(null, null); + Call call = service.post202NonRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1306,7 +1314,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202NonRetry400() throws CloudException, IOException { - Call call = service.beginPost202NonRetry400(null, null); + final Product product = null; + Call call = service.beginPost202NonRetry400(product, this.client.getAcceptLanguage()); return beginPost202NonRetry400Delegate(call.execute()); } @@ -1321,7 +1330,8 @@ public ServiceCall beginPost202NonRetry400Async(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPost202NonRetry400(null, null); + final Product product = null; + Call call = service.beginPost202NonRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1395,7 +1405,7 @@ private ServiceResponseWithHeaders begin */ public ServiceResponseWithHeaders postAsyncRelativeRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetry400(null, null).execute(); + Response result = service.postAsyncRelativeRetry400(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetry400Headers.class); } @@ -1411,7 +1421,7 @@ public ServiceCall postAsyncRelativeRetry400Async(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRelativeRetry400(null, null); + Call call = service.postAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1476,7 +1486,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetry400() throws CloudException, IOException { - Call call = service.beginPostAsyncRelativeRetry400(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); return beginPostAsyncRelativeRetry400Delegate(call.execute()); } @@ -1491,7 +1502,8 @@ public ServiceCall beginPostAsyncRelativeRetry400Async(final ServiceCallback call = service.beginPostAsyncRelativeRetry400(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetry400(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1565,7 +1577,7 @@ private ServiceResponseWithHeaders putError201NoProvisioningStatePayload() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putError201NoProvisioningStatePayload(null, null).execute(); + Response result = service.putError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1581,7 +1593,7 @@ public ServiceCall putError201NoProvisioningStatePayloadAsync(final ServiceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putError201NoProvisioningStatePayload(null, null); + Call call = service.putError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1646,7 +1658,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutError201NoProvisioningStatePayload() throws CloudException, IOException { - Call call = service.beginPutError201NoProvisioningStatePayload(null, null); + final Product product = null; + Call call = service.beginPutError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()); return beginPutError201NoProvisioningStatePayloadDelegate(call.execute()); } @@ -1661,7 +1674,8 @@ public ServiceCall beginPutError201NoProvisioningStatePayloadAsync(final Service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutError201NoProvisioningStatePayload(null, null); + final Product product = null; + Call call = service.beginPutError201NoProvisioningStatePayload(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1736,7 +1750,7 @@ private ServiceResponse beginPutError201NoProvisioningStatePayloadDeleg */ public ServiceResponseWithHeaders putAsyncRelativeRetryNoStatus() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryNoStatus(null, null).execute(); + Response result = service.putAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryNoStatusHeaders.class); } @@ -1752,7 +1766,7 @@ public ServiceCall putAsyncRelativeRetryNoStatusAsync(final ServiceCallback call = service.putAsyncRelativeRetryNoStatus(null, null); + Call call = service.putAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1817,7 +1831,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryNoStatus() throws CloudException, IOException { - Call call = service.beginPutAsyncRelativeRetryNoStatus(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()); return beginPutAsyncRelativeRetryNoStatusDelegate(call.execute()); } @@ -1832,7 +1847,8 @@ public ServiceCall beginPutAsyncRelativeRetryNoStatusAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutAsyncRelativeRetryNoStatus(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryNoStatus(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1906,7 +1922,7 @@ private ServiceResponseWithHeaders putAsyncRelativeRetryNoStatusPayload() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryNoStatusPayload(null, null).execute(); + Response result = service.putAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryNoStatusPayloadHeaders.class); } @@ -1922,7 +1938,7 @@ public ServiceCall putAsyncRelativeRetryNoStatusPayloadAsync(final ServiceCallba throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetryNoStatusPayload(null, null); + Call call = service.putAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1987,7 +2003,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryNoStatusPayload() throws CloudException, IOException { - Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()); return beginPutAsyncRelativeRetryNoStatusPayloadDelegate(call.execute()); } @@ -2002,7 +2019,8 @@ public ServiceCall beginPutAsyncRelativeRetryNoStatusPayloadAsync(final ServiceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryNoStatusPayload(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2244,7 +2262,7 @@ private ServiceResponseWithHeaders post202NoLocation() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202NoLocation(null, null).execute(); + Response result = service.post202NoLocation(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPost202NoLocationHeaders.class); } @@ -2260,7 +2278,7 @@ public ServiceCall post202NoLocationAsync(final ServiceCallback serviceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202NoLocation(null, null); + Call call = service.post202NoLocation(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2325,7 +2343,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202NoLocation() throws CloudException, IOException { - Call call = service.beginPost202NoLocation(null, null); + final Product product = null; + Call call = service.beginPost202NoLocation(product, this.client.getAcceptLanguage()); return beginPost202NoLocationDelegate(call.execute()); } @@ -2340,7 +2359,8 @@ public ServiceCall beginPost202NoLocationAsync(final ServiceCallback servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPost202NoLocation(null, null); + final Product product = null; + Call call = service.beginPost202NoLocation(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2414,7 +2434,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRelativeRetryNoPayload() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetryNoPayload(null, null).execute(); + Response result = service.postAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetryNoPayloadHeaders.class); } @@ -2430,7 +2450,7 @@ public ServiceCall postAsyncRelativeRetryNoPayloadAsync(final ServiceCallback call = service.postAsyncRelativeRetryNoPayload(null, null); + Call call = service.postAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2495,7 +2515,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetryNoPayload() throws CloudException, IOException { - Call call = service.beginPostAsyncRelativeRetryNoPayload(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()); return beginPostAsyncRelativeRetryNoPayloadDelegate(call.execute()); } @@ -2510,7 +2531,8 @@ public ServiceCall beginPostAsyncRelativeRetryNoPayloadAsync(final ServiceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostAsyncRelativeRetryNoPayload(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetryNoPayload(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2584,7 +2606,7 @@ private ServiceResponseWithHeaders put200InvalidJson() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200InvalidJson(null, null).execute(); + Response result = service.put200InvalidJson(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2600,7 +2622,7 @@ public ServiceCall put200InvalidJsonAsync(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200InvalidJson(null, null); + Call call = service.put200InvalidJson(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2665,7 +2687,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200InvalidJson() throws CloudException, IOException { - Call call = service.beginPut200InvalidJson(null, null); + final Product product = null; + Call call = service.beginPut200InvalidJson(product, this.client.getAcceptLanguage()); return beginPut200InvalidJsonDelegate(call.execute()); } @@ -2680,7 +2703,8 @@ public ServiceCall beginPut200InvalidJsonAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPut200InvalidJson(null, null); + final Product product = null; + Call call = service.beginPut200InvalidJson(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2755,7 +2779,7 @@ private ServiceResponse beginPut200InvalidJsonDelegate(Response putAsyncRelativeRetryInvalidHeader() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryInvalidHeader(null, null).execute(); + Response result = service.putAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryInvalidHeaderHeaders.class); } @@ -2771,7 +2795,7 @@ public ServiceCall putAsyncRelativeRetryInvalidHeaderAsync(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetryInvalidHeader(null, null); + Call call = service.putAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2836,7 +2860,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryInvalidHeader() throws CloudException, IOException { - Call call = service.beginPutAsyncRelativeRetryInvalidHeader(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); return beginPutAsyncRelativeRetryInvalidHeaderDelegate(call.execute()); } @@ -2851,7 +2876,8 @@ public ServiceCall beginPutAsyncRelativeRetryInvalidHeaderAsync(final ServiceCal if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutAsyncRelativeRetryInvalidHeader(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2925,7 +2951,7 @@ private ServiceResponseWithHeaders putAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRelativeRetryInvalidJsonPolling(null, null).execute(); + Response result = service.putAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPutAsyncRelativeRetryInvalidJsonPollingHeaders.class); } @@ -2941,7 +2967,7 @@ public ServiceCall putAsyncRelativeRetryInvalidJsonPollingAsync(final ServiceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRelativeRetryInvalidJsonPolling(null, null); + Call call = service.putAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3006,7 +3032,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException { - Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); return beginPutAsyncRelativeRetryInvalidJsonPollingDelegate(call.execute()); } @@ -3021,7 +3048,8 @@ public ServiceCall beginPutAsyncRelativeRetryInvalidJsonPollingAsync(final Servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(null, null); + final Product product = null; + Call call = service.beginPutAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3347,7 +3375,7 @@ private ServiceResponseWithHeaders post202RetryInvalidHeader() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202RetryInvalidHeader(null, null).execute(); + Response result = service.post202RetryInvalidHeader(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPost202RetryInvalidHeaderHeaders.class); } @@ -3363,7 +3391,7 @@ public ServiceCall post202RetryInvalidHeaderAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202RetryInvalidHeader(null, null); + Call call = service.post202RetryInvalidHeader(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3428,7 +3456,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202RetryInvalidHeader() throws CloudException, IOException { - Call call = service.beginPost202RetryInvalidHeader(null, null); + final Product product = null; + Call call = service.beginPost202RetryInvalidHeader(product, this.client.getAcceptLanguage()); return beginPost202RetryInvalidHeaderDelegate(call.execute()); } @@ -3443,7 +3472,8 @@ public ServiceCall beginPost202RetryInvalidHeaderAsync(final ServiceCallback call = service.beginPost202RetryInvalidHeader(null, null); + final Product product = null; + Call call = service.beginPost202RetryInvalidHeader(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3517,7 +3547,7 @@ private ServiceResponseWithHeaders postAsyncRelativeRetryInvalidHeader() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetryInvalidHeader(null, null).execute(); + Response result = service.postAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetryInvalidHeaderHeaders.class); } @@ -3533,7 +3563,7 @@ public ServiceCall postAsyncRelativeRetryInvalidHeaderAsync(final ServiceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRelativeRetryInvalidHeader(null, null); + Call call = service.postAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3598,7 +3628,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetryInvalidHeader() throws CloudException, IOException { - Call call = service.beginPostAsyncRelativeRetryInvalidHeader(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); return beginPostAsyncRelativeRetryInvalidHeaderDelegate(call.execute()); } @@ -3613,7 +3644,8 @@ public ServiceCall beginPostAsyncRelativeRetryInvalidHeaderAsync(final ServiceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostAsyncRelativeRetryInvalidHeader(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetryInvalidHeader(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3687,7 +3719,7 @@ private ServiceResponseWithHeaders postAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRelativeRetryInvalidJsonPolling(null, null).execute(); + Response result = service.postAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROSADsPostAsyncRelativeRetryInvalidJsonPollingHeaders.class); } @@ -3703,7 +3735,7 @@ public ServiceCall postAsyncRelativeRetryInvalidJsonPollingAsync(final ServiceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRelativeRetryInvalidJsonPolling(null, null); + Call call = service.postAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3768,7 +3800,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRelativeRetryInvalidJsonPolling() throws CloudException, IOException { - Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); return beginPostAsyncRelativeRetryInvalidJsonPollingDelegate(call.execute()); } @@ -3783,7 +3816,8 @@ public ServiceCall beginPostAsyncRelativeRetryInvalidJsonPollingAsync(final Serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(null, null); + final Product product = null; + Call call = service.beginPostAsyncRelativeRetryInvalidJsonPolling(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java index ab6e8801e1615..d5d7fa473ed3e 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsCustomHeaderOperationsImpl.java @@ -105,7 +105,7 @@ interface LROsCustomHeaderService { */ public ServiceResponseWithHeaders putAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRetrySucceeded(null, null).execute(); + Response result = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsCustomHeaderPutAsyncRetrySucceededHeaders.class); } @@ -121,7 +121,7 @@ public ServiceCall putAsyncRetrySucceededAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRetrySucceeded(null, null); + Call call = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -186,7 +186,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPutAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPutAsyncRetrySucceededDelegate(call.execute()); } @@ -201,7 +202,8 @@ public ServiceCall beginPutAsyncRetrySucceededAsync(final ServiceCallback call = service.beginPutAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -275,7 +277,7 @@ private ServiceResponseWithHeaders put201CreatingSucceeded200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingSucceeded200(null, null).execute(); + Response result = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -291,7 +293,7 @@ public ServiceCall put201CreatingSucceeded200Async(final ServiceCallback call = service.put201CreatingSucceeded200(null, null); + Call call = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -356,7 +358,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingSucceeded200() throws CloudException, IOException { - Call call = service.beginPut201CreatingSucceeded200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); return beginPut201CreatingSucceeded200Delegate(call.execute()); } @@ -371,7 +374,8 @@ public ServiceCall beginPut201CreatingSucceeded200Async(final ServiceCallback call = service.beginPut201CreatingSucceeded200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -446,7 +450,7 @@ private ServiceResponse beginPut201CreatingSucceeded200Delegate(Respons */ public ServiceResponseWithHeaders post202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202Retry200(null, null).execute(); + Response result = service.post202Retry200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsCustomHeaderPost202Retry200Headers.class); } @@ -462,7 +466,7 @@ public ServiceCall post202Retry200Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202Retry200(null, null); + Call call = service.post202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -527,7 +531,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202Retry200() throws CloudException, IOException { - Call call = service.beginPost202Retry200(null, null); + final Product product = null; + Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); return beginPost202Retry200Delegate(call.execute()); } @@ -542,7 +547,8 @@ public ServiceCall beginPost202Retry200Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPost202Retry200(null, null); + final Product product = null; + Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -616,7 +622,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders postAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetrySucceeded(null, null).execute(); + Response result = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsCustomHeaderPostAsyncRetrySucceededHeaders.class); } @@ -632,7 +638,7 @@ public ServiceCall postAsyncRetrySucceededAsync(final ServiceCallback serv throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetrySucceeded(null, null); + Call call = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -697,7 +703,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPostAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPostAsyncRetrySucceededDelegate(call.execute()); } @@ -712,7 +719,8 @@ public ServiceCall beginPostAsyncRetrySucceededAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java index 61229851edae6..6d2e6b6124a47 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROsOperationsImpl.java @@ -384,7 +384,7 @@ interface LROsService { */ public ServiceResponse put200Succeeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200Succeeded(null, null).execute(); + Response result = service.put200Succeeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -400,7 +400,7 @@ public ServiceCall put200SucceededAsync(final ServiceCallback serviceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200Succeeded(null, null); + Call call = service.put200Succeeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -465,7 +465,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200Succeeded() throws CloudException, IOException { - Call call = service.beginPut200Succeeded(null, null); + final Product product = null; + Call call = service.beginPut200Succeeded(product, this.client.getAcceptLanguage()); return beginPut200SucceededDelegate(call.execute()); } @@ -480,7 +481,8 @@ public ServiceCall beginPut200SucceededAsync(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPut200Succeeded(null, null); + final Product product = null; + Call call = service.beginPut200Succeeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -555,7 +557,7 @@ private ServiceResponse beginPut200SucceededDelegate(Response put200SucceededNoState() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200SucceededNoState(null, null).execute(); + Response result = service.put200SucceededNoState(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -571,7 +573,7 @@ public ServiceCall put200SucceededNoStateAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200SucceededNoState(null, null); + Call call = service.put200SucceededNoState(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -636,7 +638,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200SucceededNoState() throws CloudException, IOException { - Call call = service.beginPut200SucceededNoState(null, null); + final Product product = null; + Call call = service.beginPut200SucceededNoState(product, this.client.getAcceptLanguage()); return beginPut200SucceededNoStateDelegate(call.execute()); } @@ -651,7 +654,8 @@ public ServiceCall beginPut200SucceededNoStateAsync(final ServiceCallback call = service.beginPut200SucceededNoState(null, null); + final Product product = null; + Call call = service.beginPut200SucceededNoState(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -725,7 +729,7 @@ private ServiceResponse beginPut200SucceededNoStateDelegate(Response put202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put202Retry200(null, null).execute(); + Response result = service.put202Retry200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -741,7 +745,7 @@ public ServiceCall put202Retry200Async(final ServiceCallback serviceCal throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put202Retry200(null, null); + Call call = service.put202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -806,7 +810,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut202Retry200() throws CloudException, IOException { - Call call = service.beginPut202Retry200(null, null); + final Product product = null; + Call call = service.beginPut202Retry200(product, this.client.getAcceptLanguage()); return beginPut202Retry200Delegate(call.execute()); } @@ -821,7 +826,8 @@ public ServiceCall beginPut202Retry200Async(final ServiceCallback servi if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPut202Retry200(null, null); + final Product product = null; + Call call = service.beginPut202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -895,7 +901,7 @@ private ServiceResponse beginPut202Retry200Delegate(Response put201CreatingSucceeded200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingSucceeded200(null, null).execute(); + Response result = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -911,7 +917,7 @@ public ServiceCall put201CreatingSucceeded200Async(final ServiceCallback call = service.put201CreatingSucceeded200(null, null); + Call call = service.put201CreatingSucceeded200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -976,7 +982,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingSucceeded200() throws CloudException, IOException { - Call call = service.beginPut201CreatingSucceeded200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); return beginPut201CreatingSucceeded200Delegate(call.execute()); } @@ -991,7 +998,8 @@ public ServiceCall beginPut201CreatingSucceeded200Async(final ServiceCallback call = service.beginPut201CreatingSucceeded200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingSucceeded200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1066,7 +1074,7 @@ private ServiceResponse beginPut201CreatingSucceeded200Delegate(Respons */ public ServiceResponse put200UpdatingSucceeded204() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200UpdatingSucceeded204(null, null).execute(); + Response result = service.put200UpdatingSucceeded204(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1082,7 +1090,7 @@ public ServiceCall put200UpdatingSucceeded204Async(final ServiceCallback call = service.put200UpdatingSucceeded204(null, null); + Call call = service.put200UpdatingSucceeded204(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1147,7 +1155,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200UpdatingSucceeded204() throws CloudException, IOException { - Call call = service.beginPut200UpdatingSucceeded204(null, null); + final Product product = null; + Call call = service.beginPut200UpdatingSucceeded204(product, this.client.getAcceptLanguage()); return beginPut200UpdatingSucceeded204Delegate(call.execute()); } @@ -1162,7 +1171,8 @@ public ServiceCall beginPut200UpdatingSucceeded204Async(final ServiceCallback call = service.beginPut200UpdatingSucceeded204(null, null); + final Product product = null; + Call call = service.beginPut200UpdatingSucceeded204(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1236,7 +1246,7 @@ private ServiceResponse beginPut200UpdatingSucceeded204Delegate(Respons */ public ServiceResponse put201CreatingFailed200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put201CreatingFailed200(null, null).execute(); + Response result = service.put201CreatingFailed200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1252,7 +1262,7 @@ public ServiceCall put201CreatingFailed200Async(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put201CreatingFailed200(null, null); + Call call = service.put201CreatingFailed200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1317,7 +1327,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut201CreatingFailed200() throws CloudException, IOException { - Call call = service.beginPut201CreatingFailed200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingFailed200(product, this.client.getAcceptLanguage()); return beginPut201CreatingFailed200Delegate(call.execute()); } @@ -1332,7 +1343,8 @@ public ServiceCall beginPut201CreatingFailed200Async(final ServiceCallback call = service.beginPut201CreatingFailed200(null, null); + final Product product = null; + Call call = service.beginPut201CreatingFailed200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1407,7 +1419,7 @@ private ServiceResponse beginPut201CreatingFailed200Delegate(Response put200Acceptedcanceled200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.put200Acceptedcanceled200(null, null).execute(); + Response result = service.put200Acceptedcanceled200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -1423,7 +1435,7 @@ public ServiceCall put200Acceptedcanceled200Async(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.put200Acceptedcanceled200(null, null); + Call call = service.put200Acceptedcanceled200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1488,7 +1500,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPut200Acceptedcanceled200() throws CloudException, IOException { - Call call = service.beginPut200Acceptedcanceled200(null, null); + final Product product = null; + Call call = service.beginPut200Acceptedcanceled200(product, this.client.getAcceptLanguage()); return beginPut200Acceptedcanceled200Delegate(call.execute()); } @@ -1503,7 +1516,8 @@ public ServiceCall beginPut200Acceptedcanceled200Async(final ServiceCallback call = service.beginPut200Acceptedcanceled200(null, null); + final Product product = null; + Call call = service.beginPut200Acceptedcanceled200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1577,7 +1591,7 @@ private ServiceResponse beginPut200Acceptedcanceled200Delegate(Response */ public ServiceResponseWithHeaders putNoHeaderInRetry() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putNoHeaderInRetry(null, null).execute(); + Response result = service.putNoHeaderInRetry(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutNoHeaderInRetryHeaders.class); } @@ -1593,7 +1607,7 @@ public ServiceCall putNoHeaderInRetryAsync(final ServiceCallback servic throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putNoHeaderInRetry(null, null); + Call call = service.putNoHeaderInRetry(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1658,7 +1672,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutNoHeaderInRetry() throws CloudException, IOException { - Call call = service.beginPutNoHeaderInRetry(null, null); + final Product product = null; + Call call = service.beginPutNoHeaderInRetry(product, this.client.getAcceptLanguage()); return beginPutNoHeaderInRetryDelegate(call.execute()); } @@ -1673,7 +1688,8 @@ public ServiceCall beginPutNoHeaderInRetryAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutNoHeaderInRetry(null, null); + final Product product = null; + Call call = service.beginPutNoHeaderInRetry(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1747,7 +1763,7 @@ private ServiceResponseWithHeaders begin */ public ServiceResponseWithHeaders putAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRetrySucceeded(null, null).execute(); + Response result = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncRetrySucceededHeaders.class); } @@ -1763,7 +1779,7 @@ public ServiceCall putAsyncRetrySucceededAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRetrySucceeded(null, null); + Call call = service.putAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1828,7 +1844,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPutAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPutAsyncRetrySucceededDelegate(call.execute()); } @@ -1843,7 +1860,8 @@ public ServiceCall beginPutAsyncRetrySucceededAsync(final ServiceCallback call = service.beginPutAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1917,7 +1935,7 @@ private ServiceResponseWithHeaders b */ public ServiceResponseWithHeaders putAsyncNoRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncNoRetrySucceeded(null, null).execute(); + Response result = service.putAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncNoRetrySucceededHeaders.class); } @@ -1933,7 +1951,7 @@ public ServiceCall putAsyncNoRetrySucceededAsync(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncNoRetrySucceeded(null, null); + Call call = service.putAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -1998,7 +2016,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncNoRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPutAsyncNoRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPutAsyncNoRetrySucceededDelegate(call.execute()); } @@ -2013,7 +2032,8 @@ public ServiceCall beginPutAsyncNoRetrySucceededAsync(final ServiceCallback call = service.beginPutAsyncNoRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPutAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2087,7 +2107,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders putAsyncRetryFailed() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncRetryFailed(null, null).execute(); + Response result = service.putAsyncRetryFailed(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncRetryFailedHeaders.class); } @@ -2103,7 +2123,7 @@ public ServiceCall putAsyncRetryFailedAsync(final ServiceCallback servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncRetryFailed(null, null); + Call call = service.putAsyncRetryFailed(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2168,7 +2188,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncRetryFailed() throws CloudException, IOException { - Call call = service.beginPutAsyncRetryFailed(null, null); + final Product product = null; + Call call = service.beginPutAsyncRetryFailed(product, this.client.getAcceptLanguage()); return beginPutAsyncRetryFailedDelegate(call.execute()); } @@ -2183,7 +2204,8 @@ public ServiceCall beginPutAsyncRetryFailedAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutAsyncRetryFailed(null, null); + final Product product = null; + Call call = service.beginPutAsyncRetryFailed(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2257,7 +2279,7 @@ private ServiceResponseWithHeaders begi */ public ServiceResponseWithHeaders putAsyncNoRetrycanceled() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncNoRetrycanceled(null, null).execute(); + Response result = service.putAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncNoRetrycanceledHeaders.class); } @@ -2273,7 +2295,7 @@ public ServiceCall putAsyncNoRetrycanceledAsync(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncNoRetrycanceled(null, null); + Call call = service.putAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2338,7 +2360,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncNoRetrycanceled() throws CloudException, IOException { - Call call = service.beginPutAsyncNoRetrycanceled(null, null); + final Product product = null; + Call call = service.beginPutAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()); return beginPutAsyncNoRetrycanceledDelegate(call.execute()); } @@ -2353,7 +2376,8 @@ public ServiceCall beginPutAsyncNoRetrycanceledAsync(final ServiceCallback call = service.beginPutAsyncNoRetrycanceled(null, null); + final Product product = null; + Call call = service.beginPutAsyncNoRetrycanceled(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2427,7 +2451,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders putAsyncNoHeaderInRetry() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.putAsyncNoHeaderInRetry(null, null).execute(); + Response result = service.putAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResultWithHeaders(result, new TypeToken() { }.getType(), LROsPutAsyncNoHeaderInRetryHeaders.class); } @@ -2443,7 +2467,7 @@ public ServiceCall putAsyncNoHeaderInRetryAsync(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.putAsyncNoHeaderInRetry(null, null); + Call call = service.putAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2508,7 +2532,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPutAsyncNoHeaderInRetry() throws CloudException, IOException { - Call call = service.beginPutAsyncNoHeaderInRetry(null, null); + final Product product = null; + Call call = service.beginPutAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()); return beginPutAsyncNoHeaderInRetryDelegate(call.execute()); } @@ -2523,7 +2548,8 @@ public ServiceCall beginPutAsyncNoHeaderInRetryAsync(final ServiceCallback call = service.beginPutAsyncNoHeaderInRetry(null, null); + final Product product = null; + Call call = service.beginPutAsyncNoHeaderInRetry(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2597,7 +2623,7 @@ private ServiceResponseWithHeaders */ public ServiceResponse putNonResource() throws CloudException, IOException, InterruptedException { final Sku sku = null; - Response result = service.putNonResource(null, null).execute(); + Response result = service.putNonResource(sku, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2613,7 +2639,7 @@ public ServiceCall putNonResourceAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Sku sku = null; - Call call = service.putNonResource(null, null); + Call call = service.putNonResource(sku, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2678,7 +2704,8 @@ public void onResponse(Call call, Response response) * @return the Sku object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutNonResource() throws CloudException, IOException { - Call call = service.beginPutNonResource(null, null); + final Sku sku = null; + Call call = service.beginPutNonResource(sku, this.client.getAcceptLanguage()); return beginPutNonResourceDelegate(call.execute()); } @@ -2693,7 +2720,8 @@ public ServiceCall beginPutNonResourceAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutNonResource(null, null); + final Sku sku = null; + Call call = service.beginPutNonResource(sku, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2767,7 +2795,7 @@ private ServiceResponse beginPutNonResourceDelegate(Response */ public ServiceResponse putAsyncNonResource() throws CloudException, IOException, InterruptedException { final Sku sku = null; - Response result = service.putAsyncNonResource(null, null).execute(); + Response result = service.putAsyncNonResource(sku, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2783,7 +2811,7 @@ public ServiceCall putAsyncNonResourceAsync(final ServiceCallback serviceCa throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Sku sku = null; - Call call = service.putAsyncNonResource(null, null); + Call call = service.putAsyncNonResource(sku, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -2848,7 +2876,8 @@ public void onResponse(Call call, Response response) * @return the Sku object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutAsyncNonResource() throws CloudException, IOException { - Call call = service.beginPutAsyncNonResource(null, null); + final Sku sku = null; + Call call = service.beginPutAsyncNonResource(sku, this.client.getAcceptLanguage()); return beginPutAsyncNonResourceDelegate(call.execute()); } @@ -2863,7 +2892,8 @@ public ServiceCall beginPutAsyncNonResourceAsync(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutAsyncNonResource(null, null); + final Sku sku = null; + Call call = service.beginPutAsyncNonResource(sku, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2937,7 +2967,7 @@ private ServiceResponse beginPutAsyncNonResourceDelegate(Response putSubResource() throws CloudException, IOException, InterruptedException { final SubProduct product = null; - Response result = service.putSubResource(null, null).execute(); + Response result = service.putSubResource(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -2953,7 +2983,7 @@ public ServiceCall putSubResourceAsync(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final SubProduct product = null; - Call call = service.putSubResource(null, null); + Call call = service.putSubResource(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3018,7 +3048,8 @@ public void onResponse(Call call, Response response) * @return the SubProduct object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutSubResource() throws CloudException, IOException { - Call call = service.beginPutSubResource(null, null); + final SubProduct product = null; + Call call = service.beginPutSubResource(product, this.client.getAcceptLanguage()); return beginPutSubResourceDelegate(call.execute()); } @@ -3033,7 +3064,8 @@ public ServiceCall beginPutSubResourceAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPutSubResource(null, null); + final SubProduct product = null; + Call call = service.beginPutSubResource(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -3107,7 +3139,7 @@ private ServiceResponse beginPutSubResourceDelegate(Response putAsyncSubResource() throws CloudException, IOException, InterruptedException { final SubProduct product = null; - Response result = service.putAsyncSubResource(null, null).execute(); + Response result = service.putAsyncSubResource(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); } @@ -3123,7 +3155,7 @@ public ServiceCall putAsyncSubResourceAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final SubProduct product = null; - Call call = service.putAsyncSubResource(null, null); + Call call = service.putAsyncSubResource(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -3188,7 +3220,8 @@ public void onResponse(Call call, Response response) * @return the SubProduct object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse beginPutAsyncSubResource() throws CloudException, IOException { - Call call = service.beginPutAsyncSubResource(null, null); + final SubProduct product = null; + Call call = service.beginPutAsyncSubResource(product, this.client.getAcceptLanguage()); return beginPutAsyncSubResourceDelegate(call.execute()); } @@ -3203,7 +3236,8 @@ public ServiceCall beginPutAsyncSubResourceAsync(final ServiceCallback call = service.beginPutAsyncSubResource(null, null); + final SubProduct product = null; + Call call = service.beginPutAsyncSubResource(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4377,7 +4411,7 @@ private ServiceResponse beginPost200WithPayloadDelegate(Response post202Retry200() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202Retry200(null, null).execute(); + Response result = service.post202Retry200(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPost202Retry200Headers.class); } @@ -4393,7 +4427,7 @@ public ServiceCall post202Retry200Async(final ServiceCallback serviceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202Retry200(null, null); + Call call = service.post202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -4458,7 +4492,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPost202Retry200() throws CloudException, IOException { - Call call = service.beginPost202Retry200(null, null); + final Product product = null; + Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); return beginPost202Retry200Delegate(call.execute()); } @@ -4473,7 +4508,8 @@ public ServiceCall beginPost202Retry200Async(final ServiceCallback service if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPost202Retry200(null, null); + final Product product = null; + Call call = service.beginPost202Retry200(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4547,7 +4583,7 @@ private ServiceResponseWithHeaders beginPost20 */ public ServiceResponseWithHeaders post202NoRetry204() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.post202NoRetry204(null, null).execute(); + Response result = service.post202NoRetry204(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPost202NoRetry204Headers.class); } @@ -4563,7 +4599,7 @@ public ServiceCall post202NoRetry204Async(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.post202NoRetry204(null, null); + Call call = service.post202NoRetry204(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -4628,7 +4664,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPost202NoRetry204() throws CloudException, IOException { - Call call = service.beginPost202NoRetry204(null, null); + final Product product = null; + Call call = service.beginPost202NoRetry204(product, this.client.getAcceptLanguage()); return beginPost202NoRetry204Delegate(call.execute()); } @@ -4643,7 +4680,8 @@ public ServiceCall beginPost202NoRetry204Async(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPost202NoRetry204(null, null); + final Product product = null; + Call call = service.beginPost202NoRetry204(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4717,7 +4755,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetrySucceeded(null, null).execute(); + Response result = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncRetrySucceededHeaders.class); } @@ -4733,7 +4771,7 @@ public ServiceCall postAsyncRetrySucceededAsync(final ServiceCallback s throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetrySucceeded(null, null); + Call call = service.postAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -4798,7 +4836,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPostAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPostAsyncRetrySucceededDelegate(call.execute()); } @@ -4813,7 +4852,8 @@ public ServiceCall beginPostAsyncRetrySucceededAsync(final ServiceCallback call = service.beginPostAsyncRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -4888,7 +4928,7 @@ private ServiceResponseWithHeaders */ public ServiceResponseWithHeaders postAsyncNoRetrySucceeded() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncNoRetrySucceeded(null, null).execute(); + Response result = service.postAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncNoRetrySucceededHeaders.class); } @@ -4904,7 +4944,7 @@ public ServiceCall postAsyncNoRetrySucceededAsync(final ServiceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncNoRetrySucceeded(null, null); + Call call = service.postAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -4969,7 +5009,8 @@ public void onResponse(Call call, Response response) * @return the Product object wrapped in {@link ServiceResponseWithHeaders} if successful. */ public ServiceResponseWithHeaders beginPostAsyncNoRetrySucceeded() throws CloudException, IOException { - Call call = service.beginPostAsyncNoRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); return beginPostAsyncNoRetrySucceededDelegate(call.execute()); } @@ -4984,7 +5025,8 @@ public ServiceCall beginPostAsyncNoRetrySucceededAsync(final ServiceCallback call = service.beginPostAsyncNoRetrySucceeded(null, null); + final Product product = null; + Call call = service.beginPostAsyncNoRetrySucceeded(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -5059,7 +5101,7 @@ private ServiceResponseWithHeaders postAsyncRetryFailed() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetryFailed(null, null).execute(); + Response result = service.postAsyncRetryFailed(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncRetryFailedHeaders.class); } @@ -5075,7 +5117,7 @@ public ServiceCall postAsyncRetryFailedAsync(final ServiceCallback service throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetryFailed(null, null); + Call call = service.postAsyncRetryFailed(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -5140,7 +5182,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetryFailed() throws CloudException, IOException { - Call call = service.beginPostAsyncRetryFailed(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetryFailed(product, this.client.getAcceptLanguage()); return beginPostAsyncRetryFailedDelegate(call.execute()); } @@ -5155,7 +5198,8 @@ public ServiceCall beginPostAsyncRetryFailedAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostAsyncRetryFailed(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetryFailed(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -5229,7 +5273,7 @@ private ServiceResponseWithHeaders beginP */ public ServiceResponseWithHeaders postAsyncRetrycanceled() throws CloudException, IOException, InterruptedException { final Product product = null; - Response result = service.postAsyncRetrycanceled(null, null).execute(); + Response result = service.postAsyncRetrycanceled(product, this.client.getAcceptLanguage()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken() { }.getType(), LROsPostAsyncRetrycanceledHeaders.class); } @@ -5245,7 +5289,7 @@ public ServiceCall postAsyncRetrycanceledAsync(final ServiceCallback servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final Product product = null; - Call call = service.postAsyncRetrycanceled(null, null); + Call call = service.postAsyncRetrycanceled(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback() { @Override @@ -5310,7 +5354,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders beginPostAsyncRetrycanceled() throws CloudException, IOException { - Call call = service.beginPostAsyncRetrycanceled(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetrycanceled(product, this.client.getAcceptLanguage()); return beginPostAsyncRetrycanceledDelegate(call.execute()); } @@ -5325,7 +5370,8 @@ public ServiceCall beginPostAsyncRetrycanceledAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.beginPostAsyncRetrycanceled(null, null); + final Product product = null; + Call call = service.beginPostAsyncRetrycanceled(product, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java index 96d3cb4f9ccf0..cf41764797840 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java @@ -196,7 +196,11 @@ private ServiceResponse> getSinglePagesDelegate(Response> getMultiplePages() throws CloudException, IOException { - Call call = service.getMultiplePages(null, null, null, null); + final String clientRequestId = null; + final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; + Integer maxresults = null; + Integer timeout = null; + Call call = service.getMultiplePages(clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); ServiceResponse> response = getMultiplePagesDelegate(call.execute()); PagedList result = new PagedList(response.getBody()) { @Override @@ -218,7 +222,11 @@ public ServiceCall getMultiplePagesAsync(final ListOperationCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.getMultiplePages(null, null, null, null); + final String clientRequestId = null; + final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; + Integer maxresults = null; + Integer timeout = null; + Call call = service.getMultiplePages(clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -335,8 +343,11 @@ public ServiceResponse> getMultiplePagesWithOffset(final Pagi throw new IllegalArgumentException("Parameter pagingGetMultiplePagesWithOffsetOptions is required and cannot be null."); } Validator.validate(pagingGetMultiplePagesWithOffsetOptions); + final String clientRequestId = null; + Integer maxresults = pagingGetMultiplePagesWithOffsetOptions.getMaxresults(); int offset = pagingGetMultiplePagesWithOffsetOptions.getOffset(); - Call call = service.getMultiplePagesWithOffset(offset, null, null, null, null); + Integer timeout = pagingGetMultiplePagesWithOffsetOptions.getTimeout(); + Call call = service.getMultiplePagesWithOffset(offset, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); ServiceResponse> response = getMultiplePagesWithOffsetDelegate(call.execute()); PagedList result = new PagedList(response.getBody()) { @Override @@ -367,8 +378,11 @@ public ServiceCall getMultiplePagesWithOffsetAsync(final PagingGetMultiplePagesW return null; } Validator.validate(pagingGetMultiplePagesWithOffsetOptions, serviceCallback); + final String clientRequestId = null; + Integer maxresults = pagingGetMultiplePagesWithOffsetOptions.getMaxresults(); int offset = pagingGetMultiplePagesWithOffsetOptions.getOffset(); - Call call = service.getMultiplePagesWithOffset(offset, null, null, null, null); + Integer timeout = pagingGetMultiplePagesWithOffsetOptions.getTimeout(); + Call call = service.getMultiplePagesWithOffset(offset, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -849,7 +863,11 @@ public ServiceResponse> getMultiplePagesNext(final String next if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getMultiplePagesNext(nextPageLink, null, null, null, null); + final String clientRequestId = null; + final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; + Integer maxresults = null; + Integer timeout = null; + Call call = service.getMultiplePagesNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); return getMultiplePagesNextDelegate(call.execute()); } @@ -870,7 +888,11 @@ public ServiceCall getMultiplePagesNextAsync(final String nextPageLink, final Se serviceCallback.failure(new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.")); return null; } - Call call = service.getMultiplePagesNext(nextPageLink, null, null, null, null); + final String clientRequestId = null; + final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; + Integer maxresults = null; + Integer timeout = null; + Call call = service.getMultiplePagesNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); serviceCall.newCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -990,7 +1012,11 @@ public ServiceResponse> getMultiplePagesWithOffsetNext(final S if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, null, null, null, null); + final String clientRequestId = null; + final PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = null; + Integer maxresults = pagingGetMultiplePagesWithOffsetNextOptions.getMaxresults(); + Integer timeout = pagingGetMultiplePagesWithOffsetNextOptions.getTimeout(); + Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); return getMultiplePagesWithOffsetNextDelegate(call.execute()); } @@ -1011,7 +1037,11 @@ public ServiceCall getMultiplePagesWithOffsetNextAsync(final String nextPageLink serviceCallback.failure(new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.")); return null; } - Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, null, null, null, null); + final String clientRequestId = null; + final PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = null; + Integer maxresults = pagingGetMultiplePagesWithOffsetNextOptions.getMaxresults(); + Integer timeout = pagingGetMultiplePagesWithOffsetNextOptions.getTimeout(); + Call call = service.getMultiplePagesWithOffsetNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); serviceCall.newCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index 9d7a181f3d2a6..345d975af3e30 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -60,11 +60,11 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth { if (!parameter.IsRequired) { -@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.ClientType.DefaultValue); +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); } if (parameter.IsConstant) { -@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } @Model.BuildInputMappings() @@ -110,11 +110,11 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW { if (!parameter.IsRequired) { -@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.ClientType.DefaultValue); +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); } if (parameter.IsConstant) { -@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } @Model.BuildInputMappings() diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java index 7389355d46475..d4b1368b107ae 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java @@ -144,7 +144,8 @@ private ServiceResponse getNullDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putNull() throws ErrorException, IOException { - Call call = service.putNull(null); + final String stringBody = null; + Call call = service.putNull(stringBody); return putNullDelegate(call.execute()); } @@ -159,7 +160,8 @@ public ServiceCall putNullAsync(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putNull(null); + final String stringBody = null; + Call call = service.putNull(stringBody); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 1af871dd1d83d..1df9302b58566 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -964,7 +964,8 @@ public ServiceResponse paramString(String scenario) throws ErrorException, if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramString(scenario, null); + final String value = null; + Call call = service.paramString(scenario, value); return paramStringDelegate(call.execute()); } @@ -984,7 +985,8 @@ public ServiceCall paramStringAsync(String scenario, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramString(scenario, null); + final String value = null; + Call call = service.paramString(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1362,7 +1364,8 @@ public ServiceResponse paramDatetimeRfc1123(String scenario) throws ErrorE if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramDatetimeRfc1123(scenario, null); + final DateTimeRfc1123 valueConverted = null; + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1382,7 +1385,8 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, final ServiceCallb serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramDatetimeRfc1123(scenario, null); + final DateTimeRfc1123 valueConverted = null; + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1764,7 +1768,8 @@ public ServiceResponse paramEnum(String scenario) throws ErrorException, I if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramEnum(scenario, null); + final GreyscaleColors value = null; + Call call = service.paramEnum(scenario, value); return paramEnumDelegate(call.execute()); } @@ -1784,7 +1789,8 @@ public ServiceCall paramEnumAsync(String scenario, final ServiceCallback s serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramEnum(scenario, null); + final GreyscaleColors value = null; + Call call = service.paramEnum(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java index 665480b5dc2cb..bd6d6718be372 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpClientFailureOperationsImpl.java @@ -248,7 +248,8 @@ private ServiceResponse get400Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put400() throws ErrorException, IOException { - Call call = service.put400(null); + final Boolean booleanValue = null; + Call call = service.put400(booleanValue); return put400Delegate(call.execute()); } @@ -263,7 +264,8 @@ public ServiceCall put400Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put400(null); + final Boolean booleanValue = null; + Call call = service.put400(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -332,7 +334,8 @@ private ServiceResponse put400Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse patch400() throws ErrorException, IOException { - Call call = service.patch400(null); + final Boolean booleanValue = null; + Call call = service.patch400(booleanValue); return patch400Delegate(call.execute()); } @@ -347,7 +350,8 @@ public ServiceCall patch400Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch400(null); + final Boolean booleanValue = null; + Call call = service.patch400(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -416,7 +420,8 @@ private ServiceResponse patch400Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post400() throws ErrorException, IOException { - Call call = service.post400(null); + final Boolean booleanValue = null; + Call call = service.post400(booleanValue); return post400Delegate(call.execute()); } @@ -431,7 +436,8 @@ public ServiceCall post400Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post400(null); + final Boolean booleanValue = null; + Call call = service.post400(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -500,7 +506,8 @@ private ServiceResponse post400Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete400() throws ErrorException, IOException { - Call call = service.delete400(null); + final Boolean booleanValue = null; + Call call = service.delete400(booleanValue); return delete400Delegate(call.execute()); } @@ -515,7 +522,8 @@ public ServiceCall delete400Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete400(null); + final Boolean booleanValue = null; + Call call = service.delete400(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -716,7 +724,8 @@ private ServiceResponse get403Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put404() throws ErrorException, IOException { - Call call = service.put404(null); + final Boolean booleanValue = null; + Call call = service.put404(booleanValue); return put404Delegate(call.execute()); } @@ -731,7 +740,8 @@ public ServiceCall put404Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put404(null); + final Boolean booleanValue = null; + Call call = service.put404(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -800,7 +810,8 @@ private ServiceResponse put404Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse patch405() throws ErrorException, IOException { - Call call = service.patch405(null); + final Boolean booleanValue = null; + Call call = service.patch405(booleanValue); return patch405Delegate(call.execute()); } @@ -815,7 +826,8 @@ public ServiceCall patch405Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch405(null); + final Boolean booleanValue = null; + Call call = service.patch405(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -884,7 +896,8 @@ private ServiceResponse patch405Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post406() throws ErrorException, IOException { - Call call = service.post406(null); + final Boolean booleanValue = null; + Call call = service.post406(booleanValue); return post406Delegate(call.execute()); } @@ -899,7 +912,8 @@ public ServiceCall post406Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post406(null); + final Boolean booleanValue = null; + Call call = service.post406(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -968,7 +982,8 @@ private ServiceResponse post406Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete407() throws ErrorException, IOException { - Call call = service.delete407(null); + final Boolean booleanValue = null; + Call call = service.delete407(booleanValue); return delete407Delegate(call.execute()); } @@ -983,7 +998,8 @@ public ServiceCall delete407Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete407(null); + final Boolean booleanValue = null; + Call call = service.delete407(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1052,7 +1068,8 @@ private ServiceResponse delete407Delegate(Response response * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put409() throws ErrorException, IOException { - Call call = service.put409(null); + final Boolean booleanValue = null; + Call call = service.put409(booleanValue); return put409Delegate(call.execute()); } @@ -1067,7 +1084,8 @@ public ServiceCall put409Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put409(null); + final Boolean booleanValue = null; + Call call = service.put409(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1268,7 +1286,8 @@ private ServiceResponse get412Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse put413() throws ErrorException, IOException { - Call call = service.put413(null); + final Boolean booleanValue = null; + Call call = service.put413(booleanValue); return put413Delegate(call.execute()); } @@ -1283,7 +1302,8 @@ public ServiceCall put413Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put413(null); + final Boolean booleanValue = null; + Call call = service.put413(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1352,7 +1372,8 @@ private ServiceResponse put413Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse patch414() throws ErrorException, IOException { - Call call = service.patch414(null); + final Boolean booleanValue = null; + Call call = service.patch414(booleanValue); return patch414Delegate(call.execute()); } @@ -1367,7 +1388,8 @@ public ServiceCall patch414Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch414(null); + final Boolean booleanValue = null; + Call call = service.patch414(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1436,7 +1458,8 @@ private ServiceResponse patch414Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post415() throws ErrorException, IOException { - Call call = service.post415(null); + final Boolean booleanValue = null; + Call call = service.post415(booleanValue); return post415Delegate(call.execute()); } @@ -1451,7 +1474,8 @@ public ServiceCall post415Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post415(null); + final Boolean booleanValue = null; + Call call = service.post415(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1564,7 +1588,8 @@ private ServiceResponse get416Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete417() throws ErrorException, IOException { - Call call = service.delete417(null); + final Boolean booleanValue = null; + Call call = service.delete417(booleanValue); return delete417Delegate(call.execute()); } @@ -1579,7 +1604,8 @@ public ServiceCall delete417Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete417(null); + final Boolean booleanValue = null; + Call call = service.delete417(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java index 0c2eb12a0639a..d422aab756c84 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRedirectsOperationsImpl.java @@ -328,7 +328,8 @@ private ServiceResponseWithHeaders get301Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders put301() throws ErrorException, IOException { - Call call = service.put301(null); + final Boolean booleanValue = null; + Call call = service.put301(booleanValue); return put301Delegate(call.execute()); } @@ -343,7 +344,8 @@ public ServiceCall put301Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put301(null); + final Boolean booleanValue = null; + Call call = service.put301(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -505,7 +507,8 @@ private ServiceResponseWithHeaders get302Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders patch302() throws ErrorException, IOException { - Call call = service.patch302(null); + final Boolean booleanValue = null; + Call call = service.patch302(booleanValue); return patch302Delegate(call.execute()); } @@ -520,7 +523,8 @@ public ServiceCall patch302Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch302(null); + final Boolean booleanValue = null; + Call call = service.patch302(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -590,7 +594,8 @@ private ServiceResponseWithHeaders patch302D * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders post303() throws ErrorException, IOException { - Call call = service.post303(null); + final Boolean booleanValue = null; + Call call = service.post303(booleanValue); return post303Delegate(call.execute()); } @@ -605,7 +610,8 @@ public ServiceCall post303Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post303(null); + final Boolean booleanValue = null; + Call call = service.post303(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -768,7 +774,8 @@ private ServiceResponseWithHeaders get307Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders put307() throws ErrorException, IOException { - Call call = service.put307(null); + final Boolean booleanValue = null; + Call call = service.put307(booleanValue); return put307Delegate(call.execute()); } @@ -783,7 +790,8 @@ public ServiceCall put307Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put307(null); + final Boolean booleanValue = null; + Call call = service.put307(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -854,7 +862,8 @@ private ServiceResponseWithHeaders put307Deleg * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders patch307() throws ErrorException, IOException { - Call call = service.patch307(null); + final Boolean booleanValue = null; + Call call = service.patch307(booleanValue); return patch307Delegate(call.execute()); } @@ -869,7 +878,8 @@ public ServiceCall patch307Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch307(null); + final Boolean booleanValue = null; + Call call = service.patch307(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -940,7 +950,8 @@ private ServiceResponseWithHeaders patch307D * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders post307() throws ErrorException, IOException { - Call call = service.post307(null); + final Boolean booleanValue = null; + Call call = service.post307(booleanValue); return post307Delegate(call.execute()); } @@ -955,7 +966,8 @@ public ServiceCall post307Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post307(null); + final Boolean booleanValue = null; + Call call = service.post307(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1026,7 +1038,8 @@ private ServiceResponseWithHeaders post307Del * @return the {@link ServiceResponseWithHeaders} object if successful. */ public ServiceResponseWithHeaders delete307() throws ErrorException, IOException { - Call call = service.delete307(null); + final Boolean booleanValue = null; + Call call = service.delete307(booleanValue); return delete307Delegate(call.execute()); } @@ -1041,7 +1054,8 @@ public ServiceCall delete307Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete307(null); + final Boolean booleanValue = null; + Call call = service.delete307(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java index d05003ef66d57..d3ba17ef439c6 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpRetryOperationsImpl.java @@ -145,7 +145,8 @@ private ServiceResponse head408Delegate(Response response) throws Er * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put500() throws ErrorException, IOException { - Call call = service.put500(null); + final Boolean booleanValue = null; + Call call = service.put500(booleanValue); return put500Delegate(call.execute()); } @@ -160,7 +161,8 @@ public ServiceCall put500Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put500(null); + final Boolean booleanValue = null; + Call call = service.put500(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -230,7 +232,8 @@ private ServiceResponse put500Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch500() throws ErrorException, IOException { - Call call = service.patch500(null); + final Boolean booleanValue = null; + Call call = service.patch500(booleanValue); return patch500Delegate(call.execute()); } @@ -245,7 +248,8 @@ public ServiceCall patch500Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch500(null); + final Boolean booleanValue = null; + Call call = service.patch500(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -360,7 +364,8 @@ private ServiceResponse get502Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post503() throws ErrorException, IOException { - Call call = service.post503(null); + final Boolean booleanValue = null; + Call call = service.post503(booleanValue); return post503Delegate(call.execute()); } @@ -375,7 +380,8 @@ public ServiceCall post503Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post503(null); + final Boolean booleanValue = null; + Call call = service.post503(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -445,7 +451,8 @@ private ServiceResponse post503Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete503() throws ErrorException, IOException { - Call call = service.delete503(null); + final Boolean booleanValue = null; + Call call = service.delete503(booleanValue); return delete503Delegate(call.execute()); } @@ -460,7 +467,8 @@ public ServiceCall delete503Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete503(null); + final Boolean booleanValue = null; + Call call = service.delete503(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -530,7 +538,8 @@ private ServiceResponse delete503Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put504() throws ErrorException, IOException { - Call call = service.put504(null); + final Boolean booleanValue = null; + Call call = service.put504(booleanValue); return put504Delegate(call.execute()); } @@ -545,7 +554,8 @@ public ServiceCall put504Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put504(null); + final Boolean booleanValue = null; + Call call = service.put504(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -615,7 +625,8 @@ private ServiceResponse put504Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch504() throws ErrorException, IOException { - Call call = service.patch504(null); + final Boolean booleanValue = null; + Call call = service.patch504(booleanValue); return patch504Delegate(call.execute()); } @@ -630,7 +641,8 @@ public ServiceCall patch504Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch504(null); + final Boolean booleanValue = null; + Call call = service.patch504(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java index d77f6a9fb77b7..1ea87e8af11a7 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpServerFailureOperationsImpl.java @@ -170,7 +170,8 @@ private ServiceResponse get501Delegate(Response response) t * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse post505() throws ErrorException, IOException { - Call call = service.post505(null); + final Boolean booleanValue = null; + Call call = service.post505(booleanValue); return post505Delegate(call.execute()); } @@ -185,7 +186,8 @@ public ServiceCall post505Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post505(null); + final Boolean booleanValue = null; + Call call = service.post505(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -254,7 +256,8 @@ private ServiceResponse post505Delegate(Response response) * @return the Error object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse delete505() throws ErrorException, IOException { - Call call = service.delete505(null); + final Boolean booleanValue = null; + Call call = service.delete505(booleanValue); return delete505Delegate(call.execute()); } @@ -269,7 +272,8 @@ public ServiceCall delete505Async(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete505(null); + final Boolean booleanValue = null; + Call call = service.delete505(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java index 496ba12e8376c..09ab15c84944e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java @@ -230,7 +230,8 @@ private ServiceResponse get200Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put200() throws ErrorException, IOException { - Call call = service.put200(null); + final Boolean booleanValue = null; + Call call = service.put200(booleanValue); return put200Delegate(call.execute()); } @@ -245,7 +246,8 @@ public ServiceCall put200Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put200(null); + final Boolean booleanValue = null; + Call call = service.put200(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -315,7 +317,8 @@ private ServiceResponse put200Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch200() throws ErrorException, IOException { - Call call = service.patch200(null); + final Boolean booleanValue = null; + Call call = service.patch200(booleanValue); return patch200Delegate(call.execute()); } @@ -330,7 +333,8 @@ public ServiceCall patch200Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch200(null); + final Boolean booleanValue = null; + Call call = service.patch200(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -400,7 +404,8 @@ private ServiceResponse patch200Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post200() throws ErrorException, IOException { - Call call = service.post200(null); + final Boolean booleanValue = null; + Call call = service.post200(booleanValue); return post200Delegate(call.execute()); } @@ -415,7 +420,8 @@ public ServiceCall post200Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post200(null); + final Boolean booleanValue = null; + Call call = service.post200(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -485,7 +491,8 @@ private ServiceResponse post200Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete200() throws ErrorException, IOException { - Call call = service.delete200(null); + final Boolean booleanValue = null; + Call call = service.delete200(booleanValue); return delete200Delegate(call.execute()); } @@ -500,7 +507,8 @@ public ServiceCall delete200Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete200(null); + final Boolean booleanValue = null; + Call call = service.delete200(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -570,7 +578,8 @@ private ServiceResponse delete200Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put201() throws ErrorException, IOException { - Call call = service.put201(null); + final Boolean booleanValue = null; + Call call = service.put201(booleanValue); return put201Delegate(call.execute()); } @@ -585,7 +594,8 @@ public ServiceCall put201Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put201(null); + final Boolean booleanValue = null; + Call call = service.put201(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -655,7 +665,8 @@ private ServiceResponse put201Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post201() throws ErrorException, IOException { - Call call = service.post201(null); + final Boolean booleanValue = null; + Call call = service.post201(booleanValue); return post201Delegate(call.execute()); } @@ -670,7 +681,8 @@ public ServiceCall post201Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post201(null); + final Boolean booleanValue = null; + Call call = service.post201(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -740,7 +752,8 @@ private ServiceResponse post201Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put202() throws ErrorException, IOException { - Call call = service.put202(null); + final Boolean booleanValue = null; + Call call = service.put202(booleanValue); return put202Delegate(call.execute()); } @@ -755,7 +768,8 @@ public ServiceCall put202Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put202(null); + final Boolean booleanValue = null; + Call call = service.put202(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -825,7 +839,8 @@ private ServiceResponse put202Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch202() throws ErrorException, IOException { - Call call = service.patch202(null); + final Boolean booleanValue = null; + Call call = service.patch202(booleanValue); return patch202Delegate(call.execute()); } @@ -840,7 +855,8 @@ public ServiceCall patch202Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch202(null); + final Boolean booleanValue = null; + Call call = service.patch202(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -910,7 +926,8 @@ private ServiceResponse patch202Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post202() throws ErrorException, IOException { - Call call = service.post202(null); + final Boolean booleanValue = null; + Call call = service.post202(booleanValue); return post202Delegate(call.execute()); } @@ -925,7 +942,8 @@ public ServiceCall post202Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post202(null); + final Boolean booleanValue = null; + Call call = service.post202(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -995,7 +1013,8 @@ private ServiceResponse post202Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete202() throws ErrorException, IOException { - Call call = service.delete202(null); + final Boolean booleanValue = null; + Call call = service.delete202(booleanValue); return delete202Delegate(call.execute()); } @@ -1010,7 +1029,8 @@ public ServiceCall delete202Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete202(null); + final Boolean booleanValue = null; + Call call = service.delete202(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1125,7 +1145,8 @@ private ServiceResponse head204Delegate(Response response) throws Er * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse put204() throws ErrorException, IOException { - Call call = service.put204(null); + final Boolean booleanValue = null; + Call call = service.put204(booleanValue); return put204Delegate(call.execute()); } @@ -1140,7 +1161,8 @@ public ServiceCall put204Async(final ServiceCallback serviceCallback) thro if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.put204(null); + final Boolean booleanValue = null; + Call call = service.put204(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1210,7 +1232,8 @@ private ServiceResponse put204Delegate(Response response) th * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse patch204() throws ErrorException, IOException { - Call call = service.patch204(null); + final Boolean booleanValue = null; + Call call = service.patch204(booleanValue); return patch204Delegate(call.execute()); } @@ -1225,7 +1248,8 @@ public ServiceCall patch204Async(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.patch204(null); + final Boolean booleanValue = null; + Call call = service.patch204(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1295,7 +1319,8 @@ private ServiceResponse patch204Delegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse post204() throws ErrorException, IOException { - Call call = service.post204(null); + final Boolean booleanValue = null; + Call call = service.post204(booleanValue); return post204Delegate(call.execute()); } @@ -1310,7 +1335,8 @@ public ServiceCall post204Async(final ServiceCallback serviceCallback) thr if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.post204(null); + final Boolean booleanValue = null; + Call call = service.post204(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1380,7 +1406,8 @@ private ServiceResponse post204Delegate(Response response) t * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse delete204() throws ErrorException, IOException { - Call call = service.delete204(null); + final Boolean booleanValue = null; + Call call = service.delete204(booleanValue); return delete204Delegate(call.execute()); } @@ -1395,7 +1422,8 @@ public ServiceCall delete204Async(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.delete204(null); + final Boolean booleanValue = null; + Call call = service.delete204(booleanValue); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java index a49d8d7625da1..425c76ba3ada8 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java @@ -169,7 +169,8 @@ interface AutoRestResourceFlatteningTestServiceService { * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putArray() throws ErrorException, IOException { - Call call = service.putArray(null); + final List resourceArray = null; + Call call = service.putArray(resourceArray); return putArrayDelegate(call.execute()); } @@ -184,7 +185,8 @@ public ServiceCall putArrayAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putArray(null); + final List resourceArray = null; + Call call = service.putArray(resourceArray); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -301,7 +303,8 @@ private ServiceResponse> getArrayDelegate(Response putDictionary() throws ErrorException, IOException { - Call call = service.putDictionary(null); + final Map resourceDictionary = null; + Call call = service.putDictionary(resourceDictionary); return putDictionaryDelegate(call.execute()); } @@ -316,7 +319,8 @@ public ServiceCall putDictionaryAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putDictionary(null); + final Map resourceDictionary = null; + Call call = service.putDictionary(resourceDictionary); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -433,7 +437,8 @@ private ServiceResponse> getDictionaryDelegate(Res * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putResourceCollection() throws ErrorException, IOException { - Call call = service.putResourceCollection(null); + final ResourceCollection resourceComplexObject = null; + Call call = service.putResourceCollection(resourceComplexObject); return putResourceCollectionDelegate(call.execute()); } @@ -448,7 +453,8 @@ public ServiceCall putResourceCollectionAsync(final ServiceCallback servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putResourceCollection(null); + final ResourceCollection resourceComplexObject = null; + Call call = service.putResourceCollection(resourceComplexObject); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -565,7 +571,8 @@ private ServiceResponse getResourceCollectionDelegate(Respon * @return the SimpleProduct object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse putSimpleProduct() throws ErrorException, IOException { - Call call = service.putSimpleProduct(null); + final SimpleProduct simpleBodyProduct = null; + Call call = service.putSimpleProduct(simpleBodyProduct); return putSimpleProductDelegate(call.execute()); } @@ -580,7 +587,8 @@ public ServiceCall putSimpleProductAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putSimpleProduct(null); + final SimpleProduct simpleBodyProduct = null; + Call call = service.putSimpleProduct(simpleBodyProduct); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -661,10 +669,14 @@ public ServiceResponse postFlattenedSimpleProduct(String productI if (maxProductDisplayName == null) { throw new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null."); } + final String description = null; + final String odatavalue = null; SimpleProduct simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); + simpleBodyProduct = null; simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); - Call call = service.postFlattenedSimpleProduct(null); + simpleBodyProduct = null; + Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); return postFlattenedSimpleProductDelegate(call.execute()); } @@ -689,10 +701,14 @@ public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxP serviceCallback.failure(new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null.")); return null; } + final String description = null; + final String odatavalue = null; SimpleProduct simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); + simpleBodyProduct = null; simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); - Call call = service.postFlattenedSimpleProduct(null); + simpleBodyProduct = null; + Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java index 8cabd82bca5a0..e0b711b87ac9d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java @@ -210,7 +210,8 @@ private ServiceResponse postRequiredIntegerParameterDelegate(Response postOptionalIntegerParameter() throws ErrorException, IOException { - Call call = service.postOptionalIntegerParameter(null); + final Integer bodyParameter = null; + Call call = service.postOptionalIntegerParameter(bodyParameter); return postOptionalIntegerParameterDelegate(call.execute()); } @@ -225,7 +226,8 @@ public ServiceCall postOptionalIntegerParameterAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalIntegerParameter(null); + final Integer bodyParameter = null; + Call call = service.postOptionalIntegerParameter(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -351,7 +353,8 @@ private ServiceResponse postRequiredIntegerPropertyDelegate(Response postOptionalIntegerProperty() throws ErrorException, IOException { - Call call = service.postOptionalIntegerProperty(null); + final IntOptionalWrapper bodyParameter = null; + Call call = service.postOptionalIntegerProperty(bodyParameter); return postOptionalIntegerPropertyDelegate(call.execute()); } @@ -366,7 +369,8 @@ public ServiceCall postOptionalIntegerPropertyAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalIntegerProperty(null); + final IntOptionalWrapper bodyParameter = null; + Call call = service.postOptionalIntegerProperty(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -484,7 +488,8 @@ private ServiceResponse postRequiredIntegerHeaderDelegate(Response postOptionalIntegerHeader() throws ErrorException, IOException { - Call call = service.postOptionalIntegerHeader(null); + final Integer headerParameter = null; + Call call = service.postOptionalIntegerHeader(headerParameter); return postOptionalIntegerHeaderDelegate(call.execute()); } @@ -499,7 +504,8 @@ public ServiceCall postOptionalIntegerHeaderAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalIntegerHeader(null); + final Integer headerParameter = null; + Call call = service.postOptionalIntegerHeader(headerParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -623,7 +629,8 @@ private ServiceResponse postRequiredStringParameterDelegate(Response postOptionalStringParameter() throws ErrorException, IOException { - Call call = service.postOptionalStringParameter(null); + final String bodyParameter = null; + Call call = service.postOptionalStringParameter(bodyParameter); return postOptionalStringParameterDelegate(call.execute()); } @@ -638,7 +645,8 @@ public ServiceCall postOptionalStringParameterAsync(final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalStringParameter(null); + final String bodyParameter = null; + Call call = service.postOptionalStringParameter(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -764,7 +772,8 @@ private ServiceResponse postRequiredStringPropertyDelegate(Response postOptionalStringProperty() throws ErrorException, IOException { - Call call = service.postOptionalStringProperty(null); + final StringOptionalWrapper bodyParameter = null; + Call call = service.postOptionalStringProperty(bodyParameter); return postOptionalStringPropertyDelegate(call.execute()); } @@ -779,7 +788,8 @@ public ServiceCall postOptionalStringPropertyAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalStringProperty(null); + final StringOptionalWrapper bodyParameter = null; + Call call = service.postOptionalStringProperty(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -905,7 +915,8 @@ private ServiceResponse postRequiredStringHeaderDelegate(Response postOptionalStringHeader() throws ErrorException, IOException { - Call call = service.postOptionalStringHeader(null); + final String bodyParameter = null; + Call call = service.postOptionalStringHeader(bodyParameter); return postOptionalStringHeaderDelegate(call.execute()); } @@ -920,7 +931,8 @@ public ServiceCall postOptionalStringHeaderAsync(final ServiceCallback ser if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalStringHeader(null); + final String bodyParameter = null; + Call call = service.postOptionalStringHeader(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1046,7 +1058,8 @@ private ServiceResponse postRequiredClassParameterDelegate(Response postOptionalClassParameter() throws ErrorException, IOException { - Call call = service.postOptionalClassParameter(null); + final Product bodyParameter = null; + Call call = service.postOptionalClassParameter(bodyParameter); return postOptionalClassParameterDelegate(call.execute()); } @@ -1061,7 +1074,8 @@ public ServiceCall postOptionalClassParameterAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalClassParameter(null); + final Product bodyParameter = null; + Call call = service.postOptionalClassParameter(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1189,7 +1203,8 @@ private ServiceResponse postRequiredClassPropertyDelegate(Response postOptionalClassProperty() throws ErrorException, IOException { - Call call = service.postOptionalClassProperty(null); + final ClassOptionalWrapper bodyParameter = null; + Call call = service.postOptionalClassProperty(bodyParameter); return postOptionalClassPropertyDelegate(call.execute()); } @@ -1204,7 +1219,8 @@ public ServiceCall postOptionalClassPropertyAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalClassProperty(null); + final ClassOptionalWrapper bodyParameter = null; + Call call = service.postOptionalClassProperty(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1332,7 +1348,8 @@ private ServiceResponse postRequiredArrayParameterDelegate(Response postOptionalArrayParameter() throws ErrorException, IOException { - Call call = service.postOptionalArrayParameter(null); + final List bodyParameter = null; + Call call = service.postOptionalArrayParameter(bodyParameter); return postOptionalArrayParameterDelegate(call.execute()); } @@ -1347,7 +1364,8 @@ public ServiceCall postOptionalArrayParameterAsync(final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalArrayParameter(null); + final List bodyParameter = null; + Call call = service.postOptionalArrayParameter(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1475,7 +1493,8 @@ private ServiceResponse postRequiredArrayPropertyDelegate(Response postOptionalArrayProperty() throws ErrorException, IOException { - Call call = service.postOptionalArrayProperty(null); + final ArrayOptionalWrapper bodyParameter = null; + Call call = service.postOptionalArrayProperty(bodyParameter); return postOptionalArrayPropertyDelegate(call.execute()); } @@ -1490,7 +1509,8 @@ public ServiceCall postOptionalArrayPropertyAsync(final ServiceCallback se if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalArrayProperty(null); + final ArrayOptionalWrapper bodyParameter = null; + Call call = service.postOptionalArrayProperty(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1620,7 +1640,8 @@ private ServiceResponse postRequiredArrayHeaderDelegate(Response postOptionalArrayHeader() throws ErrorException, IOException { - Call call = service.postOptionalArrayHeader(null); + final String headerParameterConverted = null; + Call call = service.postOptionalArrayHeader(headerParameterConverted); return postOptionalArrayHeaderDelegate(call.execute()); } @@ -1635,7 +1656,8 @@ public ServiceCall postOptionalArrayHeaderAsync(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.postOptionalArrayHeader(null); + final String headerParameterConverted = null; + Call call = service.postOptionalArrayHeader(headerParameterConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java index a854b28e527d3..4b8c4626cc9f5 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ImplicitOperationsImpl.java @@ -149,7 +149,8 @@ private ServiceResponse getRequiredPathDelegate(Response re * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putOptionalQuery() throws ErrorException, IOException { - Call call = service.putOptionalQuery(null); + final String queryParameter = null; + Call call = service.putOptionalQuery(queryParameter); return putOptionalQueryDelegate(call.execute()); } @@ -164,7 +165,8 @@ public ServiceCall putOptionalQueryAsync(final ServiceCallback serviceCall if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putOptionalQuery(null); + final String queryParameter = null; + Call call = service.putOptionalQuery(queryParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -234,7 +236,8 @@ private ServiceResponse putOptionalQueryDelegate(Response re * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putOptionalHeader() throws ErrorException, IOException { - Call call = service.putOptionalHeader(null); + final String queryParameter = null; + Call call = service.putOptionalHeader(queryParameter); return putOptionalHeaderDelegate(call.execute()); } @@ -249,7 +252,8 @@ public ServiceCall putOptionalHeaderAsync(final ServiceCallback serviceCal if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putOptionalHeader(null); + final String queryParameter = null; + Call call = service.putOptionalHeader(queryParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -319,7 +323,8 @@ private ServiceResponse putOptionalHeaderDelegate(Response r * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse putOptionalBody() throws ErrorException, IOException { - Call call = service.putOptionalBody(null); + final String bodyParameter = null; + Call call = service.putOptionalBody(bodyParameter); return putOptionalBodyDelegate(call.execute()); } @@ -334,7 +339,8 @@ public ServiceCall putOptionalBodyAsync(final ServiceCallback serviceCallb if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.putOptionalBody(null); + final String bodyParameter = null; + Call call = service.putOptionalBody(bodyParameter); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java index 357ea0ea755ea..c7085c350749f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathItemsOperationsImpl.java @@ -91,7 +91,9 @@ public ServiceResponse getAllWithValues(String localStringPath, String pat if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); return getAllWithValuesDelegate(call.execute()); } @@ -120,7 +122,9 @@ public ServiceCall getAllWithValuesAsync(String localStringPath, String pathItem serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getAllWithValues(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -230,7 +234,9 @@ public ServiceResponse getGlobalQueryNull(String localStringPath, String p if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); return getGlobalQueryNullDelegate(call.execute()); } @@ -259,7 +265,9 @@ public ServiceCall getGlobalQueryNullAsync(String localStringPath, String pathIt serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getGlobalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -369,7 +377,9 @@ public ServiceResponse getGlobalAndLocalQueryNull(String localStringPath, if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); return getGlobalAndLocalQueryNullDelegate(call.execute()); } @@ -398,7 +408,9 @@ public ServiceCall getGlobalAndLocalQueryNullAsync(String localStringPath, Strin serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getGlobalAndLocalQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -508,7 +520,9 @@ public ServiceResponse getLocalPathItemQueryNull(String localStringPath, S if (this.client.getGlobalStringPath() == null) { throw new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null."); } - Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); return getLocalPathItemQueryNullDelegate(call.execute()); } @@ -537,7 +551,9 @@ public ServiceCall getLocalPathItemQueryNullAsync(String localStringPath, String serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getGlobalStringPath() is required and cannot be null.")); return null; } - Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), null, null, null); + final String localStringQuery = null; + final String pathItemStringQuery = null; + Call call = service.getLocalPathItemQueryNull(localStringPath, pathItemStringPath, this.client.getGlobalStringPath(), localStringQuery, pathItemStringQuery, this.client.getGlobalStringQuery()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java index 1e189f1ff4c6b..5cb35d0f1043d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java @@ -299,7 +299,8 @@ private ServiceResponse getBooleanFalseDelegate(Response res * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse getBooleanNull() throws ErrorException, IOException { - Call call = service.getBooleanNull(null); + final Boolean boolQuery = null; + Call call = service.getBooleanNull(boolQuery); return getBooleanNullDelegate(call.execute()); } @@ -314,7 +315,8 @@ public ServiceCall getBooleanNullAsync(final ServiceCallback serviceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.getBooleanNull(null); + final Boolean boolQuery = null; + Call call = service.getBooleanNull(boolQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -478,7 +480,8 @@ private ServiceResponse getIntNegativeOneMillionDelegate(Response getIntNull() throws ErrorException, IOException { - Call call = service.getIntNull(null); + final Integer intQuery = null; + Call call = service.getIntNull(intQuery); return getIntNullDelegate(call.execute()); } @@ -493,7 +496,8 @@ public ServiceCall getIntNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.getIntNull(null); + final Integer intQuery = null; + Call call = service.getIntNull(intQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -657,7 +661,8 @@ private ServiceResponse getNegativeTenBillionDelegate(Response getLongNull() throws ErrorException, IOException { - Call call = service.getLongNull(null); + final Long longQuery = null; + Call call = service.getLongNull(longQuery); return getLongNullDelegate(call.execute()); } @@ -672,7 +677,8 @@ public ServiceCall getLongNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.getLongNull(null); + final Long longQuery = null; + Call call = service.getLongNull(longQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -836,7 +842,8 @@ private ServiceResponse floatScientificNegativeDelegate(Response floatNull() throws ErrorException, IOException { - Call call = service.floatNull(null); + final Double floatQuery = null; + Call call = service.floatNull(floatQuery); return floatNullDelegate(call.execute()); } @@ -851,7 +858,8 @@ public ServiceCall floatNullAsync(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.floatNull(null); + final Double floatQuery = null; + Call call = service.floatNull(floatQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1015,7 +1023,8 @@ private ServiceResponse doubleDecimalNegativeDelegate(Response doubleNull() throws ErrorException, IOException { - Call call = service.doubleNull(null); + final Double doubleQuery = null; + Call call = service.doubleNull(doubleQuery); return doubleNullDelegate(call.execute()); } @@ -1030,7 +1039,8 @@ public ServiceCall doubleNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.doubleNull(null); + final Double doubleQuery = null; + Call call = service.doubleNull(doubleQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1241,7 +1251,8 @@ private ServiceResponse stringEmptyDelegate(Response respons * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse stringNull() throws ErrorException, IOException { - Call call = service.stringNull(null); + final String stringQuery = null; + Call call = service.stringNull(stringQuery); return stringNullDelegate(call.execute()); } @@ -1256,7 +1267,8 @@ public ServiceCall stringNullAsync(final ServiceCallback serviceCallback) if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.stringNull(null); + final String stringQuery = null; + Call call = service.stringNull(stringQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1326,7 +1338,8 @@ private ServiceResponse stringNullDelegate(Response response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumValid() throws ErrorException, IOException { - Call call = service.enumValid(null); + final UriColor enumQuery = null; + Call call = service.enumValid(enumQuery); return enumValidDelegate(call.execute()); } @@ -1341,7 +1354,8 @@ public ServiceCall enumValidAsync(final ServiceCallback serviceCallback) t if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.enumValid(null); + final UriColor enumQuery = null; + Call call = service.enumValid(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1411,7 +1425,8 @@ private ServiceResponse enumValidDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumNull() throws ErrorException, IOException { - Call call = service.enumNull(null); + final UriColor enumQuery = null; + Call call = service.enumNull(enumQuery); return enumNullDelegate(call.execute()); } @@ -1426,7 +1441,8 @@ public ServiceCall enumNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.enumNull(null); + final UriColor enumQuery = null; + Call call = service.enumNull(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1496,7 +1512,8 @@ private ServiceResponse enumNullDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteMultiByte() throws ErrorException, IOException { - Call call = service.byteMultiByte(null); + final String byteQueryConverted = null; + Call call = service.byteMultiByte(byteQueryConverted); return byteMultiByteDelegate(call.execute()); } @@ -1511,7 +1528,8 @@ public ServiceCall byteMultiByteAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.byteMultiByte(null); + final String byteQueryConverted = null; + Call call = service.byteMultiByte(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1632,7 +1650,8 @@ private ServiceResponse byteEmptyDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteNull() throws ErrorException, IOException { - Call call = service.byteNull(null); + final String byteQueryConverted = null; + Call call = service.byteNull(byteQueryConverted); return byteNullDelegate(call.execute()); } @@ -1647,7 +1666,8 @@ public ServiceCall byteNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.byteNull(null); + final String byteQueryConverted = null; + Call call = service.byteNull(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1766,7 +1786,8 @@ private ServiceResponse dateValidDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateNull() throws ErrorException, IOException { - Call call = service.dateNull(null); + final LocalDate dateQuery = null; + Call call = service.dateNull(dateQuery); return dateNullDelegate(call.execute()); } @@ -1781,7 +1802,8 @@ public ServiceCall dateNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.dateNull(null); + final LocalDate dateQuery = null; + Call call = service.dateNull(dateQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1898,7 +1920,8 @@ private ServiceResponse dateTimeValidDelegate(Response respo * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateTimeNull() throws ErrorException, IOException { - Call call = service.dateTimeNull(null); + final DateTime dateTimeQuery = null; + Call call = service.dateTimeNull(dateTimeQuery); return dateTimeNullDelegate(call.execute()); } @@ -1913,7 +1936,8 @@ public ServiceCall dateTimeNullAsync(final ServiceCallback serviceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.dateTimeNull(null); + final DateTime dateTimeQuery = null; + Call call = service.dateTimeNull(dateTimeQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1983,7 +2007,8 @@ private ServiceResponse dateTimeNullDelegate(Response respon * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvValid() throws ErrorException, IOException { - Call call = service.arrayStringCsvValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvValid(arrayQueryConverted); return arrayStringCsvValidDelegate(call.execute()); } @@ -1998,7 +2023,8 @@ public ServiceCall arrayStringCsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.arrayStringCsvValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2072,7 +2098,8 @@ private ServiceResponse arrayStringCsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvNull() throws ErrorException, IOException { - Call call = service.arrayStringCsvNull(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvNull(arrayQueryConverted); return arrayStringCsvNullDelegate(call.execute()); } @@ -2087,7 +2114,8 @@ public ServiceCall arrayStringCsvNullAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.arrayStringCsvNull(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvNull(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2161,7 +2189,8 @@ private ServiceResponse arrayStringCsvNullDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvEmpty() throws ErrorException, IOException { - Call call = service.arrayStringCsvEmpty(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); return arrayStringCsvEmptyDelegate(call.execute()); } @@ -2176,7 +2205,8 @@ public ServiceCall arrayStringCsvEmptyAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.arrayStringCsvEmpty(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2250,7 +2280,8 @@ private ServiceResponse arrayStringCsvEmptyDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringSsvValid() throws ErrorException, IOException { - Call call = service.arrayStringSsvValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringSsvValid(arrayQueryConverted); return arrayStringSsvValidDelegate(call.execute()); } @@ -2265,7 +2296,8 @@ public ServiceCall arrayStringSsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.arrayStringSsvValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringSsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2339,7 +2371,8 @@ private ServiceResponse arrayStringSsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringTsvValid() throws ErrorException, IOException { - Call call = service.arrayStringTsvValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringTsvValid(arrayQueryConverted); return arrayStringTsvValidDelegate(call.execute()); } @@ -2354,7 +2387,8 @@ public ServiceCall arrayStringTsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.arrayStringTsvValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringTsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2428,7 +2462,8 @@ private ServiceResponse arrayStringTsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringPipesValid() throws ErrorException, IOException { - Call call = service.arrayStringPipesValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringPipesValid(arrayQueryConverted); return arrayStringPipesValidDelegate(call.execute()); } @@ -2443,7 +2478,8 @@ public ServiceCall arrayStringPipesValidAsync(final ServiceCallback servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.arrayStringPipesValid(null); + final String arrayQueryConverted = null; + Call call = service.arrayStringPipesValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java index 7a46a9788f3f4..e063d58222d8e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/AutoRestValidationTestImpl.java @@ -270,7 +270,8 @@ public ServiceResponse validationOfBody(String resourceGroupName, int i if (this.getApiVersion() == null) { throw new IllegalArgumentException("Parameter this.getApiVersion() is required and cannot be null."); } - Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, null, this.getApiVersion()); + final Product body = null; + Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, body, this.getApiVersion()); return validationOfBodyDelegate(call.execute()); } @@ -299,7 +300,8 @@ public ServiceCall validationOfBodyAsync(String resourceGroupName, int id, final serviceCallback.failure(new IllegalArgumentException("Parameter this.getApiVersion() is required and cannot be null.")); return null; } - Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, null, this.getApiVersion()); + final Product body = null; + Call call = service.validationOfBody(this.getSubscriptionId(), resourceGroupName, id, body, this.getApiVersion()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -441,7 +443,8 @@ private ServiceResponse getWithConstantInPathDelegate(Response postWithConstantInBody() throws ServiceException, IOException { final String constantParam = "constant"; - Call call = service.postWithConstantInBody(constantParam, null); + final Product body = null; + Call call = service.postWithConstantInBody(constantParam, body); return postWithConstantInBodyDelegate(call.execute()); } @@ -456,7 +459,8 @@ public ServiceCall postWithConstantInBodyAsync(final ServiceCallback se throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final String constantParam = "constant"; - Call call = service.postWithConstantInBody(constantParam, null); + final Product body = null; + Call call = service.postWithConstantInBody(constantParam, body); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 38d0bfd70ed8a..c9f8bc6faf9fa 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -222,14 +222,7 @@ public string MethodRequiredParameterApiInvocation List invocations = new List(); foreach (var parameter in OrderedRetrofitParameters) { - if (parameter.IsRequired) - { - invocations.Add(parameter.WireName); - } - else - { - invocations.Add(parameter.WireType.DefaultValue); - } + invocations.Add(parameter.WireName); } var declaration = string.Join(", ", invocations); @@ -276,12 +269,7 @@ public string RequiredParameterConversion public virtual string BuildInputMappings(bool filterRequired = false) { var builder = new IndentedStringBuilder(); - var transformations = InputParameterTransformation; - if (filterRequired) - { - transformations = transformations.Where(t => t.OutputParameter.IsRequired).ToList(); - } - foreach (var transformation in transformations) + foreach (var transformation in InputParameterTransformation) { var nullCheck = BuildNullCheckExpression(transformation); bool conditionalAssignment = !string.IsNullOrEmpty(nullCheck) && !transformation.OutputParameter.IsRequired && !filterRequired; @@ -302,18 +290,24 @@ public virtual string BuildInputMappings(bool filterRequired = false) transformation.OutputParameter.Type.Name); } - var mappings = transformation.ParameterMappings; - if (filterRequired) + foreach (var mapping in transformation.ParameterMappings) { - mappings = mappings.Where(m => m.InputParameter.IsRequired).ToList(); - } - foreach (var mapping in mappings) - { - builder.AppendLine("{0}{1}{2};", - !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? - ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "", - transformation.OutputParameter.Name, - GetMapping(mapping)); + if (filterRequired && !mapping.InputParameter.IsRequired) + { + builder.AppendLine("{0}{1}{2};", + !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? + ((ParameterModel)transformation.OutputParameter).WireType + " " : "", + ((ParameterModel)transformation.OutputParameter).WireName, + " = " + ((ParameterModel)transformation.OutputParameter).WireType.DefaultValue(this)); + } + else + { + builder.AppendLine("{0}{1}{2};", + !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? + ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "", + transformation.OutputParameter.Name, + GetMapping(mapping)); + } } if (conditionalAssignment) diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index 68770ed199c52..10c86bd6adb4f 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -47,6 +47,10 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth } @foreach (ParameterModel parameter in Model.LocalParameters) { + if (!parameter.IsRequired) + { +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); + } if (parameter.IsConstant) { @: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); @@ -104,6 +108,10 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @foreach (ParameterModel parameter in Model.LocalParameters) { + if (!parameter.IsRequired) + { +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); + } if (parameter.IsConstant) { @: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); diff --git a/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs index c2d1e30a0faf3..af29a8cac8361 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs @@ -62,12 +62,9 @@ public ITypeModel ResponseVariant } } - public string DefaultValue + public string DefaultValue(MethodTemplateModel method) { - get - { - return "null"; - } + return "null"; } public IEnumerable Imports diff --git a/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs index 7fbf65406e1f3..7ed8f673b5a69 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs @@ -57,12 +57,9 @@ public ITypeModel ResponseVariant } } - public string DefaultValue + public string DefaultValue(MethodTemplateModel method) { - get - { - return "null"; - } + return "null"; } public IEnumerable Imports diff --git a/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs index 25df159a7f12a..96e5d3bc91dd4 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs @@ -37,12 +37,9 @@ public ITypeModel ResponseVariant } } - public string DefaultValue + public string DefaultValue(MethodTemplateModel method) { - get - { - return "null"; - } + return "null"; } public IEnumerable Imports diff --git a/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs index dbc95f16f2cbb..5ea54b1303f0f 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs @@ -11,8 +11,6 @@ namespace Microsoft.Rest.Generator.Java { public interface ITypeModel : IType { - string DefaultValue { get; } - ITypeModel ParameterVariant { get; } ITypeModel ResponseVariant { get; } @@ -20,5 +18,7 @@ public interface ITypeModel : IType IEnumerable Imports { get; } ITypeModel InstanceType(); + + string DefaultValue(MethodTemplateModel method); } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs index 892c4abc0b28d..78d7eaab50494 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs @@ -32,27 +32,28 @@ public PrimaryTypeModel(PrimaryType primaryType) Initialize(primaryType); } - public string DefaultValue + public string DefaultValue(MethodTemplateModel method) { - get + if (this.Name == "byte[]") { - if (this.Name == "byte[]") - { - return "new byte[0]"; - } - else if (this.Name == "Byte[]") - { - return "new Byte[0]"; - } - else if (this.IsInstanceType) - // instance type - { - return "null"; - } - else - { - throw new NotSupportedException(this.Name + " does not have default value!"); - } + return "new byte[0]"; + } + else if (this.Name == "Byte[]") + { + return "new Byte[0]"; + } + else if (this.Name == "RequestBody") + { + return "RequestBody.create(MediaType.parse(\"" + method.RequestContentType + "\"), new byte[0])"; + } + else if (this.IsInstanceType) + // instance type + { + return "null"; + } + else + { + throw new NotSupportedException(this.Name + " does not have default value!"); } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs index cd24f114945b0..4434768c17cff 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs @@ -62,12 +62,9 @@ public ITypeModel ResponseVariant } } - public string DefaultValue + public string DefaultValue(MethodTemplateModel method) { - get - { - return "null"; - } + return "null"; } public IEnumerable Imports From 107c6c9c16baf3c529c20d9c7f6fc77f2162f8ec Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 30 Mar 2016 11:39:56 -0700 Subject: [PATCH 62/99] Add null checks to optional flattened wire parameters --- .../Java/TypeModels/CompositeTypeModel.cs | 2 +- .../Java/TypeModels/DictionaryTypeModel.cs | 2 +- .../Java/Java/TypeModels/EnumTypeModel.cs | 2 +- .../Java/Java/TypeModels/ITypeModel.cs | 2 +- .../Java/Java/TypeModels/ParameterModel.cs | 48 ++++++++++++++++--- .../Java/Java/TypeModels/PrimaryTypeModel.cs | 2 +- .../Java/Java/TypeModels/SequenceTypeModel.cs | 2 +- 7 files changed, 47 insertions(+), 13 deletions(-) diff --git a/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs index af29a8cac8361..dae1d8ad4df3a 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs @@ -62,7 +62,7 @@ public ITypeModel ResponseVariant } } - public string DefaultValue(MethodTemplateModel method) + public string DefaultValue(Method method) { return "null"; } diff --git a/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs index 7ed8f673b5a69..f471e1783b919 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs @@ -57,7 +57,7 @@ public ITypeModel ResponseVariant } } - public string DefaultValue(MethodTemplateModel method) + public string DefaultValue(Method method) { return "null"; } diff --git a/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs index 96e5d3bc91dd4..aec50e5773d40 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs @@ -37,7 +37,7 @@ public ITypeModel ResponseVariant } } - public string DefaultValue(MethodTemplateModel method) + public string DefaultValue(Method method) { return "null"; } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs index 5ea54b1303f0f..5310d7dcba3bf 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs @@ -19,6 +19,6 @@ public interface ITypeModel : IType ITypeModel InstanceType(); - string DefaultValue(MethodTemplateModel method); + string DefaultValue(Method method); } } diff --git a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs index 6c8ad4d8bd0b2..9dbfeca84a50d 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs @@ -107,40 +107,74 @@ private string convertClientTypeToWireType(ITypeModel wireType, string source, s IndentedStringBuilder builder = new IndentedStringBuilder(); if (wireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { - builder.AppendLine("DateTimeRfc1123 {0} = new DateTimeRfc1123({1});", target, source); + if (!IsRequired) + { + builder.AppendLine("DateTimeRfc1123 {0} = {1};", target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } + builder.AppendLine("{0}{1} = new DateTimeRfc1123({2});", IsRequired ? "DateTimeRfc1123 " : "", target, source); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } } else if (wireType.IsPrimaryType(KnownPrimaryType.Stream)) { - builder.AppendLine("RequestBody {0} = RequestBody.create(MediaType.parse(\"{1}\"), {2});", - target, _method.RequestContentType, source); + if (!IsRequired) + { + builder.AppendLine("RequestBody {0} = {1};", target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } + builder.AppendLine("{0}{1} = RequestBody.create(MediaType.parse(\"{2}\"), {3});", + IsRequired ? "RequestBody " : "", target, _method.RequestContentType, source); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } } else if (wireType is SequenceTypeModel) { + if (!IsRequired) + { + builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } var sequenceType = wireType as SequenceTypeModel; var elementType = sequenceType.ElementTypeModel; var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); - builder.AppendLine("{0} {1} = new ArrayList<{2}>();", wireType.Name ,target, elementType.Name) + builder.AppendLine("{0}{1} = new ArrayList<{2}>();", IsRequired ? wireType.Name + " " : "" ,target, elementType.Name) .AppendLine("for ({0} {1} : {2}) {{", elementType.ParameterVariant.Name, itemName, source) .Indent().AppendLine(convertClientTypeToWireType(elementType, itemName, itemTarget, clientReference, level + 1)) .AppendLine("{0}.add({1});", target, itemTarget) .Outdent().Append("}"); _implImports.Add("java.util.ArrayList"); - return builder.ToString(); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } } else if (wireType is DictionaryTypeModel) { + if (!IsRequired) + { + builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } var dictionaryType = wireType as DictionaryTypeModel; var valueType = dictionaryType.ValueTypeModel; var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); - builder.AppendLine("{0} {1} = new HashMap();", wireType.Name, target, valueType.Name) + builder.AppendLine("{0}{1} = new HashMap();", IsRequired ? wireType.Name + " " : "", target, valueType.Name) .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.ParameterVariant.Name, itemName, source) .Indent().AppendLine(convertClientTypeToWireType(valueType, itemName + ".getValue()", itemTarget, clientReference, level + 1)) .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget) .Outdent().Append("}"); _implImports.Add("java.util.HashMap"); - return builder.ToString(); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } } return builder.ToString(); } diff --git a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs index 78d7eaab50494..ab8126b734de4 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs @@ -32,7 +32,7 @@ public PrimaryTypeModel(PrimaryType primaryType) Initialize(primaryType); } - public string DefaultValue(MethodTemplateModel method) + public string DefaultValue(Method method) { if (this.Name == "byte[]") { diff --git a/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs index 4434768c17cff..447818e312cf6 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs @@ -62,7 +62,7 @@ public ITypeModel ResponseVariant } } - public string DefaultValue(MethodTemplateModel method) + public string DefaultValue(Method method) { return "null"; } From 4ffe90d4c370114f5b8b571909a9450d5828b21a Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 30 Mar 2016 11:44:29 -0700 Subject: [PATCH 63/99] Re-gen and address code analysis errors --- .../Generators/Java/Azure.Java/GlobalSuppressions.cs | 11 +++++++++++ .../java/fixtures/header/HeaderOperationsImpl.java | 10 ++++++++-- AutoRest/Generators/Java/Java/GlobalSuppressions.cs | 10 ++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs index fe0a68ed70c54..1af18a4d3b35f 100644 --- a/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs @@ -43,3 +43,14 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureCompositeTypeModel.#.ctor(Microsoft.Rest.Generator.Java.CompositeTypeModel)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureJavaCodeGenerator.#.ctor(Microsoft.Rest.Generator.Settings)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureModelTemplateModel.#.ctor(Microsoft.Rest.Generator.ClientModel.CompositeType,Microsoft.Rest.Generator.ClientModel.ServiceClient)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceCallback", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getItems", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "PagingBahavior", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getNextPageLink", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ListOperationCallback", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#TransformPagingGroupedParameter(Microsoft.Rest.Generator.Utilities.IndentedStringBuilder,Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel,System.Boolean)")] diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 1df9302b58566..fb0c9f8b0db51 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -1415,7 +1415,10 @@ public ServiceResponse paramDatetimeRfc1123(String scenario, DateTime valu if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); + DateTimeRfc1123 valueConverted = null; + if (value != null) { + valueConverted = new DateTimeRfc1123(value); + } Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1437,7 +1440,10 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, DateTime value, fi serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - DateTimeRfc1123 valueConverted = new DateTimeRfc1123(value); + DateTimeRfc1123 valueConverted = null; + if (value != null) { + valueConverted = new DateTimeRfc1123(value); + } Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { diff --git a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs index 50c886c5c22d2..9273ec6f370ce 100644 --- a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs @@ -174,3 +174,13 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_implImports")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_implImports")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#convertToClientType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#BuildInputMappings(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#BuildInputMappings(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#convertClientTypeToWireType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PrimaryTypeModel.#DefaultValue(Microsoft.Rest.Generator.ClientModel.Method)")] From dd478b868264e51edf80be883024a3ad380b2c2a Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 30 Mar 2016 12:17:44 -0700 Subject: [PATCH 64/99] Add missing condition in Azure template --- .../Java/Azure.Java/Templates/AzureMethodTemplate.cshtml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index 345d975af3e30..f70fc9e4a3731 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -67,7 +67,7 @@ public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.Meth @: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() + @Model.BuildInputMappings(true) @Model.RequiredParameterConversion Response result = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation).execute(); return client.getAzureClient().@(Model.PollingMethod)(result, @Model.PollingResourceTypeArgs); @@ -117,7 +117,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() + @Model.BuildInputMappings(true) @Model.RequiredParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation); final ServiceCall serviceCall = new ServiceCall(call); From 1ec72489df7aeb901576b058601f3eaa080d0351 Mon Sep 17 00:00:00 2001 From: begoldsm Date: Wed, 30 Mar 2016 17:54:14 -0700 Subject: [PATCH 65/99] Fix test breaks. --- .../Azure.CSharp.Tests/AcceptanceTests.cs | 3 ++- .../ODataTests.cs | 21 ++++++++++++------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs index ec21cdd514493..d04c712fd1c96 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs @@ -527,7 +527,8 @@ public void AzureODataTests() Top = 10, OrderBy = "id" }; - Assert.Equal("$filter=id gt 5 and name eq 'foo'&$orderby=id&$top=10", filter.ToString()); + var filterString = Uri.EscapeDataString("id gt 5 and name eq 'foo'"); + Assert.Equal(string.Format("$filter={0}&$orderby=id&$top=10", filterString), filter.ToString()); client.Odata.GetWithFilter(filter); } } diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs index c651bbdc33621..639023af44855 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs @@ -227,6 +227,7 @@ public void EncodingTheParameters() [Fact] public void ODataQuerySupportsAllParameters() { + var queryString = "foo eq 'bar'"; var query = new ODataQuery(p => p.Foo == "bar") { Expand = "param1", @@ -234,7 +235,7 @@ public void ODataQuerySupportsAllParameters() Skip = 10, Top = 100 }; - Assert.Equal("$filter=foo eq 'bar'&$orderby=d&$expand=param1&$top=100&$skip=10", query.ToString()); + Assert.Equal(string.Format("$filter={0}&$orderby=d&$expand=param1&$top=100&$skip=10", Uri.EscapeDataString(queryString)), query.ToString()); } [Fact] @@ -259,34 +260,38 @@ public void ODataQuerySupportsEmptyState() [Fact] public void ODataQuerySupportsPartialState() { + var queryString = "foo eq 'bar'"; var query = new ODataQuery(p => p.Foo == "bar") { Top = 100 }; - Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); + Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); } [Fact] public void ODataQuerySupportsImplicitConversionFromFilterString() { - ODataQuery query = "foo eq 'bar'"; + var queryString = "foo eq 'bar'"; + ODataQuery query = queryString; query.Top = 100; - Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); + Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); } [Fact] public void ODataQuerySupportsImplicitConversionFromFullFilterString() { - ODataQuery query = "$filter=foo eq 'bar'"; + var queryString = "foo eq 'bar'"; + ODataQuery query = string.Format("$filter={0}", queryString); query.Top = 100; - Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); + Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); } [Fact] public void ODataQuerySupportsImplicitConversionFromQueryString() { - ODataQuery query = "$filter=foo eq 'bar'&$top=100"; - Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); + var queryString = "foo eq 'bar'"; + ODataQuery query = string.Format("$filter={0}&$top=100", queryString); + Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); } [Fact] From 12f4d007810637ef10770e1b4c2903ff1f605317 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Wed, 30 Mar 2016 20:43:49 -0700 Subject: [PATCH 66/99] base64Url support for node.js and inclusion of composed properties while flattening. --- .../Extensions/Extensions/Extensions.cs | 2 +- .../fixtures/bodyarray/ArrayOperations.java | 18 + .../bodyarray/ArrayOperationsImpl.java | 49 ++ .../bodydictionary/DictionaryOperations.java | 18 + .../DictionaryOperationsImpl.java | 49 ++ .../fixtures/bodystring/StringOperations.java | 75 +++ .../bodystring/StringOperationsImpl.java | 206 ++++++++ .../java/fixtures/url/PathsOperations.java | 21 + .../fixtures/url/PathsOperationsImpl.java | 59 +++ .../AcceptanceTests/acceptanceTests.ts | 65 +++ .../BodyArray/operations/arrayModel.js | 122 +++++ .../BodyArray/operations/index.d.ts | 15 + .../BodyDictionary/operations/dictionary.js | 122 +++++ .../BodyDictionary/operations/index.d.ts | 15 + .../BodyString/operations/index.d.ts | 58 +++ .../BodyString/operations/string.js | 463 ++++++++++++++++++ .../AcceptanceTests/Url/operations/index.d.ts | 16 + .../AcceptanceTests/Url/operations/paths.js | 102 ++++ .../NodeJS/NodeJS/ClientModelExtensions.cs | 8 +- .../NodeJS/NodeJS/NodeJsCodeNamer.cs | 2 +- .../operations/array.py | 45 ++ .../operations/dictionary.py | 45 ++ .../operations/string.py | 175 +++++++ .../operations/paths.py | 43 ++ AutoRest/TestServer/server/app.js | 2 +- .../NodeJS/ms-rest/lib/serialization.js | 48 ++ .../Azure.Java/models/AccountStatus.java | 5 + .../Azure.Java/models/AccountType.java | 5 + .../Azure.Java/models/ProvisioningState.java | 5 + .../Azure.Java/models/Reason.java | 5 + .../StorageAccountCreateParameters.java | 2 +- .../Azure.Java/models/UsageUnit.java | 5 + .../operations/storage_accounts_operations.py | 14 +- .../azure_storage/storage_accounts.rb | 8 +- Samples/petstore/Java/SwaggerPetstore.java | 1 - .../petstore/Java/SwaggerPetstoreImpl.java | 42 +- Samples/petstore/Java/models/Order.java | 2 +- Samples/petstore/Java/models/Pet.java | 2 +- .../Ruby/petstore/swagger_petstore.rb | 16 +- 39 files changed, 1912 insertions(+), 43 deletions(-) diff --git a/AutoRest/Generators/Extensions/Extensions/Extensions.cs b/AutoRest/Generators/Extensions/Extensions/Extensions.cs index e3e07511f3168..e974d9563af25 100644 --- a/AutoRest/Generators/Extensions/Extensions/Extensions.cs +++ b/AutoRest/Generators/Extensions/Extensions/Extensions.cs @@ -201,7 +201,7 @@ private static IEnumerable FlattenProperty(Property propertyToFlatten, } List extractedProperties = new List(); - foreach (Property innerProperty in typeToFlatten.Properties) + foreach (Property innerProperty in typeToFlatten.ComposedProperties) { Debug.Assert(typeToFlatten.SerializedName != null); Debug.Assert(innerProperty.SerializedName != null); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java index 5a78a5b4f48e5..e37c6c2725986 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java @@ -895,6 +895,24 @@ public interface ArrayOperations { */ ServiceCall getByteInvalidNullAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** + * Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the List<String> object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse> getBase64Url() throws ErrorException, IOException; + + /** + * Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** * Get array of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java index f0286e8f8435f..01f53ca7948f2 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java @@ -247,6 +247,10 @@ interface ArrayService { @GET("array/prim/byte/invalidnull") Call getByteInvalidNull(); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("array/prim/base64url/valid") + Call getBase64Url(); + @Headers("Content-Type: application/json; charset=utf-8") @GET("array/complex/null") Call getComplexNull(); @@ -2577,6 +2581,51 @@ private ServiceResponse> getByteInvalidNullDelegate(Response> getBase64Url() throws ErrorException, IOException { + Call call = service.getBase64Url(); + return getBase64UrlDelegate(call.execute()); + } + + /** + * Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64Url(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback>(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64UrlDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse> getBase64UrlDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder, ErrorException>(this.client.getMapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + /** * Get array of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java index 74450586af8c1..1fd31d6edb98a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java @@ -891,6 +891,24 @@ public interface DictionaryOperations { */ ServiceCall getByteInvalidNullAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Map<String, String> object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse> getBase64Url() throws ErrorException, IOException; + + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** * Get dictionary of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java index 9eb9216ca1d77..0dfc895dfa5e3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java @@ -246,6 +246,10 @@ interface DictionaryService { @GET("dictionary/prim/byte/invalidnull") Call getByteInvalidNull(); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("dictionary/prim/base64url/valid") + Call getBase64Url(); + @Headers("Content-Type: application/json; charset=utf-8") @GET("dictionary/complex/null") Call getComplexNull(); @@ -2564,6 +2568,51 @@ private ServiceResponse> getByteInvalidNullDelegate(Response .build(response); } + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Map<String, String> object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse> getBase64Url() throws ErrorException, IOException { + Call call = service.getBase64Url(); + return getBase64UrlDelegate(call.execute()); + } + + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64Url(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback>(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64UrlDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse> getBase64UrlDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder, ErrorException>(this.client.getMapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + /** * Get dictionary of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java index 6256d70621307..0107642a2747d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java @@ -211,4 +211,79 @@ public interface StringOperations { */ ServiceCall getNotProvidedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get value that is base64 encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getBase64Encoded() throws ErrorException, IOException; + + /** + * Get value that is base64 encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64EncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Get value that is base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getBase64UrlEncoded() throws ErrorException, IOException; + + /** + * Get value that is base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse putBase64UrlEncoded(String stringBody) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall putBase64UrlEncodedAsync(String stringBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Get null value that is expected to be base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getNullBase64UrlEncoded() throws ErrorException, IOException; + + /** + * Get null value that is expected to be base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getNullBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java index d4b1368b107ae..c4cb06e5903fe 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java @@ -89,6 +89,22 @@ interface StringService { @GET("string/notProvided") Call getNotProvided(); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("string/base64Encoding") + Call getBase64Encoded(); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("string/base64UrlEncoding") + Call getBase64UrlEncoded(); + + @Headers("Content-Type: application/json; charset=utf-8") + @PUT("string/base64UrlEncoding") + Call putBase64UrlEncoded(@Body String stringBody); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("string/nullBase64UrlEncoding") + Call getNullBase64UrlEncoded(); + } /** @@ -568,4 +584,194 @@ private ServiceResponse getNotProvidedDelegate(Response re .build(response); } + /** + * Get value that is base64 encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getBase64Encoded() throws ErrorException, IOException { + Call call = service.getBase64Encoded(); + return getBase64EncodedDelegate(call.execute()); + } + + /** + * Get value that is base64 encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64EncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64Encoded(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64EncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getBase64EncodedDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Get value that is base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getBase64UrlEncoded() throws ErrorException, IOException { + Call call = service.getBase64UrlEncoded(); + return getBase64UrlEncodedDelegate(call.execute()); + } + + /** + * Get value that is base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64UrlEncoded(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64UrlEncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getBase64UrlEncodedDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse putBase64UrlEncoded(String stringBody) throws ErrorException, IOException, IllegalArgumentException { + if (stringBody == null) { + throw new IllegalArgumentException("Parameter stringBody is required and cannot be null."); + } + Call call = service.putBase64UrlEncoded(stringBody); + return putBase64UrlEncodedDelegate(call.execute()); + } + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall putBase64UrlEncodedAsync(String stringBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (stringBody == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter stringBody is required and cannot be null.")); + return null; + } + Call call = service.putBase64UrlEncoded(stringBody); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(putBase64UrlEncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse putBase64UrlEncodedDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Get null value that is expected to be base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getNullBase64UrlEncoded() throws ErrorException, IOException { + Call call = service.getNullBase64UrlEncoded(); + return getNullBase64UrlEncodedDelegate(call.execute()); + } + + /** + * Get null value that is expected to be base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getNullBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getNullBase64UrlEncoded(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getNullBase64UrlEncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getNullBase64UrlEncodedDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java index cbf2ea2bd0265..411448cebeac1 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 @@ -459,4 +459,25 @@ public interface PathsOperations { */ ServiceCall dateTimeNullAsync(DateTime dateTimePath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse base64Url(String base64UrlPath) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall base64UrlAsync(String base64UrlPath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + } 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 fd3dc3f930d9c..a760f773578ad 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 @@ -148,6 +148,10 @@ interface PathsService { @GET("paths/datetime/null/{dateTimePath}") Call dateTimeNull(@Path("dateTimePath") DateTime dateTimePath); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("paths/string/bG9yZW0/{base64UrlPath}") + Call base64Url(@Path("base64UrlPath") String base64UrlPath); + } /** @@ -1293,4 +1297,59 @@ private ServiceResponse dateTimeNullDelegate(Response respon .build(response); } + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse base64Url(String base64UrlPath) throws ErrorException, IOException, IllegalArgumentException { + if (base64UrlPath == null) { + throw new IllegalArgumentException("Parameter base64UrlPath is required and cannot be null."); + } + Call call = service.base64Url(base64UrlPath); + return base64UrlDelegate(call.execute()); + } + + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall base64UrlAsync(String base64UrlPath, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (base64UrlPath == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter base64UrlPath is required and cannot be null.")); + return null; + } + Call call = service.base64Url(base64UrlPath); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(base64UrlDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse base64UrlDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + } diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index 66a8cbc2da740..58c4709ef6799 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts @@ -428,6 +428,37 @@ describe('nodejs', function () { done(); }); }); + + it('should correctly deserialize base64 encoded string', function (done) { + testClient.string.getBase64Encoded(function (error, result) { + should.not.exist(error); + should.exist(result); + result.toString('utf8').should.equal('a string that gets encoded with base64'); + done(); + }); + }); + + it('should correctly handle null base64url encoded string', function (done) { + testClient.string.getNullBase64UrlEncoded(function (error, result) { + should.not.exist(error); + should.not.exist(result); + done(); + }); + }); + + it('should correctly serialize and deserialize base64url encoded string', function (done) { + testClient.string.getBase64UrlEncoded(function (error, result) { + should.not.exist(error); + should.exist(result); + result.toString('utf8').should.equal('a string that gets encoded with base64url'); + var buff = new Buffer('a string that gets encoded with base64url', 'utf8'); + testClient.string.putBase64UrlEncoded(buff, function (error, result) { + should.not.exist(error); + should.not.exist(result); + done(); + }); + }); + }); }); describe('Byte Client', function () { @@ -911,6 +942,19 @@ describe('nodejs', function () { }); }); + it('should get base64url arrays', function (done) { + var base64Url1 = new Buffer('a string that gets encoded with base64url', 'utf8'); + var base64Url2 = new Buffer('test string', 'utf8'); + var base64Url3 = new Buffer('Lorem ipsum', 'utf8'); + var arr = [base64Url1, base64Url2, base64Url3]; + testClient.arrayModel.getBase64Url(function (error, result) { + should.not.exist(error); + should.exist(result); + assert.deepEqual(result, arr); + done(); + }); + }); + it('should get and put boolean arrays', function (done) { var boolArray = [true, false, false, true]; testClient.arrayModel.getBooleanTfft(function (error, result) { @@ -1293,6 +1337,18 @@ describe('nodejs', function () { }); }); + it('should get base64url dictionaries', function (done) { + var base64Url1 = new Buffer('a string that gets encoded with base64url', 'utf8'); + var base64Url2 = new Buffer('test string', 'utf8'); + var base64Url3 = new Buffer('Lorem ipsum', 'utf8'); + var dict: { [propertyName: string]: Buffer } = { "0": base64Url1, "1": base64Url2, "2": base64Url3 }; + testClient.dictionary.getBase64Url(function (error, result) { + should.not.exist(error); + assert.deepEqual(result, dict); + done(); + }); + }); + it('should get and put boolean dictionaries', function (done) { var boolDictionary: { [propertyName: string]: boolean } = { "0": true, "1": false, "2": false, "3": true }; testClient.dictionary.getBooleanTfft(function (error, result) { @@ -1797,6 +1853,7 @@ describe('nodejs', function () { }); }); }); + it('should work when path has string', function (done) { testClient.paths.stringEmpty('', function (error, result) { should.not.exist(error); @@ -1810,6 +1867,14 @@ describe('nodejs', function () { }); }); + it.skip('should work when path has base64url encoded string', function (done) { + testClient.paths.base64Url(new Buffer('lorem', 'utf8'), function (error, result) { + should.not.exist(error); + should.not.exist(result); + done(); + }); + }); + it('should work when path has datetime', function (done) { testClient.paths.dateTimeValid(new Date('2012-01-01T01:01:01Z'), function (error, result) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js index bd4bb202801cd..3718eebb86cc3 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js @@ -5765,6 +5765,128 @@ ArrayModel.prototype.getByteInvalidNull = function (options, callback) { }); }; +/** + * Get array value ['a string that gets encoded with base64url', 'test string' + * 'Lorem ipsum'] with the items base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {array} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +ArrayModel.prototype.getBase64Url = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//array/prim/base64url/valid'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Sequence', + element: { + required: false, + serializedName: 'BufferElementType', + type: { + name: 'Base64Url' + } + } + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + /** * Get array of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts index 76f9a3ab41aee..b09e78940d731 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts @@ -702,6 +702,21 @@ export interface ArrayModel { getByteInvalidNull(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; getByteInvalidNull(callback: ServiceCallback): void; + /** + * Get array value ['a string that gets encoded with base64url', 'test string' + * 'Lorem ipsum'] with the items base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64Url(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getBase64Url(callback: ServiceCallback): void; + /** * Get array of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js index cc8188335cd97..0ca951fc9f28c 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js @@ -5753,6 +5753,128 @@ Dictionary.prototype.getByteInvalidNull = function (options, callback) { }); }; +/** + * Get base64url dictionary value {"0": "a string that gets encoded with + * base64url", "1": "test string", "2": "Lorem ipsum"} + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {object} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Dictionary.prototype.getBase64Url = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//dictionary/prim/base64url/valid'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Dictionary', + value: { + required: false, + serializedName: 'BufferElementType', + type: { + name: 'Base64Url' + } + } + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + /** * Get dictionary of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts index 22de054220cd9..45d1abe7996dc 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts @@ -700,6 +700,21 @@ export interface Dictionary { getByteInvalidNull(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; getByteInvalidNull(callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; + /** + * Get base64url dictionary value {"0": "a string that gets encoded with + * base64url", "1": "test string", "2": "Lorem ipsum"} + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64Url(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; + getBase64Url(callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; + /** * Get dictionary of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts index 387cdc5e61570..1d5e9935b6520 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts @@ -161,6 +161,64 @@ export interface String { */ getNotProvided(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; getNotProvided(callback: ServiceCallback): void; + + /** + * Get value that is base64 encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64Encoded(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getBase64Encoded(callback: ServiceCallback): void; + + /** + * Get value that is base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64UrlEncoded(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getBase64UrlEncoded(callback: ServiceCallback): void; + + /** + * Put value that is base64url encoded + * + * @param {buffer} stringBody + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + putBase64UrlEncoded(stringBody: Buffer, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + putBase64UrlEncoded(stringBody: Buffer, callback: ServiceCallback): void; + + /** + * Get null value that is expected to be base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getNullBase64UrlEncoded(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getNullBase64UrlEncoded(callback: ServiceCallback): void; } /** diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js index a17875013063e..eb0c1554c2764 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js @@ -1091,5 +1091,468 @@ String.prototype.getNotProvided = function (options, callback) { }); }; +/** + * Get value that is base64 encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {buffer} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.getBase64Encoded = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/base64Encoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Base64Url' + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Get value that is base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {buffer} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.getBase64UrlEncoded = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/base64UrlEncoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Base64Url' + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Put value that is base64url encoded + * + * @param {buffer} stringBody + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.putBase64UrlEncoded = function (stringBody, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + // Validate + try { + if (!Buffer.isBuffer(stringBody)) { + throw new Error('stringBody cannot be null or undefined and it must be of type buffer.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/base64UrlEncoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'PUT'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + // Serialize Request + var requestContent = null; + var requestModel = null; + try { + if (stringBody !== null && stringBody !== undefined) { + var requestModelMapper = { + required: true, + serializedName: 'stringBody', + type: { + name: 'Base64Url' + } + }; + requestModel = client.serialize(requestModelMapper, stringBody, 'stringBody'); + requestContent = JSON.stringify(requestModel); + } + } catch (error) { + var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + + 'payload - "%s"', error.message, util.inspect(stringBody, {depth: null}))); + return callback(serializationError); + } + httpRequest.body = requestContent; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Get null value that is expected to be base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {buffer} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.getNullBase64UrlEncoded = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/nullBase64UrlEncoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Base64Url' + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + module.exports = String; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts index bda3709eb4178..52a74e2768063 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts @@ -360,6 +360,22 @@ export interface Paths { */ dateTimeNull(dateTimePath: Date|string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; dateTimeNull(dateTimePath: Date|string, callback: ServiceCallback): void; + + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url) + * + * @param {buffer} base64UrlPath base64url encoded value + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + base64Url(base64UrlPath: Buffer, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + base64Url(base64UrlPath: Buffer, callback: ServiceCallback): void; } /** diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js index 53af0e791fe20..6dcb63419f912 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js @@ -2247,5 +2247,107 @@ Paths.prototype.dateTimeNull = function (dateTimePath, options, callback) { }); }; +/** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url) + * + * @param {buffer} base64UrlPath base64url encoded value + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Paths.prototype.base64Url = function (base64UrlPath, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + // Validate + try { + if (!Buffer.isBuffer(base64UrlPath)) { + throw new Error('base64UrlPath cannot be null or undefined and it must be of type buffer.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//paths/string/bG9yZW0/{base64UrlPath}'; + requestUrl = requestUrl.replace('{base64UrlPath}', encodeURIComponent(base64UrlPath.toString())); + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + module.exports = Paths; diff --git a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs index 2b5e72bc5db7b..59ccc22882506 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs @@ -236,7 +236,7 @@ private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvid builder.AppendLine("if ({0} !== null && {0} !== undefined && !(typeof {0}.valueOf() === 'string' && msRest.isValidUuid({0}))) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } - else if (primary.Type == KnownPrimaryType.ByteArray) + else if (primary.Type == KnownPrimaryType.ByteArray || primary.Type == KnownPrimaryType.Base64Url) { if (isRequired) { @@ -304,7 +304,7 @@ private static string PrimaryTSType(this PrimaryType primary) return "Date"; else if (primary.Type == KnownPrimaryType.Object) return "any"; // TODO: test this - else if (primary.Type == KnownPrimaryType.ByteArray) + else if (primary.Type == KnownPrimaryType.ByteArray || primary.Type == KnownPrimaryType.Base64Url) return "Buffer"; else if (primary.Type == KnownPrimaryType.Stream) return "stream.Readable"; @@ -756,6 +756,10 @@ public static string ConstructMapper(this IType type, string serializedName, IPa { builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}"); } + else if (primary.Type == KnownPrimaryType.Base64Url) + { + builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}"); + } else if (primary.Type == KnownPrimaryType.Date) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}"); diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs index 3fdcbfb3465b1..53ac858681ef1 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs @@ -343,7 +343,7 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) if (primaryType.Type == KnownPrimaryType.Base64Url) { - primaryType.Name = "String"; + primaryType.Name = "Buffer"; } else if (primaryType.Type == KnownPrimaryType.Boolean) { diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py index 1a94ea14d19e8..1d437ec67f879 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py @@ -2053,6 +2053,51 @@ def get_byte_invalid_null( return deserialized + def get_base64_url( + self, custom_headers={}, raw=False, **operation_config): + """ + Get array value ['a string that gets encoded with base64url', 'test + string' 'Lorem ipsum'] with the items base64url encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: list of str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/array/prim/base64url/valid' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('[str]', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + def get_complex_null( self, custom_headers={}, raw=False, **operation_config): """ diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py index dbe5fd33141ad..55fd8ef1953dc 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py @@ -2058,6 +2058,51 @@ def get_byte_invalid_null( return deserialized + def get_base64_url( + self, custom_headers={}, raw=False, **operation_config): + """ + Get base64url dictionary value {"0": "a string that gets encoded with + base64url", "1": "test string", "2": "Lorem ipsum"} + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: dict + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/dictionary/prim/base64url/valid' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('{str}', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + def get_complex_null( self, custom_headers={}, raw=False, **operation_config): """ diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py index 8db69b8a580dc..5910495329f88 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py @@ -436,3 +436,178 @@ def get_not_provided( return client_raw_response return deserialized + + def get_base64_encoded( + self, custom_headers={}, raw=False, **operation_config): + """ + Get value that is base64 encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/base64Encoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('str', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + + def get_base64_url_encoded( + self, custom_headers={}, raw=False, **operation_config): + """ + Get value that is base64url encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/base64UrlEncoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('str', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + + def put_base64_url_encoded( + self, string_body, custom_headers={}, raw=False, **operation_config): + """ + Put value that is base64url encoded + + :param string_body: + :type string_body: str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/base64UrlEncoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct body + body_content = self._serialize.body(string_body, 'str') + + # Construct and send request + request = self._client.put(url, query_parameters) + response = self._client.send( + request, header_parameters, body_content, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response + + def get_null_base64_url_encoded( + self, custom_headers={}, raw=False, **operation_config): + """ + Get null value that is expected to be base64url encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/nullBase64UrlEncoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('str', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py index b8f8b973a26b6..c9b86a5a08b78 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py @@ -1026,3 +1026,46 @@ def date_time_null( if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response + + def base64_url( + self, base64_url_path, custom_headers={}, raw=False, **operation_config): + """ + Get 'lorem' encoded value as 'bG9yZW0' (base64url) + + :param base64_url_path: base64url encoded value + :type base64_url_path: str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/paths/string/bG9yZW0/{base64UrlPath}' + path_format_arguments = { + 'base64UrlPath': self._serialize.url("base64_url_path", base64_url_path, 'str') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index f1220bc06ff16..df518bfde87a1 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -195,7 +195,7 @@ var coverage = { "getStringWithLeadingAndTrailingWhitespace" : 0, "putStringWithLeadingAndTrailingWhitespace" : 0, "getStringNotProvided": 0, - /* TODO: only C# supports the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */ + /* TODO: only C# and node.js support the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */ "getStringBase64Encoded": 1, "getStringBase64UrlEncoded": 1, "putStringBase64UrlEncoded": 1, diff --git a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js index f9810f5ec7bf6..de8d0778efd92 100644 --- a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js +++ b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js @@ -78,6 +78,8 @@ exports.serialize = function (mapper, object, objectName) { payload = serializeDateTypes.call(this, mapperType, object, objectName); } else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = serializeBufferType.call(this, objectName, object); + } else if (mapperType.match(/^Base64Url$/ig) !== null) { + payload = serializeBase64UrlType.call(this, objectName, object); } else if (mapperType.match(/^Sequence$/ig) !== null) { payload = serializeSequenceType.call(this, mapper, object, objectName); } else if (mapperType.match(/^Dictionary$/ig) !== null) { @@ -338,6 +340,16 @@ function serializeBufferType(objectName, value) { return value; } +function serializeBase64UrlType(objectName, value) { + if (value !== null && value !== undefined) { + if (!Buffer.isBuffer(value)) { + throw new Error(util.format('%s must be of type Buffer.', objectName)); + } + value = bufferToBase64Url(value); + } + return value; +} + function serializeDateTypes(typeName, value, objectName) { if (value !== null && value !== undefined) { if (typeName.match(/^Date$/ig) !== null) { @@ -394,6 +406,8 @@ exports.deserialize = function (mapper, responseBody, objectName) { payload = moment.duration(responseBody); } else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = new Buffer(responseBody, 'base64'); + } else if (mapperType.match(/^Base64Url$/ig) !== null) { + payload = base64UrlToBuffer(responseBody); } else if (mapperType.match(/^Sequence$/ig) !== null) { payload = deserializeSequenceType.call(this, mapper, responseBody, objectName); } else if (mapperType.match(/^Dictionary$/ig) !== null) { @@ -547,4 +561,38 @@ function splitSerializeName(prop) { return classes; } +function bufferToBase64Url(buffer) { + if (!buffer) { + return null; + } + if (!Buffer.isBuffer(buffer)) { + throw new Error('Please provide an input of type Buffer for converting to Base64Url.'); + } + // Buffer to Base64. + var str = buffer.toString('base64'); + // Base64 to Base64Url. + return trimEnd(str, '=').replace(/\+/g, '-').replace(/\//g, '_'); +} + +function trimEnd(str, ch) { + var len = str.length; + while ((len - 1) >= 0 && str[len - 1] === ch) { + --len; + } + return str.substr(0, len); +} + +function base64UrlToBuffer(str) { + if (!str) { + return null; + } + if (str && typeof str.valueOf() !== 'string') { + throw new Error('Please provide an input of type string for converting to Buffer'); + } + // Base64Url to Base64. + str = str.replace(/\-/g, '+').replace(/\_/g, '/'); + // Base64 to Buffer. + return new Buffer(str, 'base64'); +} + exports = module.exports; \ No newline at end of file diff --git a/Samples/azure-storage/Azure.Java/models/AccountStatus.java b/Samples/azure-storage/Azure.Java/models/AccountStatus.java index 616292abb7d72..935263fada2a2 100644 --- a/Samples/azure-storage/Azure.Java/models/AccountStatus.java +++ b/Samples/azure-storage/Azure.Java/models/AccountStatus.java @@ -49,4 +49,9 @@ public static AccountStatus fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/AccountType.java b/Samples/azure-storage/Azure.Java/models/AccountType.java index 2cbd46baf78cd..8eb41907b7c13 100644 --- a/Samples/azure-storage/Azure.Java/models/AccountType.java +++ b/Samples/azure-storage/Azure.Java/models/AccountType.java @@ -58,4 +58,9 @@ public static AccountType fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/ProvisioningState.java b/Samples/azure-storage/Azure.Java/models/ProvisioningState.java index 1a60a0a9b4fc5..e3c51eac5efb4 100644 --- a/Samples/azure-storage/Azure.Java/models/ProvisioningState.java +++ b/Samples/azure-storage/Azure.Java/models/ProvisioningState.java @@ -52,4 +52,9 @@ public static ProvisioningState fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/Reason.java b/Samples/azure-storage/Azure.Java/models/Reason.java index e67cd8258a95a..d281c844c5058 100644 --- a/Samples/azure-storage/Azure.Java/models/Reason.java +++ b/Samples/azure-storage/Azure.Java/models/Reason.java @@ -49,4 +49,9 @@ public static Reason fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java b/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java index 8f8c249d078a6..975c17e4c375e 100644 --- a/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java +++ b/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java @@ -3,8 +3,8 @@ package petstore.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The parameters to provide for the account. diff --git a/Samples/azure-storage/Azure.Java/models/UsageUnit.java b/Samples/azure-storage/Azure.Java/models/UsageUnit.java index f9ffb8b0fce07..1996e58717476 100644 --- a/Samples/azure-storage/Azure.Java/models/UsageUnit.java +++ b/Samples/azure-storage/Azure.Java/models/UsageUnit.java @@ -61,4 +61,9 @@ public static UsageUnit fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py index 37991304faeee..ef19c00fbeeac 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py @@ -117,14 +117,12 @@ def create( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`StorageAccount - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`StorageAccount + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' @@ -184,6 +182,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb b/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb index 72caad2e4c328..d81d3ec1045df 100644 --- a/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb +++ b/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb @@ -80,7 +80,7 @@ def check_name_availability_async(account_name, custom_headers = nil) unless account_name.nil? account_name = StorageAccountCheckNameAvailabilityParameters.serialize_object(account_name) end - request_content = JSON.generate(account_name, quirks_mode: true) + request_content = account_name != nil ? JSON.generate(account_name, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/checkNameAvailability' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -251,7 +251,7 @@ def begin_create_async(resource_group_name, account_name, parameters, custom_hea unless parameters.nil? parameters = StorageAccountCreateParameters.serialize_object(parameters) end - request_content = JSON.generate(parameters, quirks_mode: true) + request_content = parameters != nil ? JSON.generate(parameters, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -596,7 +596,7 @@ def update_async(resource_group_name, account_name, parameters, custom_headers = unless parameters.nil? parameters = StorageAccountUpdateParameters.serialize_object(parameters) end - request_content = JSON.generate(parameters, quirks_mode: true) + request_content = parameters != nil ? JSON.generate(parameters, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -985,7 +985,7 @@ def regenerate_key_async(resource_group_name, account_name, regenerate_key, cust unless regenerate_key.nil? regenerate_key = StorageAccountRegenerateKeyParameters.serialize_object(regenerate_key) end - request_content = JSON.generate(regenerate_key, quirks_mode: true) + request_content = regenerate_key != nil ? JSON.generate(regenerate_key, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], diff --git a/Samples/petstore/Java/SwaggerPetstore.java b/Samples/petstore/Java/SwaggerPetstore.java index c69cde12b66ed..627abbb4152ed 100644 --- a/Samples/petstore/Java/SwaggerPetstore.java +++ b/Samples/petstore/Java/SwaggerPetstore.java @@ -12,7 +12,6 @@ import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceException; import com.microsoft.rest.ServiceResponse; -import java.io.InputStream; import java.io.IOException; import java.util.Map; import petstore.models.Order; diff --git a/Samples/petstore/Java/SwaggerPetstoreImpl.java b/Samples/petstore/Java/SwaggerPetstoreImpl.java index 8965397e43e74..1d8e7988a1847 100644 --- a/Samples/petstore/Java/SwaggerPetstoreImpl.java +++ b/Samples/petstore/Java/SwaggerPetstoreImpl.java @@ -21,8 +21,6 @@ import java.io.IOException; import java.util.List; import java.util.Map; -import okhttp3.MediaType; -import okhttp3.RequestBody; import okhttp3.ResponseBody; import petstore.models.Order; import petstore.models.Pet; @@ -487,7 +485,8 @@ private ServiceResponse updatePetDelegate(Response response) */ public ServiceResponse> findPetsByStatus() throws ServiceException, IOException { final List status = null; - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + Call call = service.findPetsByStatus(statusConverted); return findPetsByStatusDelegate(call.execute()); } @@ -504,7 +503,8 @@ public ServiceCall findPetsByStatusAsync(final ServiceCallback> servic throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List status = null; - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + Call call = service.findPetsByStatus(statusConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -530,7 +530,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse> findPetsByStatus(List status) throws ServiceException, IOException { Validator.validate(status); - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + Call call = service.findPetsByStatus(statusConverted); return findPetsByStatusDelegate(call.execute()); } @@ -548,7 +549,8 @@ public ServiceCall findPetsByStatusAsync(List status, final ServiceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(status, serviceCallback); - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + Call call = service.findPetsByStatus(statusConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -580,7 +582,8 @@ private ServiceResponse> findPetsByStatusDelegate(Response> findPetsByTags() throws ServiceException, IOException { final List tags = null; - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + Call call = service.findPetsByTags(tagsConverted); return findPetsByTagsDelegate(call.execute()); } @@ -597,7 +600,8 @@ public ServiceCall findPetsByTagsAsync(final ServiceCallback> serviceC throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final List tags = null; - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + Call call = service.findPetsByTags(tagsConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -623,7 +627,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse> findPetsByTags(List tags) throws ServiceException, IOException { Validator.validate(tags); - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + Call call = service.findPetsByTags(tagsConverted); return findPetsByTagsDelegate(call.execute()); } @@ -641,7 +646,8 @@ public ServiceCall findPetsByTagsAsync(List tags, final ServiceCallback< throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(tags, serviceCallback); - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + Call call = service.findPetsByTags(tagsConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -973,8 +979,9 @@ private ServiceResponse deletePetDelegate(Response response) */ public ServiceResponse uploadFile(long petId) throws ServiceException, IOException { final String additionalMetadata = null; - final InputStream file = null; - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + final byte[] file = new byte[0]; + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); return uploadFileDelegate(call.execute()); } @@ -991,8 +998,9 @@ public ServiceCall uploadFileAsync(long petId, final ServiceCallback servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final String additionalMetadata = null; - final InputStream file = null; - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + final byte[] file = new byte[0]; + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1018,7 +1026,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse uploadFile(long petId, String additionalMetadata, byte[] file) throws ServiceException, IOException { - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); return uploadFileDelegate(call.execute()); } @@ -1036,7 +1045,8 @@ public ServiceCall uploadFileAsync(long petId, String additionalMetadata, byte[] if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/Samples/petstore/Java/models/Order.java b/Samples/petstore/Java/models/Order.java index c0cf41ebe32c0..6a884a05c294b 100644 --- a/Samples/petstore/Java/models/Order.java +++ b/Samples/petstore/Java/models/Order.java @@ -3,8 +3,8 @@ package petstore.models; -import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The Order model. diff --git a/Samples/petstore/Java/models/Pet.java b/Samples/petstore/Java/models/Pet.java index 588445cd7a54f..1e172fcfe73f3 100644 --- a/Samples/petstore/Java/models/Pet.java +++ b/Samples/petstore/Java/models/Pet.java @@ -3,8 +3,8 @@ package petstore.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The Pet model. diff --git a/Samples/petstore/Ruby/petstore/swagger_petstore.rb b/Samples/petstore/Ruby/petstore/swagger_petstore.rb index ba3ac332575a2..9584898cad19a 100644 --- a/Samples/petstore/Ruby/petstore/swagger_petstore.rb +++ b/Samples/petstore/Ruby/petstore/swagger_petstore.rb @@ -68,7 +68,7 @@ def add_pet_using_byte_array_async(body = nil, custom_headers = nil) # Serialize Request request_headers['Content-Type'] = 'application/json; charset=utf-8' - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/pet' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -141,7 +141,7 @@ def add_pet_async(body = nil, custom_headers = nil) unless body.nil? body = Pet.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/pet' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -214,7 +214,7 @@ def update_pet_async(body = nil, custom_headers = nil) unless body.nil? body = Pet.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/pet' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -950,7 +950,7 @@ def place_order_async(body = nil, custom_headers = nil) unless body.nil? body = Order.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/store/order' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1204,7 +1204,7 @@ def create_user_async(body = nil, custom_headers = nil) unless body.nil? body = User.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1284,7 +1284,7 @@ def create_users_with_array_input_async(body = nil, custom_headers = nil) end body = serializedArray end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user/createWithArray' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1364,7 +1364,7 @@ def create_users_with_list_input_async(body = nil, custom_headers = nil) end body = serializedArray end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user/createWithList' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1668,7 +1668,7 @@ def update_user_async(username, body = nil, custom_headers = nil) unless body.nil? body = User.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user/{username}' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], From 73e516c63361128a016bf6d292bd132a5d2a110f Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Thu, 31 Mar 2016 11:41:53 -0700 Subject: [PATCH 67/99] Azure/azure-sdk-for-java#622: Shutdown ADAL auth executors --- .../azure/credentials/ApplicationTokenCredentials.java | 6 +++++- .../microsoft/azure/credentials/UserTokenCredentials.java | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java index a50faee9cf16a..3e995fb06a087 100644 --- a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java +++ b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java @@ -13,6 +13,7 @@ import com.microsoft.rest.credentials.TokenCredentials; import java.io.IOException; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** @@ -103,7 +104,8 @@ public void refreshToken() throws IOException { private void acquireAccessToken() throws IOException { String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); try { authenticationResult = context.acquireToken( this.getEnvironment().getTokenAudience(), @@ -111,6 +113,8 @@ private void acquireAccessToken() throws IOException { null).get(); } catch (Exception e) { throw new IOException(e.getMessage(), e); + } finally { + executor.shutdown(); } } } diff --git a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java index 995f32fabc4a1..af02c07507b74 100644 --- a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java +++ b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java @@ -13,6 +13,7 @@ import java.io.IOException; import java.util.Date; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** @@ -146,7 +147,8 @@ private void acquireAccessToken() throws IOException { private void acquireAccessTokenFromRefreshToken() throws IOException { String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); try { authenticationResult = context.acquireTokenByRefreshToken( authenticationResult.getRefreshToken(), @@ -154,6 +156,8 @@ private void acquireAccessTokenFromRefreshToken() throws IOException { null, null).get(); } catch (Exception e) { throw new IOException(e.getMessage(), e); + } finally { + executor.shutdown(); } } } From afd67f1955c3eeda0ba437db8b47c0437ed6145c Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Fri, 1 Apr 2016 17:48:59 -0700 Subject: [PATCH 68/99] added test for flattening generic properties of a model to be flattened * added test for flattening generic properties of a model to be flattened * regenerated java after merging from upstream * regen java * corrected C# java python tests * corrected C# java python tests * java test --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 5 +- .../AutoRestResourceFlatteningTestService.cs | 17 +++++-- ...ResourceFlatteningTestServiceExtensions.cs | 14 ++++-- .../IAutoRestResourceFlatteningTestService.cs | 5 +- .../Models/FlattenParameterGroup.cs | 9 +++- .../ModelFlattening/Models/GenericUrl.cs | 43 ++++++++++++++++ .../ModelFlattening/Models/SimpleProduct.cs | 9 +++- ...AutoRestResourceFlatteningTestService.java | 6 ++- ...RestResourceFlatteningTestServiceImpl.java | 24 ++++++--- .../models/FlattenParameterGroup.java | 24 +++++++++ .../modelflattening/models/GenericUrl.java | 43 ++++++++++++++++ .../modelflattening/models/SimpleProduct.java | 24 +++++++++ .../modelflattening/ModelFlatteningTests.java | 3 +- .../AcceptanceTests/modelFlattening.ts | 3 +- ...autoRestResourceFlatteningTestService.d.ts | 8 ++- .../autoRestResourceFlatteningTestService.js | 24 ++++++++- .../models/flattenParameterGroup.js | 8 +++ .../ModelFlattening/models/genericUrl.js | 50 +++++++++++++++++++ .../ModelFlattening/models/index.d.ts | 18 +++++++ .../ModelFlattening/models/index.js | 1 + .../ModelFlattening/models/simpleProduct.js | 9 ++++ .../AcceptanceTests/model_flattening_tests.py | 5 +- ...o_rest_resource_flattening_test_service.py | 15 ++++-- .../models/__init__.py | 2 + .../models/flatten_parameter_group.py | 5 +- .../models/generic_url.py | 28 +++++++++++ .../models/simple_product.py | 6 ++- .../TestServer/server/routes/model-flatten.js | 23 ++++++--- .../TestServer/swagger/model-flattening.json | 10 ++++ .../petstore/Java/SwaggerPetstoreImpl.java | 28 +++++------ 30 files changed, 414 insertions(+), 55 deletions(-) create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/GenericUrl.cs create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/GenericUrl.java create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/genericUrl.js create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 5646edbaa40f2..962a146c40337 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -2184,7 +2184,8 @@ public void ModelFlatteningSimpleTest() Description = "product description", ProductId = "123", MaxProductDisplayName = "max name", - Odatavalue = "http://foo" + Odatavalue = "http://foo", + GenericValue = "https://generic" }; var resultProduct = client.PutSimpleProduct(simpleProduct); Assert.Equal(JsonConvert.SerializeObject(resultProduct), JsonConvert.SerializeObject(simpleProduct)); @@ -2204,7 +2205,7 @@ public void ModelFlatteningWithParameterFlatteningTest() MaxProductDisplayName = "max name", Odatavalue = "http://foo" }; - var resultProduct = client.PostFlattenedSimpleProduct("123", "max name", "product description", "http://foo"); + var resultProduct = client.PostFlattenedSimpleProduct("123", "max name", "product description", null, "http://foo"); Assert.Equal(JsonConvert.SerializeObject(resultProduct), JsonConvert.SerializeObject(simpleProduct)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs index 36bd84b559bd8..507c54acd120f 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs @@ -984,6 +984,9 @@ private void Initialize() /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// @@ -996,7 +999,7 @@ private void Initialize() /// /// A response object containing the response body and response headers. /// - public async Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (productId == null) { @@ -1007,12 +1010,13 @@ private void Initialize() throw new ValidationException(ValidationRules.CannotBeNull, "maxProductDisplayName"); } SimpleProduct simpleBodyProduct = default(SimpleProduct); - if (productId != null || description != null || maxProductDisplayName != null || odatavalue != null) + if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing @@ -1172,18 +1176,24 @@ private void Initialize() { maxProductDisplayName = flattenParameterGroup.MaxProductDisplayName; } + string genericValue = default(string); + if (flattenParameterGroup != null) + { + genericValue = flattenParameterGroup.GenericValue; + } string odatavalue = default(string); if (flattenParameterGroup != null) { odatavalue = flattenParameterGroup.Odatavalue; } SimpleProduct simpleBodyProduct = default(SimpleProduct); - if (productId != null || description != null || maxProductDisplayName != null || odatavalue != null) + if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing @@ -1197,6 +1207,7 @@ private void Initialize() tracingParameters.Add("productId", productId); tracingParameters.Add("description", description); tracingParameters.Add("maxProductDisplayName", maxProductDisplayName); + tracingParameters.Add("genericValue", genericValue); tracingParameters.Add("odatavalue", odatavalue); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs index 89debcadba39f..d2ab8e3efe09e 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs @@ -249,12 +249,15 @@ public static ResourceCollection GetResourceCollection(this IAutoRestResourceFla /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// - public static SimpleProduct PostFlattenedSimpleProduct(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string)) + public static SimpleProduct PostFlattenedSimpleProduct(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) { - return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PostFlattenedSimpleProductAsync(productId, maxProductDisplayName, description, odatavalue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PostFlattenedSimpleProductAsync(productId, maxProductDisplayName, description, genericValue, odatavalue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// @@ -274,15 +277,18 @@ public static ResourceCollection GetResourceCollection(this IAutoRestResourceFla /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// /// /// The cancellation token. /// - public static async Task PostFlattenedSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string), CancellationToken cancellationToken = default(CancellationToken)) + public static async Task PostFlattenedSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), CancellationToken cancellationToken = default(CancellationToken)) { - using (var _result = await operations.PostFlattenedSimpleProductWithHttpMessagesAsync(productId, maxProductDisplayName, description, odatavalue, null, cancellationToken).ConfigureAwait(false)) + using (var _result = await operations.PostFlattenedSimpleProductWithHttpMessagesAsync(productId, maxProductDisplayName, description, genericValue, odatavalue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs index c2b0e8724c57e..e7cdeadf98fdc 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs @@ -142,6 +142,9 @@ public partial interface IAutoRestResourceFlatteningTestService : IDisposable /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// @@ -151,7 +154,7 @@ public partial interface IAutoRestResourceFlatteningTestService : IDisposable /// /// The cancellation token. /// - Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// /// Put Simple Product with client flattening true on the model diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs index 315e5db4ea53f..db9785813c55c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs @@ -29,12 +29,13 @@ public FlattenParameterGroup() { } /// /// Initializes a new instance of the FlattenParameterGroup class. /// - public FlattenParameterGroup(string name, string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string)) + public FlattenParameterGroup(string name, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) { Name = name; ProductId = productId; Description = description; MaxProductDisplayName = maxProductDisplayName; + GenericValue = genericValue; Odatavalue = odatavalue; } @@ -64,6 +65,12 @@ public FlattenParameterGroup() { } [JsonProperty(PropertyName = "")] public string MaxProductDisplayName { get; set; } + /// + /// Generic URL value. + /// + [JsonProperty(PropertyName = "")] + public string GenericValue { get; set; } + /// /// URL value. /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/GenericUrl.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/GenericUrl.cs new file mode 100644 index 0000000000000..309028eb12669 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/GenericUrl.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsModelFlattening.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + /// + /// The Generic URL. + /// + public partial class GenericUrl + { + /// + /// Initializes a new instance of the GenericUrl class. + /// + public GenericUrl() { } + + /// + /// Initializes a new instance of the GenericUrl class. + /// + public GenericUrl(string genericValue = default(string)) + { + GenericValue = genericValue; + } + + /// + /// Generic URL value. + /// + [JsonProperty(PropertyName = "generic_value")] + public string GenericValue { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs index 4c69296ee9335..5ee2fa897a5ea 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs @@ -29,10 +29,11 @@ public SimpleProduct() { } /// /// Initializes a new instance of the SimpleProduct class. /// - public SimpleProduct(string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string)) + public SimpleProduct(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) : base(productId, description) { MaxProductDisplayName = maxProductDisplayName; + GenericValue = genericValue; Odatavalue = odatavalue; } /// @@ -49,6 +50,12 @@ static SimpleProduct() [JsonProperty(PropertyName = "details.max_product_display_name")] public string MaxProductDisplayName { get; set; } + /// + /// Generic URL value. + /// + [JsonProperty(PropertyName = "details.max_product_image.generic_value")] + public string GenericValue { get; set; } + /// /// URL value. /// diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java index 9cceedd84c296..f9141d25e0048 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java @@ -290,13 +290,14 @@ public interface AutoRestResourceFlatteningTestService { * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the SimpleProduct object wrapped in {@link ServiceResponse} if successful. */ - ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String odatavalue) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue) throws ErrorException, IOException, IllegalArgumentException; /** * Put Flattened Simple Product with client flattening true on the parameter. @@ -304,12 +305,13 @@ public interface AutoRestResourceFlatteningTestService { * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Put Simple Product with client flattening true on the model. diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java index 425c76ba3ada8..6a92545776db8 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java @@ -670,12 +670,14 @@ public ServiceResponse postFlattenedSimpleProduct(String productI throw new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null."); } final String description = null; + final String genericValue = null; final String odatavalue = null; SimpleProduct simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct = null; simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); simpleBodyProduct = null; + simpleBodyProduct = null; Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); return postFlattenedSimpleProductDelegate(call.execute()); } @@ -702,12 +704,14 @@ public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxP return null; } final String description = null; + final String genericValue = null; final String odatavalue = null; SimpleProduct simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct = null; simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); simpleBodyProduct = null; + simpleBodyProduct = null; Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -729,13 +733,14 @@ public void onResponse(Call call, Response response) * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the SimpleProduct object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String odatavalue) throws ErrorException, IOException, IllegalArgumentException { + public ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue) throws ErrorException, IOException, IllegalArgumentException { if (productId == null) { throw new IllegalArgumentException("Parameter productId is required and cannot be null."); } @@ -743,11 +748,12 @@ public ServiceResponse postFlattenedSimpleProduct(String productI throw new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null."); } SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); @@ -760,12 +766,13 @@ public ServiceResponse postFlattenedSimpleProduct(String productI * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } @@ -778,11 +785,12 @@ public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxP return null; } SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); @@ -825,13 +833,15 @@ public ServiceResponse putSimpleProductWithGrouping(FlattenParame String productId = flattenParameterGroup.getProductId(); String description = flattenParameterGroup.getDescription(); String maxProductDisplayName = flattenParameterGroup.getMaxProductDisplayName(); + String genericValue = flattenParameterGroup.getGenericValue(); String odatavalue = flattenParameterGroup.getOdatavalue(); SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.putSimpleProductWithGrouping(name, simpleBodyProduct); @@ -859,13 +869,15 @@ public ServiceCall putSimpleProductWithGroupingAsync(FlattenParameterGroup flatt String productId = flattenParameterGroup.getProductId(); String description = flattenParameterGroup.getDescription(); String maxProductDisplayName = flattenParameterGroup.getMaxProductDisplayName(); + String genericValue = flattenParameterGroup.getGenericValue(); String odatavalue = flattenParameterGroup.getOdatavalue(); SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.putSimpleProductWithGrouping(name, simpleBodyProduct); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java index a5c0ba649ee3a..342b622a71f03 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java @@ -44,6 +44,12 @@ public class FlattenParameterGroup { @JsonProperty(value = "", required = true) private String maxProductDisplayName; + /** + * Generic URL value. + */ + @JsonProperty(value = "") + private String genericValue; + /** * URL value. */ @@ -122,6 +128,24 @@ public void setMaxProductDisplayName(String maxProductDisplayName) { this.maxProductDisplayName = maxProductDisplayName; } + /** + * Get the genericValue value. + * + * @return the genericValue value + */ + public String getGenericValue() { + return this.genericValue; + } + + /** + * Set the genericValue value. + * + * @param genericValue the genericValue value to set + */ + public void setGenericValue(String genericValue) { + this.genericValue = genericValue; + } + /** * Get the odatavalue value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/GenericUrl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/GenericUrl.java new file mode 100644 index 0000000000000..b5247b4e2b157 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/GenericUrl.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.modelflattening.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The Generic URL. + */ +public class GenericUrl { + /** + * Generic URL value. + */ + @JsonProperty(value = "generic_value") + private String genericValue; + + /** + * Get the genericValue value. + * + * @return the genericValue value + */ + public String getGenericValue() { + return this.genericValue; + } + + /** + * Set the genericValue value. + * + * @param genericValue the genericValue value to set + */ + public void setGenericValue(String genericValue) { + this.genericValue = genericValue; + } + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java index 1ec1bcacbffa8..aad8d564f6c53 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java @@ -30,6 +30,12 @@ public class SimpleProduct extends BaseProduct { @JsonProperty(value = "details.max_product_capacity", required = true) private String capacity; + /** + * Generic URL value. + */ + @JsonProperty(value = "details.max_product_image.generic_value") + private String genericValue; + /** * URL value. */ @@ -79,6 +85,24 @@ public void setCapacity(String capacity) { this.capacity = capacity; } + /** + * Get the genericValue value. + * + * @return the genericValue value + */ + public String getGenericValue() { + return this.genericValue; + } + + /** + * Set the genericValue value. + * + * @param genericValue the genericValue value to set + */ + public void setGenericValue(String genericValue) { + this.genericValue = genericValue; + } + /** * Get the odatavalue value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java index 8e72c306543b6..5472617de5b5a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java @@ -204,6 +204,7 @@ public void putSimpleProduct() throws Exception { simpleProduct.setMaxProductDisplayName("max name"); simpleProduct.setCapacity("Large"); simpleProduct.setOdatavalue("http://foo"); + simpleProduct.setGenericValue("https://generic"); SimpleProduct product = client.putSimpleProduct(simpleProduct).getBody(); assertSimpleProductEquals(simpleProduct, product); @@ -217,7 +218,7 @@ public void postFlattenedSimpleProduct() throws Exception { simpleProduct.setMaxProductDisplayName("max name"); simpleProduct.setCapacity("Large"); simpleProduct.setOdatavalue("http://foo"); - client.postFlattenedSimpleProduct("123", "max name", "product description", "http://foo"); + client.postFlattenedSimpleProduct("123", "max name", "product description", null, "http://foo"); } @Test diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts index d0d27d37d3324..46d5db6758604 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts @@ -188,7 +188,8 @@ describe('nodejs', function () { productId: "123", description: "product description", maxProductDisplayName: "max name", - odatavalue: "http://foo" + odatavalue: "http://foo", + genericValue: "https://generic" }; testClient.putSimpleProduct({ simpleBodyProduct: resourceBody }, function (error, result) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts index 5fddcc86f30e4..1435eb6ff6c54 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts @@ -152,6 +152,8 @@ declare class AutoRestResourceFlatteningTestService { * @param {string} [options.simpleBodyProduct.maxProductDisplayName] Display * name of product. * + * @param {string} [options.simpleBodyProduct.genericValue] Generic URL value. + * * @param {string} [options.simpleBodyProduct.odatavalue] URL value. * * @param {string} [options.simpleBodyProduct.productId] Unique identifier @@ -184,6 +186,8 @@ declare class AutoRestResourceFlatteningTestService { * * @param {string} [options.description] Description of product. * + * @param {string} [options.genericValue] Generic URL value. + * * @param {string} [options.odatavalue] URL value. * * @param {object} [options.customHeaders] Headers that will be added to the @@ -192,7 +196,7 @@ declare class AutoRestResourceFlatteningTestService { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - postFlattenedSimpleProduct(productId: string, maxProductDisplayName: string, options: { description? : string, odatavalue? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + postFlattenedSimpleProduct(productId: string, maxProductDisplayName: string, options: { description? : string, genericValue? : string, odatavalue? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; postFlattenedSimpleProduct(productId: string, maxProductDisplayName: string, callback: ServiceCallback): void; /** @@ -214,6 +218,8 @@ declare class AutoRestResourceFlatteningTestService { * @param {string} [flattenParameterGroup.maxProductDisplayName] Display name * of product. * + * @param {string} [flattenParameterGroup.genericValue] Generic URL value. + * * @param {string} [flattenParameterGroup.odatavalue] URL value. * * @param {object} [options] Optional Parameters. diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js index 447c63d2fe467..b8f3616ea6bc8 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js @@ -790,6 +790,8 @@ AutoRestResourceFlatteningTestService.prototype.getResourceCollection = function * @param {string} [options.simpleBodyProduct.maxProductDisplayName] Display * name of product. * + * @param {string} [options.simpleBodyProduct.genericValue] Generic URL value. + * * @param {string} [options.simpleBodyProduct.odatavalue] URL value. * * @param {string} [options.simpleBodyProduct.productId] Unique identifier @@ -932,6 +934,8 @@ AutoRestResourceFlatteningTestService.prototype.putSimpleProduct = function (opt * * @param {string} [options.description] Description of product. * + * @param {string} [options.genericValue] Generic URL value. + * * @param {string} [options.odatavalue] URL value. * * @param {object} [options.customHeaders] Headers that will be added to the @@ -960,6 +964,7 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun throw new Error('callback cannot be null.'); } var description = (options && options.description !== undefined) ? options.description : undefined; + var genericValue = (options && options.genericValue !== undefined) ? options.genericValue : undefined; var odatavalue = (options && options.odatavalue !== undefined) ? options.odatavalue : undefined; // Validate try { @@ -972,6 +977,9 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun if (maxProductDisplayName === null || maxProductDisplayName === undefined || typeof maxProductDisplayName.valueOf() !== 'string') { throw new Error('maxProductDisplayName cannot be null or undefined and it must be of type string.'); } + if (genericValue !== null && genericValue !== undefined && typeof genericValue.valueOf() !== 'string') { + throw new Error('genericValue must be of type string.'); + } if (odatavalue !== null && odatavalue !== undefined && typeof odatavalue.valueOf() !== 'string') { throw new Error('odatavalue must be of type string.'); } @@ -980,12 +988,13 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun } var simpleBodyProduct; try { - if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (odatavalue !== null && odatavalue !== undefined)) + if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (genericValue !== null && genericValue !== undefined) || (odatavalue !== null && odatavalue !== undefined)) { simpleBodyProduct = new client.models['SimpleProduct'](); simpleBodyProduct.productId = productId; simpleBodyProduct.description = description; simpleBodyProduct.maxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.genericValue = genericValue; simpleBodyProduct.odatavalue = odatavalue; } } catch (error) { @@ -1103,6 +1112,8 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun * @param {string} [flattenParameterGroup.maxProductDisplayName] Display name * of product. * + * @param {string} [flattenParameterGroup.genericValue] Generic URL value. + * * @param {string} [flattenParameterGroup.odatavalue] URL value. * * @param {object} [options] Optional Parameters. @@ -1144,6 +1155,7 @@ AutoRestResourceFlatteningTestService.prototype.putSimpleProductWithGrouping = f var productId; var description; var maxProductDisplayName; + var genericValue; var odatavalue; var simpleBodyProduct; try { @@ -1176,18 +1188,26 @@ AutoRestResourceFlatteningTestService.prototype.putSimpleProductWithGrouping = f } } if (flattenParameterGroup !== null && flattenParameterGroup !== undefined) + { + genericValue = flattenParameterGroup.genericValue; + if (genericValue !== null && genericValue !== undefined && typeof genericValue.valueOf() !== 'string') { + throw new Error('genericValue must be of type string.'); + } + } + if (flattenParameterGroup !== null && flattenParameterGroup !== undefined) { odatavalue = flattenParameterGroup.odatavalue; if (odatavalue !== null && odatavalue !== undefined && typeof odatavalue.valueOf() !== 'string') { throw new Error('odatavalue must be of type string.'); } } - if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (odatavalue !== null && odatavalue !== undefined)) + if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (genericValue !== null && genericValue !== undefined) || (odatavalue !== null && odatavalue !== undefined)) { simpleBodyProduct = new client.models['SimpleProduct'](); simpleBodyProduct.productId = productId; simpleBodyProduct.description = description; simpleBodyProduct.maxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.genericValue = genericValue; simpleBodyProduct.odatavalue = odatavalue; } } catch (error) { diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js index 212317768692f..d548e2c6afea8 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js @@ -25,6 +25,8 @@ * * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ @@ -68,6 +70,12 @@ FlattenParameterGroup.prototype.mapper = function () { name: 'String' } }, + genericValue: { + required: false, + type: { + name: 'String' + } + }, odatavalue: { required: false, type: { diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/genericUrl.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/genericUrl.js new file mode 100644 index 0000000000000..cd657aa822f64 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/genericUrl.js @@ -0,0 +1,50 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +'use strict'; + +/** + * @class + * Initializes a new instance of the GenericUrl class. + * @constructor + * The Generic URL. + * @member {string} [genericValue] Generic URL value. + * + */ +function GenericUrl() { +} + +/** + * Defines the metadata of GenericUrl + * + * @returns {object} metadata of GenericUrl + * + */ +GenericUrl.prototype.mapper = function () { + return { + required: false, + serializedName: 'GenericUrl', + type: { + name: 'Composite', + className: 'GenericUrl', + modelProperties: { + genericValue: { + required: false, + serializedName: 'generic_value', + type: { + name: 'String' + } + } + } + } + }; +}; + +module.exports = GenericUrl; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts index d2ec275673bdc..a105800deac0a 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts @@ -122,11 +122,14 @@ export interface BaseProduct { * The product documentation. * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ export interface SimpleProduct extends BaseProduct { maxProductDisplayName: string; + genericValue?: string; odatavalue?: string; } @@ -145,6 +148,8 @@ export interface SimpleProduct extends BaseProduct { * * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ @@ -153,5 +158,18 @@ export interface FlattenParameterGroup { productId: string; description?: string; maxProductDisplayName: string; + genericValue?: string; odatavalue?: string; } + +/** + * @class + * Initializes a new instance of the GenericUrl class. + * @constructor + * The Generic URL. + * @member {string} [genericValue] Generic URL value. + * + */ +export interface GenericUrl { + genericValue?: string; +} diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js index cca3ddb58adef..b8365a1c50aaa 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js @@ -21,3 +21,4 @@ exports.ResourceCollection = require('./resourceCollection'); exports.BaseProduct = require('./baseProduct'); exports.SimpleProduct = require('./simpleProduct'); exports.FlattenParameterGroup = require('./flattenParameterGroup'); +exports.GenericUrl = require('./genericUrl'); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js index 5739ebc390150..3e66a747ff5a0 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js @@ -21,6 +21,8 @@ var util = require('util'); * The product documentation. * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ @@ -75,6 +77,13 @@ SimpleProduct.prototype.mapper = function () { name: 'String' } }, + genericValue: { + required: false, + serializedName: 'details.max_product_image.generic_value', + type: { + name: 'String' + } + }, odatavalue: { required: false, serializedName: 'details.max_product_image.@odata\\.value', diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py index 470b6d2d677ff..f15c8d90a2c92 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py @@ -222,7 +222,8 @@ def test_model_flattening_simple(self): product_id = "123", description = "product description", max_product_display_name = "max name", - odatavalue = "http://foo" + odatavalue = "http://foo", + generic_value = "https://generic" ) result = self.client.put_simple_product(simple_prduct) @@ -237,7 +238,7 @@ def test_model_flattening_with_parameter_flattening(self): odatavalue = "http://foo" ) - result = self.client.post_flattened_simple_product("123", "max name", "product description", "http://foo") + result = self.client.post_flattened_simple_product("123", "max name", "product description", None, "http://foo") self.assertEqual(result, simple_product) def test_model_flattening_with_grouping(self): diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py index 1d5dd84a24db8..b0a90b0981ec1 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py @@ -384,7 +384,7 @@ def put_simple_product( return deserialized def post_flattened_simple_product( - self, product_id, max_product_display_name, description=None, odatavalue=None, custom_headers={}, raw=False, **operation_config): + self, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None, custom_headers={}, raw=False, **operation_config): """ Put Flattened Simple Product with client flattening true on the parameter @@ -397,6 +397,8 @@ def post_flattened_simple_product( :type max_product_display_name: str :param description: Description of product. :type description: str + :param generic_value: Generic URL value. + :type generic_value: str :param odatavalue: URL value. :type odatavalue: str :param dict custom_headers: headers that will be added to the request @@ -410,8 +412,8 @@ def post_flattened_simple_product( if raw=true """ simple_body_product = None - if product_id is not None or description is not None or max_product_display_name is not None or odatavalue is not None: - simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, odatavalue=odatavalue) + if product_id is not None or description is not None or max_product_display_name is not None or generic_value is not None or odatavalue is not None: + simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, generic_value=generic_value, odatavalue=odatavalue) # Construct URL url = '/model-flatten/customFlattening' @@ -481,12 +483,15 @@ def put_simple_product_with_grouping( max_product_display_name = None if flatten_parameter_group is not None: max_product_display_name = flatten_parameter_group.max_product_display_name + generic_value = None + if flatten_parameter_group is not None: + generic_value = flatten_parameter_group.generic_value odatavalue = None if flatten_parameter_group is not None: odatavalue = flatten_parameter_group.odatavalue simple_body_product = None - if product_id is not None or description is not None or max_product_display_name is not None or odatavalue is not None: - simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, odatavalue=odatavalue) + if product_id is not None or description is not None or max_product_display_name is not None or generic_value is not None or odatavalue is not None: + simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, generic_value=generic_value, odatavalue=odatavalue) # Construct URL url = '/model-flatten/customFlattening/parametergrouping/{name}/' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py index e9fee8e3c065c..0696da7e2b659 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py @@ -16,6 +16,7 @@ from .base_product import BaseProduct from .simple_product import SimpleProduct from .flatten_parameter_group import FlattenParameterGroup +from .generic_url import GenericUrl __all__ = [ 'Error', 'ErrorException', @@ -25,4 +26,5 @@ 'BaseProduct', 'SimpleProduct', 'FlattenParameterGroup', + 'GenericUrl', ] diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py index 5043aa2867c4e..8158dc7e601df 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py @@ -26,6 +26,8 @@ class FlattenParameterGroup(Model): :type description: str :param max_product_display_name: Display name of product. :type max_product_display_name: str + :param generic_value: Generic URL value. + :type generic_value: str :param odatavalue: URL value. :type odatavalue: str """ @@ -36,9 +38,10 @@ class FlattenParameterGroup(Model): 'max_product_display_name': {'required': True}, } - def __init__(self, name, product_id, max_product_display_name, description=None, odatavalue=None, **kwargs): + def __init__(self, name, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None, **kwargs): self.name = name self.product_id = product_id self.description = description self.max_product_display_name = max_product_display_name + self.generic_value = generic_value self.odatavalue = odatavalue diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py new file mode 100644 index 0000000000000..9bfb97699cb61 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.serialization import Model + + +class GenericUrl(Model): + """ + The Generic URL. + + :param generic_value: Generic URL value. + :type generic_value: str + """ + + _attribute_map = { + 'generic_value': {'key': 'generic_value', 'type': 'str'}, + } + + def __init__(self, generic_value=None, **kwargs): + self.generic_value = generic_value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py index 8cf7fdd16f4cd..38d5be1405c1f 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py @@ -27,6 +27,8 @@ class SimpleProduct(BaseProduct): :param capacity: Capacity of product. For example, 4 people. Default value: "Large" . :type capacity: str + :param generic_value: Generic URL value. + :type generic_value: str :param odatavalue: URL value. :type odatavalue: str """ @@ -42,11 +44,13 @@ class SimpleProduct(BaseProduct): 'description': {'key': 'base_product_description', 'type': 'str'}, 'max_product_display_name': {'key': 'details.max_product_display_name', 'type': 'str'}, 'capacity': {'key': 'details.max_product_capacity', 'type': 'str'}, + 'generic_value': {'key': 'details.max_product_image.generic_value', 'type': 'str'}, 'odatavalue': {'key': 'details.max_product_image.@odata\\.value', 'type': 'str'}, } - def __init__(self, product_id, max_product_display_name, description=None, odatavalue=None, **kwargs): + def __init__(self, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None, **kwargs): super(SimpleProduct, self).__init__(product_id=product_id, description=description, **kwargs) self.max_product_display_name = max_product_display_name self.capacity = "Large" + self.generic_value = generic_value self.odatavalue = odatavalue diff --git a/AutoRest/TestServer/server/routes/model-flatten.js b/AutoRest/TestServer/server/routes/model-flatten.js index 83b72591a030b..e5992ecd24c34 100644 --- a/AutoRest/TestServer/server/routes/model-flatten.js +++ b/AutoRest/TestServer/server/routes/model-flatten.js @@ -144,7 +144,20 @@ var modelFlatten = function (coverage) { '@odata.value': "http://foo" } } - }; + }; + + var customFlattenBodyWithInheritedProperty = { + base_product_id: "123", + base_product_description: "product description", + details: { + max_product_display_name: 'max name', + max_product_capacity: "Large", + max_product_image: { + '@odata.value': "http://foo", + 'generic_value': "https://generic" + } + } + }; router.put('/:type', function (req, res, next) { if (req.body) { if (req.params.type === 'array') { @@ -169,9 +182,9 @@ var modelFlatten = function (coverage) { utils.send400(res, next, "The received body '" + JSON.stringify(req.body) + "' did not match the expected body '" + JSON.stringify(resourceCollectionBody) + "'."); } } else if (req.params.type === 'customFlattening') { - if (_.isEqual(req.body, customFlattenBody)) { + if (_.isEqual(req.body, customFlattenBodyWithInheritedProperty)) { coverage['putModelFlattenCustomBase']++; - res.status(200).end(JSON.stringify(customFlattenBody)); + res.status(200).end(JSON.stringify(customFlattenBodyWithInheritedProperty)); } else { utils.send400(res, next, "The received body '" + JSON.stringify(req.body) + "' did not match the expected body '" + JSON.stringify(customFlattenBody) + "'."); } @@ -198,10 +211,6 @@ var modelFlatten = function (coverage) { router.put('/customFlattening/parametergrouping/:name', function (req, res, next) { if (req.body) { - console.log('>>>>>>'); - console.log(util.inspect(req.body, {depth : null})); - console.log('>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<'); - console.log(util.inspect(customFlattenBody, {depth : null})); if (_.isEqual(req.body, customFlattenBody) && req.params.name === 'groupproduct') { coverage['putModelFlattenCustomGroupedParameter']++; res.status(200).end(JSON.stringify(customFlattenBody)); diff --git a/AutoRest/TestServer/swagger/model-flattening.json b/AutoRest/TestServer/swagger/model-flattening.json index 2bd49e97414b0..0ad7424f78cc3 100644 --- a/AutoRest/TestServer/swagger/model-flattening.json +++ b/AutoRest/TestServer/swagger/model-flattening.json @@ -433,8 +433,18 @@ } } }, + "GenericUrl": { + "description": "The Generic URL.", + "properties": { + "generic_value": { + "type": "string", + "description": "Generic URL value." + } + } + }, "ProductUrl": { "description": "The product URL.", + "allOf": [ { "$ref": "#/definitions/GenericUrl" } ], "properties": { "@odata.value": { "type": "string", diff --git a/Samples/petstore/Java/SwaggerPetstoreImpl.java b/Samples/petstore/Java/SwaggerPetstoreImpl.java index 1d8e7988a1847..0a5af09be4725 100644 --- a/Samples/petstore/Java/SwaggerPetstoreImpl.java +++ b/Samples/petstore/Java/SwaggerPetstoreImpl.java @@ -484,8 +484,7 @@ private ServiceResponse updatePetDelegate(Response response) * @return the List<Pet> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> findPetsByStatus() throws ServiceException, IOException { - final List status = null; - String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + final String statusConverted = null; Call call = service.findPetsByStatus(statusConverted); return findPetsByStatusDelegate(call.execute()); } @@ -502,8 +501,7 @@ public ServiceCall findPetsByStatusAsync(final ServiceCallback> servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List status = null; - String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + final String statusConverted = null; Call call = service.findPetsByStatus(statusConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @@ -581,8 +579,7 @@ private ServiceResponse> findPetsByStatusDelegate(Response> findPetsByTags() throws ServiceException, IOException { - final List tags = null; - String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + final String tagsConverted = null; Call call = service.findPetsByTags(tagsConverted); return findPetsByTagsDelegate(call.execute()); } @@ -599,8 +596,7 @@ public ServiceCall findPetsByTagsAsync(final ServiceCallback> serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List tags = null; - String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + final String tagsConverted = null; Call call = service.findPetsByTags(tagsConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @@ -979,8 +975,7 @@ private ServiceResponse deletePetDelegate(Response response) */ public ServiceResponse uploadFile(long petId) throws ServiceException, IOException { final String additionalMetadata = null; - final byte[] file = new byte[0]; - RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + final RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); Call call = service.uploadFile(petId, additionalMetadata, fileConverted); return uploadFileDelegate(call.execute()); } @@ -998,8 +993,7 @@ public ServiceCall uploadFileAsync(long petId, final ServiceCallback servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final String additionalMetadata = null; - final byte[] file = new byte[0]; - RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + final RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); Call call = service.uploadFile(petId, additionalMetadata, fileConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -1026,7 +1020,10 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse uploadFile(long petId, String additionalMetadata, byte[] file) throws ServiceException, IOException { - RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); + if (file != null) { + fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + } Call call = service.uploadFile(petId, additionalMetadata, fileConverted); return uploadFileDelegate(call.execute()); } @@ -1045,7 +1042,10 @@ public ServiceCall uploadFileAsync(long petId, String additionalMetadata, byte[] if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); + if (file != null) { + fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + } Call call = service.uploadFile(petId, additionalMetadata, fileConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { From 6142fb7f40269f7ed4f846ab703b91a6a257beb1 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Mon, 4 Apr 2016 21:22:58 -0700 Subject: [PATCH 69/99] csv array in path #900 * added test for flattening generic properties of a model to be flattened * regenerated java after merging from upstream * regen java * corrected C# java python tests * corrected C# java python tests * java test * initial commit for fixing array in path param * csv array in path #900 * fixed C# codegen and added support for base64Url path parameters in node.js * array in path * skipping the java test * removed import stmts * Skipping python tests as well --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 2 + .../Expected/AcceptanceTests/Url/IPaths.cs | 15 +++ .../Expected/AcceptanceTests/Url/Paths.cs | 112 ++++++++++++++++++ .../AcceptanceTests/Url/PathsExtensions.cs | 35 ++++++ .../TemplateModels/MethodTemplateModel.cs | 23 +++- .../java/fixtures/url/PathsOperations.java | 22 ++++ .../fixtures/url/PathsOperationsImpl.java | 66 +++++++++++ .../test/java/fixtures/url/PathsTests.java | 11 ++ .../AcceptanceTests/acceptanceTests.ts | 9 +- .../AcceptanceTests/Url/operations/index.d.ts | 18 +++ .../AcceptanceTests/Url/operations/paths.js | 111 ++++++++++++++++- .../NodeJS/NodeJS/ClientModelExtensions.cs | 6 + .../TemplateModels/MethodTemplateModel.cs | 11 +- .../Python.Tests/AcceptanceTests/url_tests.py | 2 + .../operations/paths.py | 45 +++++++ AutoRest/TestServer/server/app.js | 1 + AutoRest/TestServer/server/routes/paths.js | 23 +++- AutoRest/TestServer/swagger/url.json | 33 ++++++ 18 files changed, 536 insertions(+), 9 deletions(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 962a146c40337..0c6e31b1c1467 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -1348,6 +1348,8 @@ public void UrlPathTests() client.Paths.StringUrlEncoded(); client.Paths.EnumValid(UriColor.Greencolor); client.Paths.Base64Url(Encoding.UTF8.GetBytes("lorem")); + var testArray = new List { "ArrayPath1", @"begin!*'();:@ &=+$,/?#[]end", null, "" }; + client.Paths.ArrayCsvInPath(testArray); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs index 093efcf2646be..ce60b9a5c2f28 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs @@ -290,5 +290,20 @@ public partial interface IPaths /// The cancellation token. /// Task Base64UrlWithHttpMessagesAsync(byte[] base64UrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ + /// &=+$,/?#[]end' , null, ''] using the csv-array format + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ + /// &=+$,/?#[]end' , null, ''] using the csv-array format + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ArrayCsvInPathWithHttpMessagesAsync(IList arrayPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs index 6cf4f380818bd..d880804521f0c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs @@ -2580,5 +2580,117 @@ public Paths(AutoRestUrlTestService client) return _result; } + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ArrayCsvInPathWithHttpMessagesAsync(IList arrayPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (arrayPath == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "arrayPath"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("arrayPath", arrayPath); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ArrayCsvInPath", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}").ToString(); + _url = _url.Replace("{arrayPath:commaSeparated}", Uri.EscapeDataString(string.Join(",", arrayPath))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs index 6bb57c30dc6ef..65ea07ea61b8b 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs @@ -677,5 +677,40 @@ public static void Base64Url(this IPaths operations, byte[] base64UrlPath) await operations.Base64UrlWithHttpMessagesAsync(base64UrlPath, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// The operations group for this extension method. + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + public static void ArrayCsvInPath(this IPaths operations, IList arrayPath) + { + Task.Factory.StartNew(s => ((IPaths)s).ArrayCsvInPathAsync(arrayPath), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// The operations group for this extension method. + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// The cancellation token. + /// + public static async Task ArrayCsvInPathAsync(this IPaths operations, IList arrayPath, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.ArrayCsvInPathWithHttpMessagesAsync(arrayPath, null, cancellationToken).ConfigureAwait(false); + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs index 440187b3a32cb..cc44708181ecf 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs @@ -8,6 +8,7 @@ using System.Net; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Utilities; +using System.Text.RegularExpressions; namespace Microsoft.Rest.Generator.CSharp { @@ -412,10 +413,28 @@ public virtual string BuildUrl(string variableName) replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});"; } - builder.AppendLine(replaceString, + var urlPathName = pathParameter.SerializedName; + string pat = @".*\{" + urlPathName + @"(\:\w+)\}"; + Regex r = new Regex(pat); + Match m = r.Match(Url); + if (m.Success) + { + urlPathName += m.Groups[1].Value; + } + if (pathParameter.Type is SequenceType) + { + builder.AppendLine(replaceString, + variableName, + urlPathName, + pathParameter.GetFormattedReferenceValue(ClientReference)); + } + else + { + builder.AppendLine(replaceString, variableName, - pathParameter.SerializedName, + urlPathName, pathParameter.Type.ToString(ClientReference, pathParameter.Name)); + } } if (this.LogicalParameterTemplateModels.Any(p => p.Location == ParameterLocation.Query)) { diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java index 411448cebeac1..f7676a65a59a3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java @@ -16,6 +16,7 @@ import fixtures.url.models.ErrorException; import fixtures.url.models.UriColor; import java.io.IOException; +import java.util.List; import org.joda.time.DateTime; import org.joda.time.LocalDate; @@ -480,4 +481,25 @@ public interface PathsOperations { */ ServiceCall base64UrlAsync(String base64UrlPath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse arrayCsvInPath(List arrayPath) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall arrayCsvInPathAsync(List arrayPath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java index a760f773578ad..b32c2fcbd2471 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java @@ -11,14 +11,17 @@ package fixtures.url; import com.google.common.reflect.TypeToken; +import com.microsoft.rest.serializer.CollectionFormat; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.ServiceResponseBuilder; import com.microsoft.rest.ServiceResponseCallback; +import com.microsoft.rest.Validator; import fixtures.url.models.ErrorException; import fixtures.url.models.UriColor; import java.io.IOException; +import java.util.List; import okhttp3.ResponseBody; import org.apache.commons.codec.binary.Base64; import org.joda.time.DateTime; @@ -152,6 +155,10 @@ interface PathsService { @GET("paths/string/bG9yZW0/{base64UrlPath}") Call base64Url(@Path("base64UrlPath") String base64UrlPath); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}") + Call arrayCsvInPath(@Path("arrayPath") String arrayPath); + } /** @@ -1352,4 +1359,63 @@ private ServiceResponse base64UrlDelegate(Response response) .build(response); } + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse arrayCsvInPath(List arrayPath) throws ErrorException, IOException, IllegalArgumentException { + if (arrayPath == null) { + throw new IllegalArgumentException("Parameter arrayPath is required and cannot be null."); + } + Validator.validate(arrayPath); + String arrayPathConverted = this.client.getMapperAdapter().serializeList(arrayPath, CollectionFormat.CSV); + Call call = service.arrayCsvInPath(arrayPathConverted); + return arrayCsvInPathDelegate(call.execute()); + } + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall arrayCsvInPathAsync(List arrayPath, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (arrayPath == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter arrayPath is required and cannot be null.")); + return null; + } + Validator.validate(arrayPath, serviceCallback); + String arrayPathConverted = this.client.getMapperAdapter().serializeList(arrayPath, CollectionFormat.CSV); + Call call = service.arrayCsvInPath(arrayPathConverted); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(arrayCsvInPathDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse arrayCsvInPathDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java index 710e949f7093b..4aa614e9bc02b 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java @@ -143,4 +143,15 @@ public void dateTimeNull() throws Exception { Assert.assertTrue(ex.getMessage().contains("Parameter dateTimePath is required")); } } + /* + @Test + public void arrayCsvInPath() throws Exception { + List arrayPath = new ArrayList<>(); + arrayPath.add("ArrayPath1"); + arrayPath.add("begin!*'();:@ &=+$,/?#[]end"); + arrayPath.add(null); + arrayPath.add(""); + client.getPathsOperations().arrayCsvInPath(arrayPath); + } + */ } diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index 58c4709ef6799..52e27445dc45e 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts @@ -1867,7 +1867,7 @@ describe('nodejs', function () { }); }); - it.skip('should work when path has base64url encoded string', function (done) { + it('should work when path has base64url encoded string', function (done) { testClient.paths.base64Url(new Buffer('lorem', 'utf8'), function (error, result) { should.not.exist(error); should.not.exist(result); @@ -2087,6 +2087,13 @@ describe('nodejs', function () { }); }); }); + it('should work when path has string array values', function (done) { + var testArray = ['ArrayPath1', 'begin!*\'();:@ &=+$,/?#[]end', null, '']; + testClient.paths.arrayCsvInPath(testArray, function (error, result) { + should.not.exist(error); + done(); + }); + }); it('should work when use null values in url query', function (done) { testClient.queries.byteNull({ byteQuery: null }, function (error, result) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts index 52a74e2768063..3d9f5f55e7f91 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts @@ -376,6 +376,24 @@ export interface Paths { */ base64Url(base64UrlPath: Buffer, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; base64Url(base64UrlPath: Buffer, callback: ServiceCallback): void; + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, + * ''] using the csv-array format + * + * @param {array} arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ + * &=+$,/?#[]end' , null, ''] using the csv-array format + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + arrayCsvInPath(arrayPath: string[], options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + arrayCsvInPath(arrayPath: string[], callback: ServiceCallback): void; } /** diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js index 6dcb63419f912..ac14e44e195cb 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js @@ -2290,7 +2290,116 @@ Paths.prototype.base64Url = function (base64UrlPath, options, callback) { // Construct URL var requestUrl = this.client.baseUri + '//paths/string/bG9yZW0/{base64UrlPath}'; - requestUrl = requestUrl.replace('{base64UrlPath}', encodeURIComponent(base64UrlPath.toString())); + requestUrl = requestUrl.replace('{base64UrlPath}', encodeURIComponent(client.serialize({required: true, serializedName: 'base64UrlPath', type: {name: 'Base64Url'}}, base64UrlPath, 'base64UrlPath'))); + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, + * ''] using the csv-array format + * + * @param {array} arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ + * &=+$,/?#[]end' , null, ''] using the csv-array format + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Paths.prototype.arrayCsvInPath = function (arrayPath, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + // Validate + try { + if (!util.isArray(arrayPath)) { + throw new Error('arrayPath cannot be null or undefined and it must be of type array.'); + } + for (var i = 0; i < arrayPath.length; i++) { + if (arrayPath[i] !== null && arrayPath[i] !== undefined && typeof arrayPath[i].valueOf() !== 'string') { + throw new Error('arrayPath[i] must be of type string.'); + } + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}'; + requestUrl = requestUrl.replace('{arrayPath:commaSeparated}', encodeURIComponent(arrayPath.toString())); // trim all duplicate forward slashes in the url var regex = /([^:]\/)\/+/gi; requestUrl = requestUrl.replace(regex, '$1'); diff --git a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs index 59ccc22882506..c842b28b3280b 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs @@ -125,6 +125,12 @@ public static string ToString(this IType type, string reference) return string.Format(CultureInfo.InvariantCulture, "{0}.toISOString()", reference); } + + if (known.Type == KnownPrimaryType.Base64Url) + { + return string.Format(CultureInfo.InvariantCulture, + "client.serialize({{required: true, serializedName: '{0}', type: {{name: 'Base64Url'}}}}, {0}, '{0}')", reference); + } } return string.Format(CultureInfo.InvariantCulture, "{0}.toString()", reference); diff --git a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs index b07c71cfb566b..d5ee24b66c21f 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs @@ -11,6 +11,7 @@ using Microsoft.Rest.Generator.Utilities; using System.Collections; using System.Text; +using System.Text.RegularExpressions; namespace Microsoft.Rest.Generator.NodeJS { @@ -610,7 +611,15 @@ protected virtual void BuildPathParameters(string variableName, IndentedStringBu { pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', {2});"; } - builder.AppendLine(pathReplaceFormat, variableName, pathParameter.SerializedName, + var urlPathName = pathParameter.SerializedName; + string pat = @".*\{" + urlPathName + @"(\:\w+)\}"; + Regex r = new Regex(pat); + Match m = r.Match(Url); + if (m.Success) + { + urlPathName += m.Groups[1].Value; + } + builder.AppendLine(pathReplaceFormat, variableName, urlPathName, pathParameter.Type.ToString(pathParameter.Name)); } } diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py index 4cba849ad212a..05f7b4dcdba4f 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py @@ -90,6 +90,8 @@ def test_url_path(self): self.client.paths.get_negative_ten_billion(-10000000000) self.client.paths.get_ten_billion(10000000000) self.client.paths.string_empty("") + #test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + #self.client.paths.array_csv_in_path(test_array) with self.assertRaises(ValidationError): self.client.paths.string_null(None) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py index c9b86a5a08b78..46bface0d9375 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 @@ -1069,3 +1069,48 @@ def base64_url( if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response + + def array_csv_in_path( + self, array_path, custom_headers={}, raw=False, **operation_config): + """ + Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + null, ''] using the csv-array format + + :param array_path: an array of string ['ArrayPath1', 'begin!*'();:@ + &=+$,/?#[]end' , null, ''] using the csv-array format + :type array_path: list of str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}' + path_format_arguments = { + 'arrayPath': self._serialize.url("array_path", array_path, '[str]', div=',') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index df518bfde87a1..f0da0d60682c8 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -203,6 +203,7 @@ var coverage = { "getArrayBase64Url": 1, "getDictionaryBase64Url": 1, "UrlPathsStringBase64Url": 1, + "UrlPathsArrayCSVInPath": 1, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, diff --git a/AutoRest/TestServer/server/routes/paths.js b/AutoRest/TestServer/server/routes/paths.js index 15eaa93885a43..ba1b8e99df9e6 100644 --- a/AutoRest/TestServer/server/routes/paths.js +++ b/AutoRest/TestServer/server/routes/paths.js @@ -22,7 +22,8 @@ var scenarioMap = { "2012-01-01": "Valid", "2012-01-01T01:01:01Z": "Valid", "green color" : "Valid", - "bG9yZW0" : "Base64Url" + "bG9yZW0" : "Base64Url", + "ArrayPath1,begin!*'();:@ &=+$,/?#[]end,,": "CSVInPath" }; var typeMap = { @@ -35,7 +36,8 @@ var typeMap = { "byte": "Byte", "date": "Date", "datetime": "DateTime", - "enum" : "Enum" + "enum" : "Enum", + "array": "Array" }; var getScenarioName = function (type, scenario) { @@ -48,7 +50,12 @@ var getScenarioName = function (type, scenario) { console.log('Got parsed type "' + parsedType + '" and parsed scenario "' + parsedScenario + '"\n'); return '' + parsedType + parsedScenario; -} +}; + +var validateArrayPath = function (arrayValue, separator) { + console.log('received array value "' + arrayValue + '" separator "' + separator + '"'); + return (arrayValue === "ArrayPath1" + separator + "begin!*'();:@ &=+$,/?#[]end" + separator + separator); +}; var paths = function (coverage) { router.get('/:type/empty', function (req, res, next) { @@ -79,7 +86,7 @@ var paths = function (coverage) { var test = getScenarioName(type, scenario); var bytes = new Buffer(constants.MULTIBYTE_BUFFER); - if (type === 'enum' || type === 'date' || + if (type === 'enum' || type === 'date' || type === 'array' || type === 'datetime' || scenario === 'multibyte' || (type === 'string' && @@ -106,6 +113,14 @@ var paths = function (coverage) { } else { utils.send400(res, next, 'Failed string scenario \"' + scenario + '\" does not match wire parameter \"' + wireParameter + '\"'); } + } else if (type === 'array') { + if (scenario === wireParameter && validateArrayPath(wireParameter, ',')) { + console.log("Success!\n"); + coverage['UrlPaths' + test]++; + res.status(200).end(); + } else { + utils.send400(res, next, 'Failed enum scenario \"' + scenario + '\" does not match wire parameter \"' + wireParameter + '\"'); + } } else if (type === 'enum') { if (scenario === wireParameter) { console.log("Success!\n"); diff --git a/AutoRest/TestServer/swagger/url.json b/AutoRest/TestServer/swagger/url.json index 00da5fdfc2a94..4bf4530d177fb 100644 --- a/AutoRest/TestServer/swagger/url.json +++ b/AutoRest/TestServer/swagger/url.json @@ -740,6 +740,39 @@ } } }, + "/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}": { + "get": { + "operationId": "paths_ArrayCsvInPath", + "description": "Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format", + "tags": [ + "query Operations" + ], + "parameters": [ + { + "name": "arrayPath", + "in": "path", + "required": true, + "description": "an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format", + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + } + ], + "responses": { + "200": { + "description": "Successfully received /paths/array/ArrayPath1,begin!*'();:@ &=+$,/?#[]end,,/ArrayPath1,begin!*'();:@ &=+$,/?#[]end,," + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/queries/bool/true": { "get": { "operationId": "queries_getBooleanTrue", From 965e722ab492d19524c2a0db0da77b30879bbb77 Mon Sep 17 00:00:00 2001 From: Parvez Ahmed Date: Tue, 5 Apr 2016 19:03:26 +0530 Subject: [PATCH 70/99] Adding a method in the AzureClientExtensions to handle the PutOrPatch async calls with 202 responses which have no body and no specific headers --- .../AzureClientExtensions.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs index 57bbd064b95c2..9a38463a88e08 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs @@ -122,6 +122,38 @@ await UpdateStateFromGetResourceOperation(client, pollingState, getOperationUrl, return pollingState.AzureOperationResponse; } + /// + /// Gets operation result for PUT and PATCH operations. + /// + /// IAzureClient + /// Response from the begin operation + /// Headers that will be added to request + /// Cancellation token + /// Operation response + public static async Task GetPutOrPatchOperationResultAsync( + this IAzureClient client, + AzureOperationResponse response, + Dictionary> customHeaders, + CancellationToken cancellationToken) + { + var newResponse = new AzureOperationResponse + { + Request = response.Request, + Response = response.Response, + RequestId = response.RequestId + }; + + var azureOperationResponse = await client.GetPutOrPatchOperationResultAsync( + newResponse, customHeaders, cancellationToken); + + return new AzureOperationResponse + { + Request = azureOperationResponse.Request, + Response = azureOperationResponse.Response, + RequestId = azureOperationResponse.RequestId + }; + } + /// /// Gets operation result for DELETE and POST operations. /// From 97545e3876301f72c83a5efff077c54d43c54ddd Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Tue, 5 Apr 2016 10:12:03 -0700 Subject: [PATCH 71/99] fixes issue #890 --- .../ExponentialBackoffRetryStrategy.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs index cbe87e573cf61..b1241b6dcbe6c 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs @@ -112,10 +112,10 @@ public override ShouldRetryHandler GetShouldRetryHandler() { var random = new Random(); - var delta = (int) ((Math.Pow(2.0, currentRetryCount) - 1.0)* - random.Next((int) (_deltaBackoff.TotalMilliseconds*0.8), - (int) (_deltaBackoff.TotalMilliseconds*1.2))); - var interval = (int) Math.Min(checked(_minBackoff.TotalMilliseconds + delta), + var delta = (Math.Pow(2.0, currentRetryCount) - 1.0) * + random.Next((int) (_deltaBackoff.TotalMilliseconds*0.8), + (int) (_deltaBackoff.TotalMilliseconds*1.2)); + var interval = (int) Math.Min(_minBackoff.TotalMilliseconds + delta, _maxBackoff.TotalMilliseconds); TimeSpan retryInterval = TimeSpan.FromMilliseconds(interval); From 5915c652a29ff75c079014dc923014702643931d Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Wed, 6 Apr 2016 10:31:31 -0700 Subject: [PATCH 72/99] removing logic to require('moment') from model classes * fixes issue #890 * removing logic to require('moment') from model classes --- .../AzureCompositeModelClient/models/durationWrapper.js | 2 -- .../NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml | 5 ----- .../AcceptanceTests/BodyComplex/models/durationWrapper.js | 2 -- .../Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml | 5 ----- 4 files changed, 14 deletions(-) diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js index 3eba03688006e..05c4a93c4a750 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js @@ -10,8 +10,6 @@ 'use strict'; -var moment = require('moment'); - /** * @class * Initializes a new instance of the DurationWrapper class. diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml index 4f714041a98a5..36056f6225333 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml @@ -14,11 +14,6 @@ @EmptyLine var util = require('util'); @EmptyLine -@if (Model.ContainsDurationProperty()) -{ -@:var moment = require('moment'); -@EmptyLine -} /** * @@class * Initializes a new instance of the @(Model.Name) class. diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js index 3eba03688006e..05c4a93c4a750 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js @@ -10,8 +10,6 @@ 'use strict'; -var moment = require('moment'); - /** * @class * Initializes a new instance of the DurationWrapper class. diff --git a/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml b/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml index 75c9384491c78..9ab35ed94e1e0 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml @@ -20,11 +20,6 @@ @:var util = require('util'); @EmptyLine } -@if (Model.ContainsDurationProperty()) -{ -@:var moment = require('moment'); -@EmptyLine -} /** * @@class * Initializes a new instance of the @(Model.Name) class. From 12e9590b057dd8c18d1faaec6dd48ef8e8eecbfe Mon Sep 17 00:00:00 2001 From: annatisch Date: Wed, 6 Apr 2016 10:31:51 -0700 Subject: [PATCH 73/99] Python model kwargs removal * Removed kwargs from models * Regenerated tests * Updated runtime versions * Regenerated with updated version --- .../models/error.py | 2 +- .../AzureBodyDuration/setup.py | 2 +- .../models/error.py | 2 +- .../models/first_parameter_group.py | 2 +- ...t_multi_param_groups_second_param_group.py | 2 +- ...meter_grouping_post_optional_parameters.py | 2 +- ...meter_grouping_post_required_parameters.py | 2 +- .../AzureParameterGrouping/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/AzureReport/setup.py | 2 +- .../models/error.py | 2 +- .../models/flattened_product.py | 4 +- .../models/resource.py | 2 +- .../models/resource_collection.py | 2 +- .../AcceptanceTests/AzureResource/setup.py | 2 +- .../models/error.py | 2 +- .../models/odata_filter.py | 2 +- .../AcceptanceTests/AzureSpecials/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/CustomBaseUri/setup.py | 2 +- .../Expected/AcceptanceTests/Head/setup.py | 2 +- .../AcceptanceTests/HeadExceptions/setup.py | 2 +- .../models/operation_result.py | 2 +- .../models/operation_result_error.py | 2 +- .../models/product.py | 4 +- .../models/resource.py | 2 +- .../models/sku.py | 2 +- .../models/sub_product.py | 4 +- .../models/sub_resource.py | 2 +- .../Expected/AcceptanceTests/Lro/setup.py | 2 +- .../models/operation_result.py | 2 +- .../paging_get_multiple_pages_options.py | 2 +- ..._get_multiple_pages_with_offset_options.py | 2 +- .../models/product.py | 2 +- .../models/product_properties.py | 2 +- .../Expected/AcceptanceTests/Paging/setup.py | 2 +- .../StorageManagementClient/setup.py | 2 +- .../storagemanagementclient/models/bar.py | 2 +- .../models/check_name_availability_result.py | 2 +- .../models/custom_domain.py | 2 +- .../models/endpoints.py | 2 +- .../storagemanagementclient/models/foo.py | 2 +- .../models/resource.py | 2 +- .../models/storage_account.py | 4 +- ...ount_check_name_availability_parameters.py | 2 +- .../storage_account_create_parameters.py | 4 +- .../models/storage_account_keys.py | 2 +- ...orage_account_regenerate_key_parameters.py | 2 +- .../storage_account_update_parameters.py | 4 +- .../models/sub_resource.py | 2 +- .../storagemanagementclient/models/usage.py | 2 +- .../models/usage_list_result.py | 2 +- .../models/usage_name.py | 2 +- .../microsoftazuretesturl/models/error.py | 2 +- .../models/sample_resource_group.py | 2 +- .../SubscriptionIdApiVersion/setup.py | 2 +- .../Azure.Python/AzurePythonCodeGenerator.cs | 2 +- .../AzureServiceClientTemplateModel.cs | 2 +- .../Python.Tests/AcceptanceTests/zzz_tests.py | 4 ++ .../models/error.py | 2 +- .../models/product.py | 2 +- .../AcceptanceTests/BodyArray/setup.py | 2 +- .../autorestbooltestservice/models/error.py | 2 +- .../AcceptanceTests/BodyBoolean/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/BodyByte/setup.py | 2 +- .../models/array_wrapper.py | 2 +- .../models/basic.py | 2 +- .../models/boolean_wrapper.py | 2 +- .../models/byte_wrapper.py | 2 +- .../autorestcomplextestservice/models/cat.py | 4 +- .../models/cookiecuttershark.py | 4 +- .../models/date_wrapper.py | 2 +- .../models/datetime_wrapper.py | 2 +- .../models/datetimerfc1123_wrapper.py | 2 +- .../models/dictionary_wrapper.py | 2 +- .../autorestcomplextestservice/models/dog.py | 4 +- .../models/double_wrapper.py | 2 +- .../models/duration_wrapper.py | 2 +- .../models/error.py | 2 +- .../autorestcomplextestservice/models/fish.py | 2 +- .../models/float_wrapper.py | 2 +- .../models/goblinshark.py | 4 +- .../models/int_wrapper.py | 2 +- .../models/long_wrapper.py | 2 +- .../autorestcomplextestservice/models/pet.py | 2 +- .../models/readonly_obj.py | 2 +- .../models/salmon.py | 4 +- .../models/sawshark.py | 4 +- .../models/shark.py | 4 +- .../models/siamese.py | 4 +- .../models/string_wrapper.py | 2 +- .../AcceptanceTests/BodyComplex/setup.py | 2 +- .../autorestdatetestservice/models/error.py | 2 +- .../AcceptanceTests/BodyDate/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/BodyDateTime/setup.py | 2 +- .../models/error.py | 2 +- .../BodyDateTimeRfc1123/setup.py | 2 +- .../models/error.py | 2 +- .../models/widget.py | 2 +- .../AcceptanceTests/BodyDictionary/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/BodyDuration/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/BodyFile/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/BodyFormData/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/BodyInteger/setup.py | 2 +- .../autorestnumbertestservice/models/error.py | 2 +- .../AcceptanceTests/BodyNumber/setup.py | 2 +- .../autorestswaggerbatservice/models/error.py | 2 +- .../AcceptanceTests/BodyString/setup.py | 2 +- .../models/error.py | 2 +- .../AcceptanceTests/CustomBaseUri/setup.py | 2 +- .../models/error.py | 2 +- .../Expected/AcceptanceTests/Header/setup.py | 2 +- .../models/a.py | 2 +- .../models/b.py | 4 +- .../models/c.py | 2 +- .../models/d.py | 2 +- .../models/error.py | 2 +- .../Expected/AcceptanceTests/Http/setup.py | 2 +- .../models/base_product.py | 2 +- .../models/error.py | 2 +- .../models/flatten_parameter_group.py | 2 +- .../models/flattened_product.py | 4 +- .../models/generic_url.py | 2 +- .../models/resource.py | 2 +- .../models/resource_collection.py | 2 +- .../models/simple_product.py | 6 +-- .../AcceptanceTests/ModelFlattening/setup.py | 2 +- .../availability_set_update_parameters.py | 2 +- .../ParameterFlattening/setup.py | 2 +- .../autorestreportservice/models/error.py | 2 +- .../Expected/AcceptanceTests/Report/setup.py | 2 +- .../models/array_optional_wrapper.py | 2 +- .../models/array_wrapper.py | 2 +- .../models/class_optional_wrapper.py | 2 +- .../models/class_wrapper.py | 2 +- .../models/error.py | 2 +- .../models/int_optional_wrapper.py | 2 +- .../models/int_wrapper.py | 2 +- .../models/product.py | 2 +- .../models/string_optional_wrapper.py | 2 +- .../models/string_wrapper.py | 2 +- .../AcceptanceTests/RequiredOptional/setup.py | 2 +- .../autoresturltestservice/models/error.py | 2 +- .../Expected/AcceptanceTests/Url/setup.py | 2 +- .../models/child_product.py | 4 +- .../models/constant_product.py | 6 +-- .../autorestvalidationtest/models/error.py | 2 +- .../autorestvalidationtest/models/product.py | 8 ++-- .../AcceptanceTests/Validation/setup.py | 2 +- .../Python/Python/PythonCodeGenerator.cs | 2 +- .../TemplateModels/ModelTemplateModel.cs | 4 ++ .../ServiceClientTemplateModel.cs | 2 +- .../Python/Templates/ModelTemplate.cshtml | 4 +- .../Python/msrest/msrest/serialization.py | 42 ++++++++++++------- 160 files changed, 217 insertions(+), 197 deletions(-) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py index 386a34a84a195..251a4cda74c35 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py index bd178f8128ba4..0a3174e49ea52 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py @@ -22,6 +22,6 @@ class FirstParameterGroup(Model): :type query_one: int """ - def __init__(self, header_one=None, query_one=30, **kwargs): + def __init__(self, header_one=None, query_one=30): self.header_one = header_one self.query_one = query_one diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py index e885a9124d948..d178c7470903e 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py @@ -22,6 +22,6 @@ class ParameterGroupingPostMultiParamGroupsSecondParamGroup(Model): :type query_two: int """ - def __init__(self, header_two=None, query_two=30, **kwargs): + def __init__(self, header_two=None, query_two=30): self.header_two = header_two self.query_two = query_two diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py index a89e6b36d00b3..7368af7d84956 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py @@ -22,6 +22,6 @@ class ParameterGroupingPostOptionalParameters(Model): :type query: int """ - def __init__(self, custom_header=None, query=30, **kwargs): + def __init__(self, custom_header=None, query=30): self.custom_header = custom_header self.query = query diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py index 56ec95284747e..33627d834bdad 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py @@ -31,7 +31,7 @@ class ParameterGroupingPostRequiredParameters(Model): 'path': {'required': True}, } - def __init__(self, body, path, custom_header=None, query=30, **kwargs): + def __init__(self, body, path, custom_header=None, query=30): self.body = body self.custom_header = custom_header self.query = query diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py index 188c79aaea4bf..2e0910c9bcdeb 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py index b088cbdc514b9..762429f51c290 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py index 019aa228b5d07..5b5b7ea2e4c04 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py @@ -44,8 +44,8 @@ class FlattenedProduct(Resource): 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, lsize=None, provisioning_state=None, **kwargs): - super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs) + def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, lsize=None, provisioning_state=None): + super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name) self.pname = pname self.lsize = lsize self.provisioning_state = provisioning_state diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py index c2e81e8035ee3..ccc46d79f60ce 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py @@ -35,7 +35,7 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, **kwargs): + def __init__(self, id=None, type=None, tags=None, location=None, name=None): self.id = id self.type = type self.tags = tags diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py index ce97251d6b01a..4c59a75395942 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py @@ -31,7 +31,7 @@ class ResourceCollection(Model): 'dictionaryofresources': {'key': 'dictionaryofresources', 'type': '{FlattenedProduct}'}, } - def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None, **kwargs): + def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None): self.productresource = productresource self.arrayofresources = arrayofresources self.dictionaryofresources = dictionaryofresources diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py index 93b7b7f8b4bd8..d4003cb22d3fd 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py index b4ab713953874..e9ef780e3aefa 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py @@ -30,7 +30,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, constant_id=None, message=None, **kwargs): + def __init__(self, status=None, constant_id=None, message=None): self.status = status self.constant_id = constant_id self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py index a0604d9f6045b..16c1f6545d148 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py @@ -26,6 +26,6 @@ class OdataFilter(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py index 581909f4464b6..a23f56d19161d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py index d7a4a945847f1..b58762d14bf16 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py index 8fd8508a288a8..e11e2311eb413 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py index 94a2cb8cb8860..eea7127ecba39 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py index 21fd4883dc37e..2ded58b2f5920 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py @@ -29,6 +29,6 @@ class OperationResult(Model): 'error': {'key': 'error', 'type': 'OperationResultError'}, } - def __init__(self, status=None, error=None, **kwargs): + def __init__(self, status=None, error=None): self.status = status self.error = error diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py index 974649001b44e..22dab4495c979 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py @@ -26,6 +26,6 @@ class OperationResultError(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, code=None, message=None, **kwargs): + def __init__(self, code=None, message=None): self.code = code self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py index db52ee8ddc946..6f322f37b09fc 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py @@ -43,7 +43,7 @@ class Product(Resource): 'provisioning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, provisioning_state=None, provisioning_state_values=None, **kwargs): - super(Product, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs) + def __init__(self, id=None, type=None, tags=None, location=None, name=None, provisioning_state=None, provisioning_state_values=None): + super(Product, self).__init__(id=id, type=type, tags=tags, location=location, name=name) self.provisioning_state = provisioning_state self.provisioning_state_values = provisioning_state_values diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py index c2e81e8035ee3..ccc46d79f60ce 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py @@ -35,7 +35,7 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, **kwargs): + def __init__(self, id=None, type=None, tags=None, location=None, name=None): self.id = id self.type = type self.tags = tags diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py index 42b14cd43755d..d7f35d777f639 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py @@ -26,6 +26,6 @@ class Sku(Model): 'id': {'key': 'id', 'type': 'str'}, } - def __init__(self, name=None, id=None, **kwargs): + def __init__(self, name=None, id=None): self.name = name self.id = id diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py index a0bc26f58f22e..099f79ecdc9de 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py @@ -31,7 +31,7 @@ class SubProduct(SubResource): 'provisioning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'}, } - def __init__(self, id=None, provisioning_state=None, provisioning_state_values=None, **kwargs): - super(SubProduct, self).__init__(id=id, **kwargs) + def __init__(self, id=None, provisioning_state=None, provisioning_state_values=None): + super(SubProduct, self).__init__(id=id) self.provisioning_state = provisioning_state self.provisioning_state_values = provisioning_state_values diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py index 83b7f418cbe93..46ce23db785ac 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py @@ -23,5 +23,5 @@ class SubResource(Model): 'id': {'key': 'id', 'type': 'str'}, } - def __init__(self, id=None, **kwargs): + def __init__(self, id=None): self.id = id diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py index 3d6569fed9a9e..6efdcd0d3ea4e 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py index 13b86a98343d8..e0af748f82c9f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py @@ -25,5 +25,5 @@ class OperationResult(Model): 'status': {'key': 'status', 'type': 'str'}, } - def __init__(self, status=None, **kwargs): + def __init__(self, status=None): self.status = status diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py index c91f754fee26f..c776b4da879d7 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py @@ -25,6 +25,6 @@ class PagingGetMultiplePagesOptions(Model): :type timeout: int """ - def __init__(self, maxresults=None, timeout=30, **kwargs): + def __init__(self, maxresults=None, timeout=30): self.maxresults = maxresults self.timeout = timeout diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py index cdb588109cda7..57650f8519648 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py @@ -31,7 +31,7 @@ class PagingGetMultiplePagesWithOffsetOptions(Model): 'offset': {'required': True}, } - def __init__(self, offset, maxresults=None, timeout=30, **kwargs): + def __init__(self, offset, maxresults=None, timeout=30): self.maxresults = maxresults self.offset = offset self.timeout = timeout diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py index d9babb6925957..f019f46d72e5a 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py @@ -24,5 +24,5 @@ class Product(Model): 'properties': {'key': 'properties', 'type': 'ProductProperties'}, } - def __init__(self, properties=None, **kwargs): + def __init__(self, properties=None): self.properties = properties diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py index 2924fa9464303..4db1d4204a78d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py @@ -26,6 +26,6 @@ class ProductProperties(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py index a02653a9cb33b..b8c042a69efb9 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py index 100c1f03a42f3..7e7b4160e02e1 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py index dd61b74f50851..09c2ed766ed61 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py @@ -26,5 +26,5 @@ class Bar(Model): 'recursive_point': {'key': 'RecursivePoint', 'type': 'Endpoints'}, } - def __init__(self, recursive_point=None, **kwargs): + def __init__(self, recursive_point=None): self.recursive_point = recursive_point diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py index 2626b7d6d9408..cc1c87848bdf4 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py @@ -35,7 +35,7 @@ class CheckNameAvailabilityResult(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, name_available=None, reason=None, message=None, **kwargs): + def __init__(self, name_available=None, reason=None, message=None): self.name_available = name_available self.reason = reason self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py index e94b86210a007..f23bf8e6696ec 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py @@ -30,6 +30,6 @@ class CustomDomain(Model): 'use_sub_domain': {'key': 'useSubDomain', 'type': 'bool'}, } - def __init__(self, name=None, use_sub_domain=None, **kwargs): + def __init__(self, name=None, use_sub_domain=None): self.name = name self.use_sub_domain = use_sub_domain diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py index 18e67db15f0e1..898527a5c8db1 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py @@ -39,7 +39,7 @@ class Endpoints(Model): 'foo_point': {'key': 'FooPoint', 'type': 'Foo'}, } - def __init__(self, blob=None, queue=None, table=None, dummy_end_point=None, foo_point=None, **kwargs): + def __init__(self, blob=None, queue=None, table=None, dummy_end_point=None, foo_point=None): self.blob = blob self.queue = queue self.table = table diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py index 91428f1689ace..2de0ad72c8366 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py @@ -26,5 +26,5 @@ class Foo(Model): 'bar_point': {'key': 'Bar.Point', 'type': 'Bar'}, } - def __init__(self, bar_point=None, **kwargs): + def __init__(self, bar_point=None): self.bar_point = bar_point diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py index d9358ccfb3f05..9025ae9819072 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py @@ -39,7 +39,7 @@ class Resource(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, **kwargs): + def __init__(self, location, id=None, name=None, type=None, tags=None): self.id = id self.name = name self.type = type diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py index b565b7120cee1..3268320474a92 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py @@ -99,8 +99,8 @@ class StorageAccount(Resource): 'secondary_endpoints': {'key': 'properties.secondaryEndpoints', 'type': 'Endpoints'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None, **kwargs): - super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, location, id=None, name=None, type=None, tags=None, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None): + super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags) self.provisioning_state = provisioning_state self.account_type = account_type self.primary_endpoints = primary_endpoints diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py index 7fd37db107159..3874804d1acce 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py @@ -30,6 +30,6 @@ class StorageAccountCheckNameAvailabilityParameters(Model): 'type': {'key': 'type', 'type': 'str'}, } - def __init__(self, name, type="Microsoft.Storage/storageAccounts", **kwargs): + def __init__(self, name, type="Microsoft.Storage/storageAccounts"): self.name = name self.type = type diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py index e4de00fde6c84..449f6c502135a 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py @@ -45,6 +45,6 @@ class StorageAccountCreateParameters(Resource): 'account_type': {'key': 'properties.accountType', 'type': 'AccountType'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None, **kwargs): - super(StorageAccountCreateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None): + super(StorageAccountCreateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags) self.account_type = account_type diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py index 6a3d1413b9f3d..6a49f862ea08c 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py @@ -27,6 +27,6 @@ class StorageAccountKeys(Model): 'key2': {'key': 'key2', 'type': 'str'}, } - def __init__(self, key1=None, key2=None, **kwargs): + def __init__(self, key1=None, key2=None): self.key1 = key1 self.key2 = key2 diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py index f4c0bd5893004..7fe2da5d56729 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py @@ -23,5 +23,5 @@ class StorageAccountRegenerateKeyParameters(Model): 'key_name': {'key': 'keyName', 'type': 'KeyName'}, } - def __init__(self, key_name=None, **kwargs): + def __init__(self, key_name=None): self.key_name = key_name diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py index 1a4b634650561..5975e56879436 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py @@ -54,7 +54,7 @@ class StorageAccountUpdateParameters(Resource): 'custom_domain': {'key': 'properties.customDomain', 'type': 'CustomDomain'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None, custom_domain=None, **kwargs): - super(StorageAccountUpdateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None, custom_domain=None): + super(StorageAccountUpdateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags) self.account_type = account_type self.custom_domain = custom_domain diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py index 4daf061642fbf..676b7409deec4 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py @@ -23,5 +23,5 @@ class SubResource(Model): 'id': {'key': 'id', 'type': 'str'}, } - def __init__(self, id=None, **kwargs): + def __init__(self, id=None): self.id = id diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py index 3be6b28966e34..53d96b70adf16 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py @@ -38,7 +38,7 @@ class Usage(Model): 'name': {'key': 'name', 'type': 'UsageName'}, } - def __init__(self, unit=None, current_value=None, limit=None, name=None, **kwargs): + def __init__(self, unit=None, current_value=None, limit=None, name=None): self.unit = unit self.current_value = current_value self.limit = limit diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py index bb868e0c1633d..58bcc17497530 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py @@ -25,5 +25,5 @@ class UsageListResult(Model): 'value': {'key': 'value', 'type': '[Usage]'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py index 920db4d98eeeb..91e050893c0f9 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py @@ -28,6 +28,6 @@ class UsageName(Model): 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } - def __init__(self, value=None, localized_value=None, **kwargs): + def __init__(self, value=None, localized_value=None): self.value = value self.localized_value = localized_value diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py index e85f2c415d577..9b230ca9dee62 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, code=None, message=None, **kwargs): + def __init__(self, code=None, message=None): self.code = code self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py index f2a334ff424c4..19fa537a1bea8 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py @@ -26,6 +26,6 @@ class SampleResourceGroup(Model): 'location': {'key': 'location', 'type': 'str'}, } - def __init__(self, name=None, location=None, **kwargs): + def __init__(self, name=None, location=None): self.name = name self.location = location diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py index 0d026fe2b27f5..a0eeb22b2beda 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs b/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs index fb90e029585e1..0ad15558928b5 100644 --- a/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs +++ b/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs @@ -19,7 +19,7 @@ namespace Microsoft.Rest.Generator.Azure.Python { public class AzurePythonCodeGenerator : PythonCodeGenerator { - private const string ClientRuntimePackage = "msrestazure version 0.1.0"; + private const string ClientRuntimePackage = "msrestazure version 0.2.1"; // page extensions class dictionary. private IList pageModels; diff --git a/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs b/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs index 145dbeb3a79ae..3c0cfcbf8160c 100644 --- a/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs +++ b/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs @@ -97,7 +97,7 @@ public override string SetupRequires { get { - return "\"msrest>=0.1.0\", \"msrestazure>=0.1.0\""; + return "\"msrest>=0.2.0\", \"msrestazure>=0.2.1\""; } } diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py index 3702f08cd4316..b54157497620c 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py @@ -53,6 +53,8 @@ def test_ensure_coverage(self): config.log_level = log_level client = AutoRestReportService(config) report = client.get_report() + + # These will not be supported in Python report['getIntegerOverflow']=1 report['getIntegerUnderflow']=1 report['getLongOverflow']=1 @@ -60,6 +62,8 @@ def test_ensure_coverage(self): report['getDateInvalid']=1 report['getDictionaryNullkey']=1 report['HttpRedirect300Get']=1 + + # TODO: Support large file streams report['FileStreamVeryLarge']=1 # TODO: Support ignore readonly property in http put diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py index 3358c74205436..b74b8ee418307 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py @@ -26,6 +26,6 @@ class Product(Model): 'string': {'key': 'string', 'type': 'str'}, } - def __init__(self, integer=None, string=None, **kwargs): + def __init__(self, integer=None, string=None): self.integer = integer self.string = string diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py index db9a2a12116a5..cf329dfab37c5 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py index 8058a2eff9ed9..facfec90a0b4c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py index 38ae3533fae8d..0482b6833f373 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py index 954d370a66c94..df8448a8fbea8 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py @@ -23,5 +23,5 @@ class ArrayWrapper(Model): 'array': {'key': 'array', 'type': '[str]'}, } - def __init__(self, array=None, **kwargs): + def __init__(self, array=None): self.array = array diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py index 0f914a9ac9030..83a9721456ac7 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py @@ -30,7 +30,7 @@ class Basic(Model): 'color': {'key': 'color', 'type': 'CMYKColors'}, } - def __init__(self, id=None, name=None, color=None, **kwargs): + def __init__(self, id=None, name=None, color=None): self.id = id self.name = name self.color = color diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py index 89429bc9bc429..abe1f9cb4e232 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py @@ -26,6 +26,6 @@ class BooleanWrapper(Model): 'field_false': {'key': 'field_false', 'type': 'bool'}, } - def __init__(self, field_true=None, field_false=None, **kwargs): + def __init__(self, field_true=None, field_false=None): self.field_true = field_true self.field_false = field_false diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py index 505b230b7c2f7..56711e83f0787 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py @@ -23,5 +23,5 @@ class ByteWrapper(Model): 'field': {'key': 'field', 'type': 'bytearray'}, } - def __init__(self, field=None, **kwargs): + def __init__(self, field=None): self.field = field diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py index 476c2a0c1d028..15ec946bab6d2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py @@ -33,7 +33,7 @@ class Cat(Pet): 'hates': {'key': 'hates', 'type': '[Dog]'}, } - def __init__(self, id=None, name=None, color=None, hates=None, **kwargs): - super(Cat, self).__init__(id=id, name=name, **kwargs) + def __init__(self, id=None, name=None, color=None, hates=None): + super(Cat, self).__init__(id=id, name=name) self.color = color self.hates = hates diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py index ee898dd7d3582..835f078e28c02 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py @@ -36,6 +36,6 @@ class Cookiecuttershark(Shark): 'birthday': {'required': True}, } - def __init__(self, length, birthday, species=None, siblings=None, age=None, **kwargs): - super(Cookiecuttershark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None): + super(Cookiecuttershark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday) self.fishtype = 'cookiecuttershark' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py index 03b379e1105c7..d876dc6e736c8 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py @@ -26,6 +26,6 @@ class DateWrapper(Model): 'leap': {'key': 'leap', 'type': 'date'}, } - def __init__(self, field=None, leap=None, **kwargs): + def __init__(self, field=None, leap=None): self.field = field self.leap = leap diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py index 74e8645ace21d..c768499e011f9 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py @@ -26,6 +26,6 @@ class DatetimeWrapper(Model): 'now': {'key': 'now', 'type': 'iso-8601'}, } - def __init__(self, field=None, now=None, **kwargs): + def __init__(self, field=None, now=None): self.field = field self.now = now diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py index 165fdceb85a3c..a0279c5425f7c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py @@ -26,6 +26,6 @@ class Datetimerfc1123Wrapper(Model): 'now': {'key': 'now', 'type': 'rfc-1123'}, } - def __init__(self, field=None, now=None, **kwargs): + def __init__(self, field=None, now=None): self.field = field self.now = now diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py index e639e709ab1d9..999fec60f3d96 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py @@ -23,5 +23,5 @@ class DictionaryWrapper(Model): 'default_program': {'key': 'defaultProgram', 'type': '{str}'}, } - def __init__(self, default_program=None, **kwargs): + def __init__(self, default_program=None): self.default_program = default_program diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py index 69911b3d30437..420352f5b0eb5 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py @@ -29,6 +29,6 @@ class Dog(Pet): 'food': {'key': 'food', 'type': 'str'}, } - def __init__(self, id=None, name=None, food=None, **kwargs): - super(Dog, self).__init__(id=id, name=name, **kwargs) + def __init__(self, id=None, name=None, food=None): + super(Dog, self).__init__(id=id, name=name) self.food = food diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py index 5eb718fcc08e7..63f46bd155bd0 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py @@ -29,6 +29,6 @@ class DoubleWrapper(Model): 'field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose': {'key': 'field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose', 'type': 'float'}, } - def __init__(self, field1=None, field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose=None, **kwargs): + def __init__(self, field1=None, field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose=None): self.field1 = field1 self.field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose = field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py index ce5cd3ce54403..04cfa5a36c7d2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py @@ -23,5 +23,5 @@ class DurationWrapper(Model): 'field': {'key': 'field', 'type': 'duration'}, } - def __init__(self, field=None, **kwargs): + def __init__(self, field=None): self.field = field diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py index f1aea273aefb1..fb83f8e3fa972 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py @@ -42,7 +42,7 @@ class Fish(Model): 'fishtype': {'salmon': 'Salmon', 'shark': 'Shark'} } - def __init__(self, length, species=None, siblings=None, **kwargs): + def __init__(self, length, species=None, siblings=None): self.species = species self.length = length self.siblings = siblings diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py index 52350aacd388a..098ff503ef763 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py @@ -26,6 +26,6 @@ class FloatWrapper(Model): 'field2': {'key': 'field2', 'type': 'float'}, } - def __init__(self, field1=None, field2=None, **kwargs): + def __init__(self, field1=None, field2=None): self.field1 = field1 self.field2 = field2 diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py index c9cf046ed0cb5..a119ee4d6e574 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py @@ -48,7 +48,7 @@ class Goblinshark(Shark): 'jawsize': {'key': 'jawsize', 'type': 'int'}, } - def __init__(self, length, birthday, species=None, siblings=None, age=None, jawsize=None, **kwargs): - super(Goblinshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None, jawsize=None): + super(Goblinshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday) self.jawsize = jawsize self.fishtype = 'goblin' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py index ad9a60209e698..92136de6442c0 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py @@ -26,6 +26,6 @@ class IntWrapper(Model): 'field2': {'key': 'field2', 'type': 'int'}, } - def __init__(self, field1=None, field2=None, **kwargs): + def __init__(self, field1=None, field2=None): self.field1 = field1 self.field2 = field2 diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py index 350dff72efff5..70a8c78b56d3b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py @@ -26,6 +26,6 @@ class LongWrapper(Model): 'field2': {'key': 'field2', 'type': 'long'}, } - def __init__(self, field1=None, field2=None, **kwargs): + def __init__(self, field1=None, field2=None): self.field1 = field1 self.field2 = field2 diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py index f637af26154de..ae794dc5f6338 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py @@ -26,6 +26,6 @@ class Pet(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py index 54f617ab191ec..f0db42cc1b3f9 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py @@ -26,6 +26,6 @@ class ReadonlyObj(Model): 'size': {'key': 'size', 'type': 'int'}, } - def __init__(self, id=None, size=None, **kwargs): + def __init__(self, id=None, size=None): self.id = id self.size = size diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py index 94073cb2b7e36..ca9ac00e67109 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py @@ -44,8 +44,8 @@ class Salmon(Fish): 'iswild': {'key': 'iswild', 'type': 'bool'}, } - def __init__(self, length, species=None, siblings=None, location=None, iswild=None, **kwargs): - super(Salmon, self).__init__(species=species, length=length, siblings=siblings, **kwargs) + def __init__(self, length, species=None, siblings=None, location=None, iswild=None): + super(Salmon, self).__init__(species=species, length=length, siblings=siblings) self.location = location self.iswild = iswild self.fishtype = 'salmon' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py index 9666b532506da..eb5f018fd759b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py @@ -48,7 +48,7 @@ class Sawshark(Shark): 'picture': {'key': 'picture', 'type': 'bytearray'}, } - def __init__(self, length, birthday, species=None, siblings=None, age=None, picture=None, **kwargs): - super(Sawshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None, picture=None): + super(Sawshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday) self.picture = picture self.fishtype = 'sawshark' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py index 51fe0956bf51d..18d4187ebede9 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py @@ -49,8 +49,8 @@ class Shark(Fish): 'fishtype': {'sawshark': 'Sawshark', 'goblin': 'Goblinshark', 'cookiecuttershark': 'Cookiecuttershark'} } - def __init__(self, length, birthday, species=None, siblings=None, age=None, **kwargs): - super(Shark, self).__init__(species=species, length=length, siblings=siblings, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None): + super(Shark, self).__init__(species=species, length=length, siblings=siblings) self.age = age self.birthday = birthday self.fishtype = 'shark' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py index a52c0d69892b1..ad83ab4771cf1 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py @@ -36,6 +36,6 @@ class Siamese(Cat): 'breed': {'key': 'breed', 'type': 'str'}, } - def __init__(self, id=None, name=None, color=None, hates=None, breed=None, **kwargs): - super(Siamese, self).__init__(id=id, name=name, color=color, hates=hates, **kwargs) + def __init__(self, id=None, name=None, color=None, hates=None, breed=None): + super(Siamese, self).__init__(id=id, name=name, color=color, hates=hates) self.breed = breed diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py index 19bb78f4673a5..a01f361cdba21 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py @@ -29,7 +29,7 @@ class StringWrapper(Model): 'null': {'key': 'null', 'type': 'str'}, } - def __init__(self, field=None, empty=None, null=None, **kwargs): + def __init__(self, field=None, empty=None, null=None): self.field = field self.empty = empty self.null = null diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py index c67f7c49a7562..65d0a41a65f59 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py index 09e6aa6e8c9ef..c70f0e8100516 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py index 420c600dff136..ac383e8eb0acb 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py index b323ed157ce25..143969182ad02 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py index 3ac8dcf6034e4..3a3c86f698dd4 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py @@ -26,6 +26,6 @@ class Widget(Model): 'string': {'key': 'string', 'type': 'str'}, } - def __init__(self, integer=None, string=None, **kwargs): + def __init__(self, integer=None, string=None): self.integer = integer self.string = string diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py index 6dcd5850b3d44..3326b76166d12 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py index 3340f8db5b9cd..88bb6938d4a09 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py index 918eb67dcd7c0..ff524cfed3430 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py index 03d887addbd35..f71daa3028819 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py index a85431ad534e1..c203877495320 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py index 2948a18b3e493..7495879ab1b3f 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py index adcf15f154920..26c1dc8c835ef 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py index bb4a542940856..20758a3b0efba 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py index bf58eae79e6c9..2e773b93aad57 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py index 291d1604b627f..f6baf6ea42b4c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py @@ -24,7 +24,7 @@ class A(Model): 'status_code': {'key': 'statusCode', 'type': 'str'}, } - def __init__(self, status_code=None, **kwargs): + def __init__(self, status_code=None): self.status_code = status_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py index 4b73a497c8406..0853087e7d476 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py @@ -26,6 +26,6 @@ class B(A): 'text_status_code': {'key': 'textStatusCode', 'type': 'str'}, } - def __init__(self, status_code=None, text_status_code=None, **kwargs): - super(B, self).__init__(status_code=status_code, **kwargs) + def __init__(self, status_code=None, text_status_code=None): + super(B, self).__init__(status_code=status_code) self.text_status_code = text_status_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py index ec12dffd7884a..2e23c31e92048 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py @@ -23,5 +23,5 @@ class C(Model): 'http_code': {'key': 'httpCode', 'type': 'str'}, } - def __init__(self, http_code=None, **kwargs): + def __init__(self, http_code=None): self.http_code = http_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py index 3e08e4489c52a..8b32eef124a99 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py @@ -23,5 +23,5 @@ class D(Model): 'http_status_code': {'key': 'httpStatusCode', 'type': 'str'}, } - def __init__(self, http_status_code=None, **kwargs): + def __init__(self, http_status_code=None): self.http_status_code = http_status_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py index 2db682d7ec3dc..e08efb221837d 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py index 55707c63063ed..ad8b2a34ebceb 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py @@ -33,6 +33,6 @@ class BaseProduct(Model): 'description': {'key': 'base_product_description', 'type': 'str'}, } - def __init__(self, product_id, description=None, **kwargs): + def __init__(self, product_id, description=None): self.product_id = product_id self.description = description diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py index bb9d41eb9cbde..0ff39bf5de7f9 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py @@ -31,7 +31,7 @@ class Error(Model): 'parent_error': {'key': 'parentError', 'type': 'Error'}, } - def __init__(self, status=None, message=None, parent_error=None, **kwargs): + def __init__(self, status=None, message=None, parent_error=None): self.status = status self.message = message self.parent_error = parent_error diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py index 8158dc7e601df..ef30dd1f2d039 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py @@ -38,7 +38,7 @@ class FlattenParameterGroup(Model): 'max_product_display_name': {'required': True}, } - def __init__(self, name, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None, **kwargs): + def __init__(self, name, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None): self.name = name self.product_id = product_id self.description = description diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py index 458eef6da4c3d..99e49b9aa384f 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py @@ -49,8 +49,8 @@ class FlattenedProduct(Resource): 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, flattened_product_type=None, provisioning_state_values=None, provisioning_state=None, **kwargs): - super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs) + def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, flattened_product_type=None, provisioning_state_values=None, provisioning_state=None): + super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name) self.pname = pname self.flattened_product_type = flattened_product_type self.provisioning_state_values = provisioning_state_values diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py index 9bfb97699cb61..44d207c724ad2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py @@ -24,5 +24,5 @@ class GenericUrl(Model): 'generic_value': {'key': 'generic_value', 'type': 'str'}, } - def __init__(self, generic_value=None, **kwargs): + def __init__(self, generic_value=None): self.generic_value = generic_value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py index c2e81e8035ee3..ccc46d79f60ce 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py @@ -35,7 +35,7 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, **kwargs): + def __init__(self, id=None, type=None, tags=None, location=None, name=None): self.id = id self.type = type self.tags = tags diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py index e84cbdeba5dea..b4c53e9e238ba 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py @@ -31,7 +31,7 @@ class ResourceCollection(Model): 'dictionaryofresources': {'key': 'dictionaryofresources', 'type': '{FlattenedProduct}'}, } - def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None, **kwargs): + def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None): self.productresource = productresource self.arrayofresources = arrayofresources self.dictionaryofresources = dictionaryofresources diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py index 38d5be1405c1f..1be642054ecac 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py @@ -36,7 +36,7 @@ class SimpleProduct(BaseProduct): _validation = { 'product_id': {'required': True}, 'max_product_display_name': {'required': True}, - 'capacity': {'required': True}, + 'capacity': {'required': True, 'constant': True}, } _attribute_map = { @@ -48,8 +48,8 @@ class SimpleProduct(BaseProduct): 'odatavalue': {'key': 'details.max_product_image.@odata\\.value', 'type': 'str'}, } - def __init__(self, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None, **kwargs): - super(SimpleProduct, self).__init__(product_id=product_id, description=description, **kwargs) + def __init__(self, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None): + super(SimpleProduct, self).__init__(product_id=product_id, description=description) self.max_product_display_name = max_product_display_name self.capacity = "Large" self.generic_value = generic_value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py index 4eebe2a59088e..326c330b62a5b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py index 7c14ba67a9fd0..eb0b7aa4d4e00 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py @@ -27,5 +27,5 @@ class AvailabilitySetUpdateParameters(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, tags, **kwargs): + def __init__(self, tags): self.tags = tags diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py index 81ec092249336..1e6900d3ef817 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py index c1ba503f44a53..ff3a17c58c7ff 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py index b5c3efad06a28..cb71ed5d5debe 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py @@ -23,5 +23,5 @@ class ArrayOptionalWrapper(Model): 'value': {'key': 'value', 'type': '[str]'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py index 7eb7270bfd325..43685d1c6dba2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py @@ -27,5 +27,5 @@ class ArrayWrapper(Model): 'value': {'key': 'value', 'type': '[str]'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py index 269a6f0c146a3..4d0d010de7de7 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py @@ -24,5 +24,5 @@ class ClassOptionalWrapper(Model): 'value': {'key': 'value', 'type': 'Product'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py index 9e9278497aaf4..ff139aaf09fd4 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py @@ -28,5 +28,5 @@ class ClassWrapper(Model): 'value': {'key': 'value', 'type': 'Product'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py index ec49c66263db1..366aa950c993d 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py @@ -23,5 +23,5 @@ class IntOptionalWrapper(Model): 'value': {'key': 'value', 'type': 'int'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py index 558b905ae14b7..9d20dbc5fba7a 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py @@ -27,5 +27,5 @@ class IntWrapper(Model): 'value': {'key': 'value', 'type': 'int'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py index 438c0c95e8f11..68be843067783 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py @@ -30,6 +30,6 @@ class Product(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id, name=None, **kwargs): + def __init__(self, id, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py index 70f024163a822..b7484c342146e 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py @@ -23,5 +23,5 @@ class StringOptionalWrapper(Model): 'value': {'key': 'value', 'type': 'str'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py index 8494e03473016..659da492dd4f5 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py @@ -27,5 +27,5 @@ class StringWrapper(Model): 'value': {'key': 'value', 'type': 'str'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py index aa49668c0f66d..14f66afcfb516 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py index 5db4f0ba4406a..5ecd97fb73461 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py index 9c02450e6e110..e7270ddf47641 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py @@ -23,7 +23,7 @@ class ChildProduct(Model): """ _validation = { - 'const_property': {'required': True}, + 'const_property': {'required': True, 'constant': True}, } _attribute_map = { @@ -31,6 +31,6 @@ class ChildProduct(Model): 'count': {'key': 'count', 'type': 'int'}, } - def __init__(self, count=None, **kwargs): + def __init__(self, count=None): self.const_property = "constant" self.count = count diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py index 98f60fd2eab82..14f416cef6f00 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py @@ -23,8 +23,8 @@ class ConstantProduct(Model): """ _validation = { - 'const_property': {'required': True}, - 'const_property2': {'required': True}, + 'const_property': {'required': True, 'constant': True}, + 'const_property2': {'required': True, 'constant': True}, } _attribute_map = { @@ -32,6 +32,6 @@ class ConstantProduct(Model): 'const_property2': {'key': 'constProperty2', 'type': 'str'}, } - def __init__(self, **kwargs): + def __init__(self): self.const_property = "constant" self.const_property2 = "constant2" diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py index 7284a2e86309f..3cd8f0d632c08 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py @@ -30,7 +30,7 @@ class Error(Model): 'fields': {'key': 'fields', 'type': 'str'}, } - def __init__(self, code=None, message=None, fields=None, **kwargs): + def __init__(self, code=None, message=None, fields=None): self.code = code self.message = message self.fields = fields diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py index 0447d1ff7f400..c9577fa07f23d 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py @@ -43,9 +43,9 @@ class Product(Model): 'capacity': {'maximum_ex': 100, 'minimum_ex': 0}, 'image': {'pattern': 'http://\w+'}, 'child': {'required': True}, - 'const_child': {'required': True}, - 'const_int': {'required': True}, - 'const_string': {'required': True}, + 'const_child': {'required': True, 'constant': True}, + 'const_int': {'required': True, 'constant': True}, + 'const_string': {'required': True, 'constant': True}, } _attribute_map = { @@ -59,7 +59,7 @@ class Product(Model): 'const_string_as_enum': {'key': 'constStringAsEnum', 'type': 'EnumConst'}, } - def __init__(self, child, display_names=None, capacity=None, image=None, const_string_as_enum=None, **kwargs): + def __init__(self, child, display_names=None, capacity=None, image=None, const_string_as_enum=None): self.display_names = display_names self.capacity = capacity self.image = image diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py index 22a1da7feac0a..3d693bfbb149f 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs b/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs index ff332c771c70e..d987055d49f6f 100644 --- a/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs +++ b/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs @@ -16,7 +16,7 @@ namespace Microsoft.Rest.Generator.Python { public class PythonCodeGenerator : CodeGenerator { - private const string ClientRuntimePackage = "msrest version 0.1.0"; + private const string ClientRuntimePackage = "msrest version 0.2.0"; public PythonCodeGenerator(Settings settings) : base(settings) { diff --git a/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs index c63acff125dfc..dbd8fd040ff5f 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs @@ -100,6 +100,10 @@ public IList Validators { validation.Add("'required': True"); } + if (parameter.IsConstant) + { + validation.Add("'constant': True"); + } if (parameter.Constraints.Any()) { validation.AddRange(BuildValidationParameters(parameter.Constraints)); diff --git a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs index 3e9d595d83f47..4eb487cdfdee5 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs @@ -138,7 +138,7 @@ public virtual string SetupRequires { get { - return "\"msrest>=0.1.0\""; + return "\"msrest>=0.2.0\""; } } diff --git a/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml index d035a46155cf1..40ee94f75cb4b 100644 --- a/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml @@ -90,10 +90,10 @@ else } @EmptyLine - def __init__(self@(Model.MethodParameterDeclaration()), **kwargs): + def __init__(self@(Model.MethodParameterDeclaration())): @if (Model.HasParent) { - @:super(@(Model.Name), self).__init__(@(Model.SuperParameterDeclaration()), **kwargs) + @:super(@(Model.Name), self).__init__(@(Model.SuperParameterDeclaration())) } @{ var propertyList = new List(Model.Properties); diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index 18254317e58e2..40f4c88578686 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -686,21 +686,33 @@ def _instantiate_model(self, response, attrs): :param response: The response model class. :param d_attrs: The deserialized response attributes. """ - subtype = response._get_subtype_map() - try: - kwargs = {k: v for k, v in attrs.items() if k not in subtype} - return response(**kwargs) - except TypeError: - pass - - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to instantiate or populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + if callable(response): + subtype = response._get_subtype_map() + try: + consts = [k for k, v in response._validation.items() + if v.get('constant')] + kwargs = {k: v for k, v in attrs.items() + if k not in subtype and k not in consts} + response_obj = response(**kwargs) + + # We have to do this until we resolve the issue of complex + # constant attributes not being auto-instantiated. + for attr in consts: + setattr(response_obj, attr, attrs.get(attr)) + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format( + kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) def deserialize_data(self, data, data_type): """Process data for deserialization according to data type. From 1f446952e3e26a8bc2845a4984601afb1a252c76 Mon Sep 17 00:00:00 2001 From: Laurent Mazuel Date: Wed, 6 Apr 2016 10:31:59 -0700 Subject: [PATCH 74/99] msrestazure 0.2.1 --- ClientRuntimes/Python/msrestazure/doc/conf.py | 4 ++-- ClientRuntimes/Python/msrestazure/msrestazure/version.py | 2 +- ClientRuntimes/Python/msrestazure/readme.rst | 8 ++++++++ ClientRuntimes/Python/msrestazure/setup.py | 2 +- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/ClientRuntimes/Python/msrestazure/doc/conf.py b/ClientRuntimes/Python/msrestazure/doc/conf.py index 0c188afe88a4c..9a76b3204d5c2 100644 --- a/ClientRuntimes/Python/msrestazure/doc/conf.py +++ b/ClientRuntimes/Python/msrestazure/doc/conf.py @@ -58,9 +58,9 @@ # built documents. # # The short X.Y version. -version = '0.2.0' +version = '0.2.1' # The full version, including alpha/beta/rc tags. -release = '0.2.0' +release = '0.2.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/version.py b/ClientRuntimes/Python/msrestazure/msrestazure/version.py index afe6b750dc35e..23c80b2514da3 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/version.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/version.py @@ -24,4 +24,4 @@ # # -------------------------------------------------------------------------- -msrestazure_version = "0.2.0" +msrestazure_version = "0.2.1" diff --git a/ClientRuntimes/Python/msrestazure/readme.rst b/ClientRuntimes/Python/msrestazure/readme.rst index 6410f9f335943..18a49a8035f2b 100644 --- a/ClientRuntimes/Python/msrestazure/readme.rst +++ b/ClientRuntimes/Python/msrestazure/readme.rst @@ -15,6 +15,14 @@ To install: Release History --------------- +2016-03-31 Version 0.2.1 +++++++++++++++++++++++++ + +**Bugfixes** + +- Fix AzurePollerOperation if Swagger defines provisioning status as enum type (https://github.com/Azure/autorest/pull/892) + + 2016-03-25 Version 0.2.0 ++++++++++++++++++++++++ diff --git a/ClientRuntimes/Python/msrestazure/setup.py b/ClientRuntimes/Python/msrestazure/setup.py index 170ea10a30aa9..d25ce47f33493 100644 --- a/ClientRuntimes/Python/msrestazure/setup.py +++ b/ClientRuntimes/Python/msrestazure/setup.py @@ -28,7 +28,7 @@ setup( name='msrestazure', - version='0.2.0', + version='0.2.1', author='Microsoft Corporation', packages=['msrestazure'], url=('https://github.com/xingwu1/autorest/tree/python/' From 3106fb864836aa60820db28be34560e2315c7402 Mon Sep 17 00:00:00 2001 From: Dan Schulte Date: Wed, 6 Apr 2016 11:56:03 -0700 Subject: [PATCH 75/99] Automatically detect MSBuild tools version in Windows platform * Automatically detect MSBuild tools version in Windows platform * Add initial AzureResourceSchema project and test project --- AutoRest.sln | 25 ++++++ ...Generator.AzureResourceSchema.Tests.csproj | 87 +++++++++++++++++++ .../Properties/AssemblyInfo.cs | 36 ++++++++ .../AzureResourceSchema.Tests/packages.config | 10 +++ ...oRest.Generator.AzureResourceSchema.csproj | 53 +++++++++++ .../Properties/AssemblyInfo.cs | 36 ++++++++ gulpfile.js | 12 ++- 7 files changed, 258 insertions(+), 1 deletion(-) create mode 100644 AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj create mode 100644 AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/Properties/AssemblyInfo.cs create mode 100644 AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config create mode 100644 AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/AutoRest.Generator.AzureResourceSchema.csproj create mode 100644 AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/Properties/AssemblyInfo.cs diff --git a/AutoRest.sln b/AutoRest.sln index f616c9ac420d0..b11b89d798ca5 100644 --- a/AutoRest.sln +++ b/AutoRest.sln @@ -118,6 +118,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Modeler.CompositeS EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Modeler.CompositeSwagger.Tests", "AutoRest\Modelers\CompositeSwagger.Tests\AutoRest.Modeler.CompositeSwagger.Tests.csproj", "{DA37E6A9-5D59-45A3-A809-ABA85031C369}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AzureResourceSchema", "AzureResourceSchema", "{B6A1FC1E-0779-4900-84EE-262DD0E53FF4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Generator.AzureResourceSchema", "AutoRest\Generators\AzureResourceSchema\AzureResourceSchema\AutoRest.Generator.AzureResourceSchema.csproj", "{654344A5-0556-49C7-BFB3-59676D7440D3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Generator.AzureResourceSchema.Tests", "AutoRest\Generators\AzureResourceSchema\AzureResourceSchema.Tests\AutoRest.Generator.AzureResourceSchema.Tests.csproj", "{1C3B4A33-E045-4C8F-9202-1B651A686567}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Net45-Debug|Any CPU = Net45-Debug|Any CPU @@ -366,6 +372,22 @@ Global {DA37E6A9-5D59-45A3-A809-ABA85031C369}.Portable-Debug|Any CPU.Build.0 = Portable-Debug|Any CPU {DA37E6A9-5D59-45A3-A809-ABA85031C369}.Portable-Release|Any CPU.ActiveCfg = Portable-Release|Any CPU {DA37E6A9-5D59-45A3-A809-ABA85031C369}.Portable-Release|Any CPU.Build.0 = Portable-Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Debug|Any CPU.Build.0 = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Release|Any CPU.ActiveCfg = Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Release|Any CPU.Build.0 = Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Debug|Any CPU.Build.0 = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Release|Any CPU.ActiveCfg = Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Release|Any CPU.Build.0 = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Debug|Any CPU.Build.0 = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Release|Any CPU.ActiveCfg = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Release|Any CPU.Build.0 = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Debug|Any CPU.Build.0 = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Release|Any CPU.ActiveCfg = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -407,5 +429,8 @@ Global {74BE0601-FF65-4B46-8A8B-E670056061C4} = {74F7C659-952F-400C-839F-90BED9BB66C3} {31AEC9B5-35C9-4FEA-8420-4C34D3FEAAC8} = {02144BF6-4489-4AFC-9B2D-0306C3DD3C19} {DA37E6A9-5D59-45A3-A809-ABA85031C369} = {02144BF6-4489-4AFC-9B2D-0306C3DD3C19} + {B6A1FC1E-0779-4900-84EE-262DD0E53FF4} = {EF9E346D-70C6-45F5-8FF9-9B734F4A1298} + {654344A5-0556-49C7-BFB3-59676D7440D3} = {B6A1FC1E-0779-4900-84EE-262DD0E53FF4} + {1C3B4A33-E045-4C8F-9202-1B651A686567} = {B6A1FC1E-0779-4900-84EE-262DD0E53FF4} EndGlobalSection EndGlobal diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj new file mode 100644 index 0000000000000..079278b9d781b --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj @@ -0,0 +1,87 @@ + + + + + + Debug + AnyCPU + {1C3B4A33-E045-4C8F-9202-1B651A686567} + Library + Properties + AutoRest.Generator.AzureResourceSchema.Tests + AutoRest.Generator.AzureResourceSchema.Tests + v4.5.2 + 512 + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + ..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll + True + + + ..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll + True + + + ..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll + True + + + ..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll + True + + + + + + + + + + + {654344a5-0556-49c7-bfb3-59676d7440d3} + AutoRest.Generator.AzureResourceSchema + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/Properties/AssemblyInfo.cs b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..d8be4efbcaee3 --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoRest.Generator.AzureResourceSchema.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoRest.Generator.AzureResourceSchema.Tests")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1c3b4a33-e045-4c8f-9202-1b651a686567")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config new file mode 100644 index 0000000000000..64fb5d7b3b792 --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/AutoRest.Generator.AzureResourceSchema.csproj b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/AutoRest.Generator.AzureResourceSchema.csproj new file mode 100644 index 0000000000000..9afbe46b7ef40 --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/AutoRest.Generator.AzureResourceSchema.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {654344A5-0556-49C7-BFB3-59676D7440D3} + Library + Properties + Microsoft.Rest.Generator.AzureResourceSchema + AutoRest.Generator.AzureResourceSchema + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/Properties/AssemblyInfo.cs b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..34f7036d5899a --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("AutoRest.Generator.AzureResourceSchema")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoRest.Generator.AzureResourceSchema")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("654344a5-0556-49c7-bfb3-59676d7440d3")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/gulpfile.js b/gulpfile.js index 46785dfa21046..942ac3a898b84 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -411,13 +411,23 @@ gulp.task('regenerate:expected:samples:azure', function(){ } }); +var msBuildToolsVersion = 12.0; +if (isWindows) { + fs.readdirSync('C:/Program Files (x86)/MSBuild/').forEach(function (item) { + var itemAsFloat = parseFloat(item); + if (itemAsFloat > msBuildToolsVersion) { + msBuildToolsVersion = itemAsFloat; + } + }); +} + var msbuildDefaults = { stdout: process.stdout, stderr: process.stderr, maxBuffer: MAX_BUFFER, verbosity: 'minimal', errorOnFail: true, - toolsVersion: 12.0 + toolsVersion: msBuildToolsVersion }; gulp.task('clean:node_modules', function(cb) { From 7c261364dd3f2fb1c3dcdc9462c1c5d35ee012ef Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Wed, 6 Apr 2016 15:13:12 -0700 Subject: [PATCH 76/99] Android license split into 2 --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 700c37840023e..51223465035c8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,7 +35,8 @@ install: # Install android SDK - mkdir android - wget -qO- "http://dl.google.com/android/android-sdk_r23.0.2-linux.tgz" | tar -zxv -C ./android - - echo y | ./android/android-sdk-linux/tools/android update sdk --all --filter platform-tools,android-23,build-tools-23.0.1,extra-android-support,extra-android-m2repository,extra-google-m2repository --no-ui --force + - echo y | ./android/android-sdk-linux/tools/android update sdk --all --filter platform-tools,android-23,build-tools-23.0.1 --no-ui --force + - echo y | ./android/android-sdk-linux/tools/android update sdk --all --filter extra-android-support,extra-android-m2repository,extra-google-m2repository --no-ui --force - export ANDROID_HOME=`pwd`/android/android-sdk-linux script: - dnvm install 1.0.0-rc1-final -r mono From b73c7841f9f1fb148c44127497fd671275aff764 Mon Sep 17 00:00:00 2001 From: begoldsm Date: Wed, 6 Apr 2016 17:21:28 -0700 Subject: [PATCH 77/99] Fix: https://github.com/Azure/autorest/issues/923 * Fix: https://github.com/Azure/autorest/issues/923 * regenerate tests after sync --- .../AcceptanceTests/azureCustomBaseUri.js | 3 ++- .../autoRestParameterizedHostTestClient.d.ts | 6 +++--- .../autoRestParameterizedHostTestClient.js | 17 +++++++---------- .../AzureServiceClientTemplate.cshtml | 17 +++++++++++------ .../AzureServiceClientTemplateTS.cshtml | 6 +++--- .../AcceptanceTests/acceptanceTests.ts | 5 ++++- .../autoRestParameterizedHostTestClient.d.ts | 6 +++--- .../autoRestParameterizedHostTestClient.js | 17 +++++++---------- .../ServiceClientTemplateModel.cs | 9 +++++++-- .../Templates/ServiceClientTemplate.cshtml | 18 ++++++++++++------ .../Templates/ServiceClientTemplateTS.cshtml | 6 +++--- Samples/azure-storage/Azure.Python/setup.py | 2 +- .../models/check_name_availability_result.py | 2 +- .../models/custom_domain.py | 2 +- .../models/endpoints.py | 2 +- .../storagemanagementclient/models/resource.py | 2 +- .../models/storage_account.py | 4 ++-- ...count_check_name_availability_parameters.py | 2 +- .../storage_account_create_parameters.py | 2 +- .../models/storage_account_keys.py | 2 +- .../models/storage_account_properties.py | 2 +- ...age_account_properties_create_parameters.py | 2 +- ...age_account_properties_update_parameters.py | 2 +- ...torage_account_regenerate_key_parameters.py | 2 +- .../storage_account_update_parameters.py | 2 +- .../storagemanagementclient/models/usage.py | 2 +- .../models/usage_name.py | 2 +- Samples/petstore/Python/setup.py | 2 +- .../Python/swaggerpetstore/models/category.py | 2 +- .../Python/swaggerpetstore/models/order.py | 2 +- .../Python/swaggerpetstore/models/pet.py | 2 +- .../Python/swaggerpetstore/models/tag.py | 2 +- .../Python/swaggerpetstore/models/user.py | 2 +- 33 files changed, 85 insertions(+), 71 deletions(-) diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js index 70960a0e0895e..c50f1f521a66d 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js @@ -18,7 +18,8 @@ var clientOptions = {}; describe('nodejs', function () { describe('Custom BaseUri Client', function () { - var testClient = new customBaseUriClient(credentials, 'host:3000', clientOptions); + clientOptions.host = 'host:3000'; + var testClient = new customBaseUriClient(credentials, clientOptions); it('should return 200', function (done) { testClient.paths.getEmpty('local', function (error, result, request, response) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts index 59cea5a89b930..5092268e0db7c 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts @@ -19,8 +19,6 @@ declare class AutoRestParameterizedHostTestClient { * * @param {credentials} credentials - Gets Azure subscription credentials. * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -30,6 +28,8 @@ declare class AutoRestParameterizedHostTestClient { * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * * @param {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. * * @param {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. @@ -37,7 +37,7 @@ declare class AutoRestParameterizedHostTestClient { * @param {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * */ - constructor(credentials: ServiceClientCredentials, host: string, options: ServiceClientOptions); + constructor(credentials: ServiceClientCredentials, options: ServiceClientOptions); credentials: ServiceClientCredentials; diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js index 9c7f803b703ef..43f7a3c828168 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js @@ -29,8 +29,6 @@ var operations = require('./operations'); * * @param {credentials} credentials - Gets Azure subscription credentials. * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -40,6 +38,8 @@ var operations = require('./operations'); * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * * @param {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. * * @param {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. @@ -47,7 +47,7 @@ var operations = require('./operations'); * @param {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * */ -function AutoRestParameterizedHostTestClient(credentials, host, options) { +function AutoRestParameterizedHostTestClient(credentials, options) { this.host = 'host'; this.acceptLanguage = 'en-US'; this.longRunningOperationRetryTimeout = 30; @@ -55,19 +55,16 @@ function AutoRestParameterizedHostTestClient(credentials, host, options) { if (credentials === null || credentials === undefined) { throw new Error('\'credentials\' cannot be null.'); } - if (host === null || host === undefined) { - throw new Error('\'host\' cannot be null.'); - } if (!options) options = {}; AutoRestParameterizedHostTestClient['super_'].call(this, credentials, options); - if (!this.baseUri) { - this.baseUri = 'http://{accountName}{host}'; - } + this.baseUri = 'http://{accountName}{host}'; this.credentials = credentials; - this.host = host; + if(options.host !== null && options.host !== undefined) { + this.host = options.host; + } if(options.acceptLanguage !== null && options.acceptLanguage !== undefined) { this.acceptLanguage = options.acceptLanguage; } diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml index cdfc5a425ea54..e0639dec63e0b 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml @@ -40,8 +40,8 @@ var ServiceClient = msRestAzure.AzureServiceClient; @:var operations = require('./operations'); } @EmptyLine -@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} -@{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} +@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} +@{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -73,7 +73,7 @@ var ServiceClient = msRestAzure.AzureServiceClient; @: * } */ -function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { +function @(Model.Name)(@(!string.IsNullOrEmpty(Model.RequiredConstructorParameters) ? Model.RequiredConstructorParameters + ", " : "")options) { @foreach (var property in Model.Properties.Where(p => p.DefaultValue != null)) { @:this.@(property.Name) = @(property.DefaultValue); @@ -91,11 +91,16 @@ function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { @if(!Model.IsCustomBaseUri) { @:this.baseUri = baseUri; + @:if (!this.baseUri) { + @:this.baseUri = '@Model.BaseUrl'; + @:} +} +else +{ + @:this.baseUri = '@Model.BaseUrl'; } - if (!this.baseUri) { - this.baseUri = '@Model.BaseUrl'; - } + @foreach (var param in requiredParameters) { @: this.@(param.Name) = @(param.Name); diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml index b7142e35c49e4..5448c378c401c 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml @@ -18,8 +18,8 @@ import { ServiceClientOptions, RequestOptions, ServiceCallback, ServiceClientCre } @EmptyLine declare class @(Model.Name) { - @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} - @{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} + @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} + @{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -52,7 +52,7 @@ declare class @(Model.Name) { @: * } */ - constructor(@(Model.RequiredConstructorParametersTS), options: ServiceClientOptions); + constructor(@(!string.IsNullOrEmpty(Model.RequiredConstructorParametersTS) ? Model.RequiredConstructorParametersTS + ", " : "")options: ServiceClientOptions); @foreach (var property in Model.Properties) { diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index 52e27445dc45e..c7404da84e360 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts @@ -65,7 +65,10 @@ describe('nodejs', function () { describe('Swagger BAT', function () { describe('Custom BaseUri Client', function () { - var testClient = new customBaseUriClient('host:3000', clientOptions); + var customOptions = { + host: 'host:3000' + }; + var testClient = new customBaseUriClient(customOptions); it('should return 200', function (done) { testClient.paths.getEmpty('local', function (error, result, request, response) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts index 7dfd384801704..55373a0e9682c 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts @@ -17,8 +17,6 @@ declare class AutoRestParameterizedHostTestClient { * Initializes a new instance of the AutoRestParameterizedHostTestClient class. * @constructor * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -28,8 +26,10 @@ declare class AutoRestParameterizedHostTestClient { * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * */ - constructor(host: string, options: ServiceClientOptions); + constructor(options: ServiceClientOptions); host: string; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js index 96817a9819895..84e01146a9845 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js @@ -26,8 +26,6 @@ var operations = require('./operations'); * Initializes a new instance of the AutoRestParameterizedHostTestClient class. * @constructor * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -37,21 +35,20 @@ var operations = require('./operations'); * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * */ -function AutoRestParameterizedHostTestClient(host, options) { +function AutoRestParameterizedHostTestClient(options) { this.host = 'host'; - if (host === null || host === undefined) { - throw new Error('\'host\' cannot be null.'); - } if (!options) options = {}; AutoRestParameterizedHostTestClient['super_'].call(this, null, options); - if (!this.baseUri) { - this.baseUri = 'http://{accountName}{host}'; - } - this.host = host; + this.baseUri = 'http://{accountName}{host}'; + if(options.host !== null && options.host !== undefined) { + this.host = options.host; + } this.paths = new operations.Paths(this); this.models = models; msRest.addSerializationMixin(this); diff --git a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs index 577a91bd3e147..ec34d6af04247 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs @@ -154,13 +154,18 @@ public string RequiredConstructorParameters get { var requireParams = new List(); - this.Properties.Where(p => p.IsRequired && !p.IsConstant) + this.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue)) .ForEach(p => requireParams.Add(p.Name.ToCamelCase())); if (!IsCustomBaseUri) { requireParams.Add("baseUri"); } + if(requireParams == null || requireParams.Count == 0) + { + return string.Empty; + } + return string.Join(", ", requireParams); } } @@ -174,7 +179,7 @@ public string RequiredConstructorParametersTS { bool first = true; foreach (var p in this.Properties) { - if (!p.IsRequired || p.IsConstant) + if (!p.IsRequired || p.IsConstant || (p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue))) continue; if (!first) diff --git a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml index 07092323c73f6..055038401726b 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml @@ -37,8 +37,8 @@ var ServiceClient = msRest.ServiceClient; @:var operations = require('./operations'); } @EmptyLine -@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} -@{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} +@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} +@{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -71,7 +71,7 @@ var ServiceClient = msRest.ServiceClient; @: * } */ -function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { +function @(Model.Name)(@(!string.IsNullOrEmpty(Model.RequiredConstructorParameters) ? Model.RequiredConstructorParameters + ", ": "")options) { @foreach (var property in Model.Properties.Where(p => p.DefaultValue != null)) { @:this.@(property.Name) = @(property.DefaultValue); @@ -91,11 +91,17 @@ function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { @if(!Model.IsCustomBaseUri) { @:this.baseUri = baseUri; + + @:if (!this.baseUri) { + @:this.baseUri = '@Model.BaseUrl'; + @:} +} +else +{ + @:this.baseUri = '@Model.BaseUrl'; } - if (!this.baseUri) { - this.baseUri = '@Model.BaseUrl'; - } + @foreach (var param in requiredParameters) { diff --git a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml index 61edf0e006279..c9e479a3c95e4 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml +++ b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml @@ -18,8 +18,8 @@ import { ServiceClientOptions, RequestOptions, ServiceCallback } from 'ms-rest'; } @EmptyLine declare class @(Model.Name) { - @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} - @{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} + @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} + @{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -52,7 +52,7 @@ declare class @(Model.Name) { @: * } */ - constructor(@(Model.RequiredConstructorParametersTS), options: ServiceClientOptions); + constructor(@(!string.IsNullOrEmpty(Model.RequiredConstructorParametersTS) ? Model.RequiredConstructorParametersTS + ", ": "")options: ServiceClientOptions); @foreach (var property in Model.Properties) { diff --git a/Samples/azure-storage/Azure.Python/setup.py b/Samples/azure-storage/Azure.Python/setup.py index f3539db2972f1..b9fe5db7a8f35 100644 --- a/Samples/azure-storage/Azure.Python/setup.py +++ b/Samples/azure-storage/Azure.Python/setup.py @@ -15,7 +15,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py index 0bbc5f5c291e2..1c7ee5c86a0b9 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py @@ -28,7 +28,7 @@ class CheckNameAvailabilityResult(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, name_available=None, reason=None, message=None, **kwargs): + def __init__(self, name_available=None, reason=None, message=None): self.name_available = name_available self.reason = reason self.message = message diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py index ee95d5f7d6163..77a0857f912e8 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py @@ -27,6 +27,6 @@ class CustomDomain(Model): 'use_sub_domain': {'key': 'useSubDomain', 'type': 'bool'}, } - def __init__(self, name, use_sub_domain=None, **kwargs): + def __init__(self, name, use_sub_domain=None): self.name = name self.use_sub_domain = use_sub_domain diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py index de3d2386cd0a1..155622f51543c 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py @@ -27,7 +27,7 @@ class Endpoints(Model): 'file': {'key': 'file', 'type': 'str'}, } - def __init__(self, blob=None, queue=None, table=None, file=None, **kwargs): + def __init__(self, blob=None, queue=None, table=None, file=None): self.blob = blob self.queue = queue self.table = table diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py index 0bcb8add022c5..e784f717664d9 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py @@ -28,7 +28,7 @@ class Resource(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, id=None, name=None, type=None, location=None, tags=None, **kwargs): + def __init__(self, id=None, name=None, type=None, location=None, tags=None): self.id = id self.name = name self.type = type diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py index 3949fa133fb15..274af1b58793d 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py @@ -33,6 +33,6 @@ class StorageAccount(Resource): 'properties': {'key': 'properties', 'type': 'StorageAccountProperties'}, } - def __init__(self, id=None, name=None, type=None, location=None, tags=None, properties=None, **kwargs): - super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, id=None, name=None, type=None, location=None, tags=None, properties=None): + super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags) self.properties = properties diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py index 2ee4a450e04a8..bca58a1d79bab 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py @@ -23,6 +23,6 @@ class StorageAccountCheckNameAvailabilityParameters(Model): 'type': {'key': 'type', 'type': 'str'}, } - def __init__(self, name, type="Microsoft.Storage/storageAccounts", **kwargs): + def __init__(self, name, type="Microsoft.Storage/storageAccounts"): self.name = name self.type = type diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py index d490562665d8b..1f5fe04cca5bc 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py @@ -28,7 +28,7 @@ class StorageAccountCreateParameters(Model): 'properties': {'key': 'properties', 'type': 'StorageAccountPropertiesCreateParameters'}, } - def __init__(self, location, tags=None, properties=None, **kwargs): + def __init__(self, location, tags=None, properties=None): self.location = location self.tags = tags self.properties = properties diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py index 3bc0943541fc0..171d1d785f012 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py @@ -20,6 +20,6 @@ class StorageAccountKeys(Model): 'key2': {'key': 'key2', 'type': 'str'}, } - def __init__(self, key1=None, key2=None, **kwargs): + def __init__(self, key1=None, key2=None): self.key1 = key1 self.key2 = key2 diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py index cb58445a1ce39..2259b66353acf 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py @@ -69,7 +69,7 @@ class StorageAccountProperties(Model): 'secondary_endpoints': {'key': 'secondaryEndpoints', 'type': 'Endpoints'}, } - def __init__(self, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None, **kwargs): + def __init__(self, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None): self.provisioning_state = provisioning_state self.account_type = account_type self.primary_endpoints = primary_endpoints diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py index 4d69da5caf759..b2d63195ed800 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py @@ -22,5 +22,5 @@ class StorageAccountPropertiesCreateParameters(Model): 'account_type': {'key': 'accountType', 'type': 'AccountType'}, } - def __init__(self, account_type, **kwargs): + def __init__(self, account_type): self.account_type = account_type diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py index 9a5fbc12e1783..a9a27ddebd2c1 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py @@ -26,6 +26,6 @@ class StorageAccountPropertiesUpdateParameters(Model): 'custom_domain': {'key': 'customDomain', 'type': 'CustomDomain'}, } - def __init__(self, account_type=None, custom_domain=None, **kwargs): + def __init__(self, account_type=None, custom_domain=None): self.account_type = account_type self.custom_domain = custom_domain diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py index 04c4ce47cf68b..057ea3a49177e 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py @@ -20,5 +20,5 @@ class StorageAccountRegenerateKeyParameters(Model): 'key_name': {'key': 'keyName', 'type': 'str'}, } - def __init__(self, key_name, **kwargs): + def __init__(self, key_name): self.key_name = key_name diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py index f339b37d57d36..39c5cd78d1599 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py @@ -21,6 +21,6 @@ class StorageAccountUpdateParameters(Model): 'properties': {'key': 'properties', 'type': 'StorageAccountPropertiesUpdateParameters'}, } - def __init__(self, tags=None, properties=None, **kwargs): + def __init__(self, tags=None, properties=None): self.tags = tags self.properties = properties diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py index aa81987351d9c..a22a532456d2c 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py @@ -37,7 +37,7 @@ class Usage(Model): 'name': {'key': 'name', 'type': 'UsageName'}, } - def __init__(self, unit, current_value, limit, name, **kwargs): + def __init__(self, unit, current_value, limit, name): self.unit = unit self.current_value = current_value self.limit = limit diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py index 3477988bfbb5c..5edfc23c328e0 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py @@ -21,6 +21,6 @@ class UsageName(Model): 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } - def __init__(self, value=None, localized_value=None, **kwargs): + def __init__(self, value=None, localized_value=None): self.value = value self.localized_value = localized_value diff --git a/Samples/petstore/Python/setup.py b/Samples/petstore/Python/setup.py index f1c57ff21b2c6..bd6e6ed040665 100644 --- a/Samples/petstore/Python/setup.py +++ b/Samples/petstore/Python/setup.py @@ -15,7 +15,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/Samples/petstore/Python/swaggerpetstore/models/category.py b/Samples/petstore/Python/swaggerpetstore/models/category.py index 274c76da920e0..70aae7c8f0d90 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/category.py +++ b/Samples/petstore/Python/swaggerpetstore/models/category.py @@ -19,6 +19,6 @@ class Category(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/Samples/petstore/Python/swaggerpetstore/models/order.py b/Samples/petstore/Python/swaggerpetstore/models/order.py index e02faeb1811a7..8b7b27a2bbe96 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/order.py +++ b/Samples/petstore/Python/swaggerpetstore/models/order.py @@ -32,7 +32,7 @@ class Order(Model): 'complete': {'key': 'complete', 'type': 'bool'}, } - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=None, **kwargs): + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=None): self.id = id self.pet_id = pet_id self.quantity = quantity diff --git a/Samples/petstore/Python/swaggerpetstore/models/pet.py b/Samples/petstore/Python/swaggerpetstore/models/pet.py index eea3cb945d5af..3c01b6a3ba08d 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/pet.py +++ b/Samples/petstore/Python/swaggerpetstore/models/pet.py @@ -37,7 +37,7 @@ class Pet(Model): 'status': {'key': 'status', 'type': 'str'}, } - def __init__(self, name, photo_urls, id=None, category=None, tags=None, status=None, **kwargs): + def __init__(self, name, photo_urls, id=None, category=None, tags=None, status=None): self.id = id self.category = category self.name = name diff --git a/Samples/petstore/Python/swaggerpetstore/models/tag.py b/Samples/petstore/Python/swaggerpetstore/models/tag.py index 34b6460af1321..38d4ffbabcd1f 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/tag.py +++ b/Samples/petstore/Python/swaggerpetstore/models/tag.py @@ -19,6 +19,6 @@ class Tag(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/Samples/petstore/Python/swaggerpetstore/models/user.py b/Samples/petstore/Python/swaggerpetstore/models/user.py index ce6eeadc63758..17d843abff65b 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/user.py +++ b/Samples/petstore/Python/swaggerpetstore/models/user.py @@ -37,7 +37,7 @@ class User(Model): 'user_status': {'key': 'userStatus', 'type': 'int'}, } - def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None, **kwargs): + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): self.id = id self.username = username self.first_name = first_name From 016cef65f6cc532f4c80c53ff73be5368dcd9860 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Sat, 9 Apr 2016 12:28:10 -0700 Subject: [PATCH 78/99] Enhancement to "x-ms-parameterized-host" extension (#929) * Enhancement to x-ms-parameterized-host extension * positionInOperation defaults to first --- ...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 | 108 ++++++++ .../TestServer/swagger/custom-baseUrl.json | 1 + Documentation/swagger-extensions.md | 4 +- gulpfile.js | 3 +- schema/swagger-extensions.json | 9 + 48 files changed, 2379 insertions(+), 18 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 079278b9d781b..01522ea89f2b4 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 64fb5d7b3b792..4e690e09d9def 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 0c6e31b1c1467..0d5c31f0e5182 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 0000000000000..e680cbe6a8731 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/AutoRestParameterizedCustomHostTestClient.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Diagnostics; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Models; + + /// + /// Test Infrastructure for AutoRest + /// + public partial class AutoRestParameterizedCustomHostTestClient : ServiceClient, IAutoRestParameterizedCustomHostTestClient + { + /// + /// The base URI of the service. + /// + internal string BaseUri {get; set;} + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// The subscription id with value 'test12'. + /// + public string SubscriptionId { get; set; } + + /// + /// A string value that is used as a global part of the parameterized host. + /// Default value 'host'. + /// + public string DnsSuffix { get; set; } + + /// + /// Gets the IPaths. + /// + public virtual IPaths Paths { get; private set; } + + /// + /// Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestParameterizedCustomHostTestClient(params DelegatingHandler[] handlers) : base(handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestParameterizedCustomHostTestClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + this.Initialize(); + } + + /// + /// An optional partial-method to perform custom initialization. + /// + partial void CustomInitialize(); + /// + /// Initializes client properties. + /// + private void Initialize() + { + this.Paths = new Paths(this); + this.BaseUri = "{vault}{secret}{dnsSuffix}"; + this.DnsSuffix = "host"; + SerializationSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + CustomInitialize(); + } + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IAutoRestParameterizedCustomHostTestClient.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IAutoRestParameterizedCustomHostTestClient.cs new file mode 100644 index 0000000000000..87db999d81c42 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IAutoRestParameterizedCustomHostTestClient.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Newtonsoft.Json; + using Microsoft.Rest; + using Models; + + /// + /// Test Infrastructure for AutoRest + /// + public partial interface IAutoRestParameterizedCustomHostTestClient : IDisposable + { + /// + /// The base URI of the service. + /// + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + /// + /// The subscription id with value 'test12'. + /// + string SubscriptionId { get; set; } + + /// + /// A string value that is used as a global part of the parameterized + /// host. Default value 'host'. + /// + string DnsSuffix { get; set; } + + + /// + /// Gets the IPaths. + /// + IPaths Paths { get; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IPaths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IPaths.cs new file mode 100644 index 0000000000000..a117b914e7526 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IPaths.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Models; + + /// + /// Paths operations. + /// + public partial interface IPaths + { + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task GetEmptyWithHttpMessagesAsync(string vault, string secret, string keyName, string keyVersion = "v1", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/Error.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/Error.cs new file mode 100644 index 0000000000000..82a4873e61389 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/Error.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Error + { + /// + /// Initializes a new instance of the Error class. + /// + public Error() { } + + /// + /// Initializes a new instance of the Error class. + /// + public Error(int? status = default(int?), string message = default(string)) + { + Status = status; + Message = message; + } + + /// + /// + [JsonProperty(PropertyName = "status")] + public int? Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/ErrorException.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/ErrorException.cs new file mode 100644 index 0000000000000..e3ab1c0a08abc --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/ErrorException.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions.Models +{ + using Microsoft.Rest; + using System; + using System.Net.Http; + using System.Runtime.Serialization; +#if !PORTABLE && !DNXCORE50 + using System.Security.Permissions; +#endif + + /// + /// Exception thrown for an invalid response with Error information. + /// +#if !PORTABLE && !DNXCORE50 + [Serializable] +#endif + public class ErrorException : RestException + { + /// + /// Gets information about the associated HTTP request. + /// + public HttpRequestMessageWrapper Request { get; set; } + + /// + /// Gets information about the associated HTTP response. + /// + public HttpResponseMessageWrapper Response { get; set; } + + /// + /// Gets or sets the body object. + /// + public Error Body { get; set; } + + /// + /// Initializes a new instance of the ErrorException class. + /// + public ErrorException() + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + public ErrorException(string message) + : this(message, null) + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + /// Inner exception. + public ErrorException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !PORTABLE && !DNXCORE50 + /// + /// Initializes a new instance of the ErrorException class. + /// + /// Serialization info. + /// Streaming context. + protected ErrorException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + + /// + /// Serializes content of the exception. + /// + /// Serialization info. + /// Streaming context. + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + if (info == null) + { + throw new ArgumentNullException("info"); + } + + info.AddValue("Request", Request); + info.AddValue("Response", Response); + info.AddValue("Body", Body); + } +#endif + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Paths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Paths.cs new file mode 100644 index 0000000000000..a8599cf083382 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Paths.cs @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Models; + + /// + /// Paths operations. + /// + public partial class Paths : IServiceOperations, IPaths + { + /// + /// Initializes a new instance of the Paths class. + /// + /// + /// Reference to the service client. + /// + public Paths(AutoRestParameterizedCustomHostTestClient client) + { + if (client == null) + { + throw new ArgumentNullException("client"); + } + this.Client = client; + } + + /// + /// Gets a reference to the AutoRestParameterizedCustomHostTestClient + /// + public AutoRestParameterizedCustomHostTestClient Client { get; private set; } + + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task GetEmptyWithHttpMessagesAsync(string vault, string secret, string keyName, string keyVersion = "v1", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (vault == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "vault"); + } + if (secret == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "secret"); + } + if (this.Client.DnsSuffix == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.DnsSuffix"); + } + if (keyName == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "keyName"); + } + if (this.Client.SubscriptionId == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("vault", vault); + tracingParameters.Add("secret", secret); + tracingParameters.Add("keyName", keyName); + tracingParameters.Add("keyVersion", keyVersion); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri; + var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "customuri/{subscriptionId}/{keyName}"; + _url = _url.Replace("{vault}", vault); + _url = _url.Replace("{secret}", secret); + _url = _url.Replace("{dnsSuffix}", this.Client.DnsSuffix); + _url = _url.Replace("{keyName}", Uri.EscapeDataString(keyName)); + _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); + List _queryParameters = new List(); + if (keyVersion != null) + { + _queryParameters.Add(string.Format("keyVersion={0}", Uri.EscapeDataString(keyVersion))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/PathsExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/PathsExtensions.cs new file mode 100644 index 0000000000000..c553414304ed0 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/PathsExtensions.cs @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Models; + + /// + /// Extension methods for Paths. + /// + public static partial class PathsExtensions + { + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The operations group for this extension method. + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + public static void GetEmpty(this IPaths operations, string vault, string secret, string keyName, string keyVersion = "v1") + { + Task.Factory.StartNew(s => ((IPaths)s).GetEmptyAsync(vault, secret, keyName, keyVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The operations group for this extension method. + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + /// + /// The cancellation token. + /// + public static async Task GetEmptyAsync(this IPaths operations, string vault, string secret, string keyName, string keyVersion = "v1", CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.GetEmptyWithHttpMessagesAsync(vault, secret, keyName, keyVersion, null, cancellationToken).ConfigureAwait(false); + } + + } +} diff --git a/AutoRest/Generators/Extensions/Extensions/Extensions.cs b/AutoRest/Generators/Extensions/Extensions/Extensions.cs index e974d9563af25..620a2d594c83e 100644 --- a/AutoRest/Generators/Extensions/Extensions/Extensions.cs +++ b/AutoRest/Generators/Extensions/Extensions/Extensions.cs @@ -12,6 +12,8 @@ using Microsoft.Rest.Modeler.Swagger.Model; using Newtonsoft.Json.Linq; using Newtonsoft.Json; +using System.Text.RegularExpressions; +using Microsoft.Rest.Generator.Properties; namespace Microsoft.Rest.Generator { @@ -27,6 +29,8 @@ public abstract class Extensions public const string FlattenOriginalTypeName = "x-ms-client-flatten-original-type-name"; public const string ParameterGroupExtension = "x-ms-parameter-grouping"; public const string ParameterizedHostExtension = "x-ms-parameterized-host"; + public const string UseSchemePrefix = "useSchemePrefix"; + public const string PositionInOperation = "positionInOperation"; private static bool hostChecked = false; @@ -67,6 +71,28 @@ public static void ProcessParameterizedHost(ServiceClient serviceClient, Setting { var hostTemplate = (string)hostExtension["hostTemplate"]; var parametersJson = hostExtension["parameters"].ToString(); + var useSchemePrefix = true; + if (hostExtension[UseSchemePrefix] != null) + { + useSchemePrefix = bool.Parse(hostExtension[UseSchemePrefix].ToString()); + } + + var position = "first"; + + if (hostExtension[PositionInOperation] != null) + { + var pat = "^(fir|la)st$"; + Regex r = new Regex(pat, RegexOptions.IgnoreCase); + var text = hostExtension[PositionInOperation].ToString(); + Match m = r.Match(text); + if (!m.Success) + { + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, + Resources.InvalidExtensionProperty, text, PositionInOperation, ParameterizedHostExtension, "first, last")); + } + position = text; + } + if (!string.IsNullOrEmpty(parametersJson)) { var jsonSettings = new JsonSerializerSettings @@ -76,7 +102,7 @@ public static void ProcessParameterizedHost(ServiceClient serviceClient, Setting }; var swaggerParams = JsonConvert.DeserializeObject>(parametersJson, jsonSettings); - + List hostParamList = new List(); foreach (var swaggerParameter in swaggerParams) { // Build parameter @@ -89,16 +115,33 @@ public static void ProcessParameterizedHost(ServiceClient serviceClient, Setting parameter.ClientProperty = serviceClient.Properties.Single(p => p.SerializedName.Equals(parameter.SerializedName)); } parameter.Extensions["hostParameter"] = true; + hostParamList.Add(parameter); + } - foreach (var method in serviceClient.Methods) + foreach (var method in serviceClient.Methods) + { + if (position.Equals("first", StringComparison.OrdinalIgnoreCase)) { - method.Parameters.Add(parameter); + method.Parameters.InsertRange(0, hostParamList); } + else + { + method.Parameters.AddRange(hostParamList); + } + } - - serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", - modeler.ServiceDefinition.Schemes[0].ToString().ToLowerInvariant(), - hostTemplate, modeler.ServiceDefinition.BasePath); + if (useSchemePrefix) + { + serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", + modeler.ServiceDefinition.Schemes[0].ToString().ToLowerInvariant(), + hostTemplate, modeler.ServiceDefinition.BasePath); + } + else + { + serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}{1}", + hostTemplate, modeler.ServiceDefinition.BasePath); + } + } } } diff --git a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs index 689a601b826f3..f98e2ea0b022c 100644 --- a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs +++ b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs @@ -69,6 +69,15 @@ internal static string HeadMethodInvalidResponses { } } + /// + /// Looks up a localized string similar to The value '{0}' provided for property '{1}' of extension '{2} is invalid. Valid values are: '{3}'.. + /// + internal static string InvalidExtensionProperty { + get { + return ResourceManager.GetString("InvalidExtensionProperty", resourceCulture); + } + } + /// /// Looks up a localized string similar to Azure resource {0} is missing required 'properties' property.. /// diff --git a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx index d06a580a716fe..7df584f0a47aa 100644 --- a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx +++ b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx @@ -120,6 +120,9 @@ Head method '{0}' should contain only 200 level responses, or 404. + + The value '{0}' provided for property '{1}' of extension '{2} is invalid. Valid values are: '{3}'. + Azure resource {0} is missing required 'properties' property. diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClient.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClient.java new file mode 100644 index 0000000000000..7c5bb29be05d4 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClient.java @@ -0,0 +1,86 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import java.util.List; +import okhttp3.Interceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import com.microsoft.rest.AutoRestBaseUrl; +import com.microsoft.rest.serializer.JacksonMapperAdapter; + +/** + * The interface for AutoRestParameterizedCustomHostTestClient class. + */ +public interface AutoRestParameterizedCustomHostTestClient { + /** + * Gets the URL used as the base for all cloud service requests. + * + * @return the BaseUrl object. + */ + AutoRestBaseUrl getBaseUrl(); + + /** + * Gets the list of interceptors the OkHttp client will execute. + * + * @return the list of interceptors. + */ + List getClientInterceptors(); + + /** + * Sets the logging level for OkHttp client. + * + * @param logLevel the logging level enum. + */ + void setLogLevel(Level logLevel); + + /** + * Gets the adapter for {@link com.fasterxml.jackson.databind.ObjectMapper} for serialization + * and deserialization operations.. + * + * @return the adapter. + */ + JacksonMapperAdapter getMapperAdapter(); + + /** + * Gets The subscription id with value 'test12'.. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + + /** + * Sets The subscription id with value 'test12'.. + * + * @param subscriptionId the subscriptionId value. + */ + void setSubscriptionId(String subscriptionId); + + /** + * Gets A string value that is used as a global part of the parameterized host. Default value 'host'.. + * + * @return the dnsSuffix value. + */ + String getDnsSuffix(); + + /** + * Sets A string value that is used as a global part of the parameterized host. Default value 'host'.. + * + * @param dnsSuffix the dnsSuffix value. + */ + void setDnsSuffix(String dnsSuffix); + + /** + * Gets the PathsOperations object to access its operations. + * @return the PathsOperations object. + */ + PathsOperations getPathsOperations(); + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClientImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClientImpl.java new file mode 100644 index 0000000000000..ad9fe946dc423 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClientImpl.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import com.microsoft.rest.ServiceClient; +import com.microsoft.rest.AutoRestBaseUrl; +import okhttp3.OkHttpClient; +import retrofit2.Retrofit; + +/** + * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + */ +public final class AutoRestParameterizedCustomHostTestClientImpl extends ServiceClient implements AutoRestParameterizedCustomHostTestClient { + /** + * The URL used as the base for all cloud service requests. + */ + private final AutoRestBaseUrl baseUrl; + + /** + * Gets the URL used as the base for all cloud service requests. + * + * @return The BaseUrl value. + */ + public AutoRestBaseUrl getBaseUrl() { + return this.baseUrl; + } + + /** The subscription id with value 'test12'. */ + private String subscriptionId; + + /** + * Gets The subscription id with value 'test12'. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Sets The subscription id with value 'test12'. + * + * @param subscriptionId the subscriptionId value. + */ + public void setSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + } + + /** A string value that is used as a global part of the parameterized host. Default value 'host'. */ + private String dnsSuffix; + + /** + * Gets A string value that is used as a global part of the parameterized host. Default value 'host'. + * + * @return the dnsSuffix value. + */ + public String getDnsSuffix() { + return this.dnsSuffix; + } + + /** + * Sets A string value that is used as a global part of the parameterized host. Default value 'host'. + * + * @param dnsSuffix the dnsSuffix value. + */ + public void setDnsSuffix(String dnsSuffix) { + this.dnsSuffix = dnsSuffix; + } + + /** + * Gets the PathsOperations object to access its operations. + * @return the PathsOperations object. + */ + public PathsOperations getPathsOperations() { + return new PathsOperationsImpl(this.retrofitBuilder.client(clientBuilder.build()).build(), this); + } + + /** + * Initializes an instance of AutoRestParameterizedCustomHostTestClient client. + */ + public AutoRestParameterizedCustomHostTestClientImpl() { + this("{vault}{secret}{dnsSuffix}"); + } + + /** + * Initializes an instance of AutoRestParameterizedCustomHostTestClient client. + * + * @param baseUrl the base URL of the host + */ + private AutoRestParameterizedCustomHostTestClientImpl(String baseUrl) { + super(); + this.baseUrl = new AutoRestBaseUrl(baseUrl); + initialize(); + } + + /** + * Initializes an instance of AutoRestParameterizedCustomHostTestClient client. + * + * @param clientBuilder the builder for building up an {@link OkHttpClient} + * @param retrofitBuilder the builder for building up a {@link Retrofit} + */ + public AutoRestParameterizedCustomHostTestClientImpl(OkHttpClient.Builder clientBuilder, Retrofit.Builder retrofitBuilder) { + super(clientBuilder, retrofitBuilder); + this.baseUrl = new AutoRestBaseUrl("{vault}{secret}{dnsSuffix}"); + initialize(); + } + + @Override + protected void initialize() { + super.initialize(); + this.retrofitBuilder.baseUrl(baseUrl); + } +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperations.java new file mode 100644 index 0000000000000..6273f3426d73c --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperations.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import fixtures.custombaseurimoreoptions.models.ErrorException; +import java.io.IOException; + +/** + * An instance of this class provides access to all the operations defined + * in PathsOperations. + */ +public interface PathsOperations { + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse getEmpty(String vault, String secret, String keyName) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getEmptyAsync(String vault, String secret, String keyName, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse getEmpty(String vault, String secret, String keyName, String keyVersion) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getEmptyAsync(String vault, String secret, String keyName, String keyVersion, final ServiceCallback serviceCallback) throws IllegalArgumentException; + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperationsImpl.java new file mode 100644 index 0000000000000..13994720257bd --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperationsImpl.java @@ -0,0 +1,245 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import com.google.common.reflect.TypeToken; +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.ServiceResponseBuilder; +import com.microsoft.rest.ServiceResponseCallback; +import fixtures.custombaseurimoreoptions.models.ErrorException; +import java.io.IOException; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.http.GET; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.Response; +import retrofit2.Retrofit; + +/** + * An instance of this class provides access to all the operations defined + * in PathsOperations. + */ +public final class PathsOperationsImpl implements PathsOperations { + /** The Retrofit service to perform REST calls. */ + private PathsService service; + /** The service client containing this operation class. */ + private AutoRestParameterizedCustomHostTestClient client; + + /** + * Initializes an instance of PathsOperations. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public PathsOperationsImpl(Retrofit retrofit, AutoRestParameterizedCustomHostTestClient client) { + this.service = retrofit.create(PathsService.class); + this.client = client; + } + + /** + * The interface defining all the services for PathsOperations to be + * used by Retrofit to perform actually REST calls. + */ + interface PathsService { + @Headers("Content-Type: application/json; charset=utf-8") + @GET("customuri/{subscriptionId}/{keyName}") + Call getEmpty(@Path("keyName") String keyName, @Path("subscriptionId") String subscriptionId, @Query("keyVersion") String keyVersion); + + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse getEmpty(String vault, String secret, String keyName) throws ErrorException, IOException, IllegalArgumentException { + if (vault == null) { + throw new IllegalArgumentException("Parameter vault is required and cannot be null."); + } + if (secret == null) { + throw new IllegalArgumentException("Parameter secret is required and cannot be null."); + } + if (this.client.getDnsSuffix() == null) { + throw new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null."); + } + if (keyName == null) { + throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); + } + if (this.client.getSubscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null."); + } + final String keyVersion = null; + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + return getEmptyDelegate(call.execute()); + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getEmptyAsync(String vault, String secret, String keyName, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (vault == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter vault is required and cannot be null.")); + return null; + } + if (secret == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter secret is required and cannot be null.")); + return null; + } + if (this.client.getDnsSuffix() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null.")); + return null; + } + if (keyName == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter keyName is required and cannot be null.")); + return null; + } + if (this.client.getSubscriptionId() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null.")); + return null; + } + final String keyVersion = null; + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getEmptyDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse getEmpty(String vault, String secret, String keyName, String keyVersion) throws ErrorException, IOException, IllegalArgumentException { + if (vault == null) { + throw new IllegalArgumentException("Parameter vault is required and cannot be null."); + } + if (secret == null) { + throw new IllegalArgumentException("Parameter secret is required and cannot be null."); + } + if (this.client.getDnsSuffix() == null) { + throw new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null."); + } + if (keyName == null) { + throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); + } + if (this.client.getSubscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null."); + } + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + return getEmptyDelegate(call.execute()); + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getEmptyAsync(String vault, String secret, String keyName, String keyVersion, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (vault == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter vault is required and cannot be null.")); + return null; + } + if (secret == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter secret is required and cannot be null.")); + return null; + } + if (this.client.getDnsSuffix() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null.")); + return null; + } + if (keyName == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter keyName is required and cannot be null.")); + return null; + } + if (this.client.getSubscriptionId() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null.")); + return null; + } + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getEmptyDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getEmptyDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/Error.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/Error.java new file mode 100644 index 0000000000000..73232cf4ed434 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/Error.java @@ -0,0 +1,64 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions.models; + + +/** + * The Error model. + */ +public class Error { + /** + * The status property. + */ + private Integer status; + + /** + * The message property. + */ + private String message; + + /** + * Get the status value. + * + * @return the status value + */ + public Integer getStatus() { + return this.status; + } + + /** + * Set the status value. + * + * @param status the status value to set + */ + public void setStatus(Integer status) { + this.status = status; + } + + /** + * Get the message value. + * + * @return the message value + */ + public String getMessage() { + return this.message; + } + + /** + * Set the message value. + * + * @param message the message value to set + */ + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/ErrorException.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/ErrorException.java new file mode 100644 index 0000000000000..0c4458e200dac --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/ErrorException.java @@ -0,0 +1,89 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions.models; + +import com.microsoft.rest.AutoRestException; +import retrofit2.Response; + +/** + * Exception thrown for an invalid response with Error information. + */ +public class ErrorException extends AutoRestException { + /** + * Information about the associated HTTP response. + */ + private Response response; + /** + * The actual response body. + */ + private Error body; + /** + * Initializes a new instance of the ErrorException class. + */ + public ErrorException() { } + /** + * Initializes a new instance of the ErrorException class. + * + * @param message The exception message. + */ + public ErrorException(final String message) { + super(message); + } + /** + * Initializes a new instance of the ErrorException class. + * + * @param message the exception message + * @param cause exception that caused this exception to occur + */ + public ErrorException(final String message, final Throwable cause) { + super(message, cause); + } + /** + * Initializes a new instance of the ErrorException class. + * + * @param cause exception that caused this exception to occur + */ + public ErrorException(final Throwable cause) { + super(cause); + } + /** + * Gets information about the associated HTTP response. + * + * @return the HTTP response + */ + public Response getResponse() { + return response; + } + /** + * Gets the HTTP response body. + * + * @return the response body + */ + public Error getBody() { + return body; + } + /** + * Sets the HTTP response. + * + * @param response the HTTP response + */ + public void setResponse(Response response) { + this.response = response; + } + /** + * Sets the HTTP response body. + * + * @param body the response body + */ + public void setBody(Error body) { + this.body = body; + } +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/package-info.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/package-info.java new file mode 100644 index 0000000000000..b5c9a91ec97d8 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/package-info.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +/** + * This package contains the model classes for AutoRestParameterizedCustomHostTestClient. + * Test Infrastructure for AutoRest. + */ +package fixtures.custombaseurimoreoptions.models; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/package-info.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/package-info.java new file mode 100644 index 0000000000000..a6434083eb1c5 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/package-info.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +/** + * This package contains the classes for AutoRestParameterizedCustomHostTestClient. + * Test Infrastructure for AutoRest. + */ +package fixtures.custombaseurimoreoptions; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index c7404da84e360..0a81b3420068b 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts @@ -32,7 +32,7 @@ import dictionaryModels = require('../Expected/AcceptanceTests/BodyDictionary/mo import httpClient = require('../Expected/AcceptanceTests/Http/autoRestHttpInfrastructureTestService'); import formDataClient = require('../Expected/AcceptanceTests/BodyFormData/autoRestSwaggerBATFormDataService'); import customBaseUriClient = require('../Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient'); - +import customBaseUriClientMoreOptions = require('../Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient'); var dummyToken = 'dummy12321343423'; var credentials = new msRest.TokenCredentials(dummyToken); @@ -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 0000000000000..98c22ab85f4de --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.d.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +import { ServiceClientOptions, RequestOptions, ServiceCallback } from 'ms-rest'; +import * as operations from "./operations"; + +declare class AutoRestParameterizedCustomHostTestClient { + /** + * @class + * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + * @constructor + * + * @param {string} subscriptionId - The subscription id with value 'test12'. + * + * @param {object} [options] - The parameter options + * + * @param {Array} [options.filters] - Filters to be added to the request pipeline + * + * @param {object} [options.requestOptions] - Options for the underlying request object + * {@link https://github.com/request/request#requestoptions-callback Options doc} + * + * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy + * + * @param {string} [options.dnsSuffix] - A string value that is used as a global part of the parameterized host. Default value 'host'. + * + */ + constructor(subscriptionId: string, options: ServiceClientOptions); + + subscriptionId: string; + + dnsSuffix: string; + + // Operation groups + paths: operations.Paths; + } + +export = AutoRestParameterizedCustomHostTestClient; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.js new file mode 100644 index 0000000000000..391f7b50deb38 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.js @@ -0,0 +1,65 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +/* jshint latedef:false */ +/* jshint forin:false */ +/* jshint noempty:false */ + +'use strict'; + +var util = require('util'); +var msRest = require('ms-rest'); +var ServiceClient = msRest.ServiceClient; + +var models = require('./models'); +var operations = require('./operations'); + +/** + * @class + * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + * @constructor + * + * @param {string} subscriptionId - The subscription id with value 'test12'. + * + * @param {object} [options] - The parameter options + * + * @param {Array} [options.filters] - Filters to be added to the request pipeline + * + * @param {object} [options.requestOptions] - Options for the underlying request object + * {@link https://github.com/request/request#requestoptions-callback Options doc} + * + * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy + * + * @param {string} [options.dnsSuffix] - A string value that is used as a global part of the parameterized host. Default value 'host'. + * + */ +function AutoRestParameterizedCustomHostTestClient(subscriptionId, options) { + this.dnsSuffix = 'host'; + if (subscriptionId === null || subscriptionId === undefined) { + throw new Error('\'subscriptionId\' cannot be null.'); + } + + if (!options) options = {}; + + AutoRestParameterizedCustomHostTestClient['super_'].call(this, null, options); + this.baseUri = '{vault}{secret}{dnsSuffix}'; + this.subscriptionId = subscriptionId; + + if(options.dnsSuffix !== null && options.dnsSuffix !== undefined) { + this.dnsSuffix = options.dnsSuffix; + } + this.paths = new operations.Paths(this); + this.models = models; + msRest.addSerializationMixin(this); +} + +util.inherits(AutoRestParameterizedCustomHostTestClient, ServiceClient); + +module.exports = AutoRestParameterizedCustomHostTestClient; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/errorModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/errorModel.js new file mode 100644 index 0000000000000..663be0f4aaa8c --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/errorModel.js @@ -0,0 +1,58 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +'use strict'; + +/** + * @class + * Initializes a new instance of the ErrorModel class. + * @constructor + * @member {number} [status] + * + * @member {string} [message] + * + */ +function ErrorModel() { +} + +/** + * Defines the metadata of ErrorModel + * + * @returns {object} metadata of ErrorModel + * + */ +ErrorModel.prototype.mapper = function () { + return { + required: false, + serializedName: 'Error', + type: { + name: 'Composite', + className: 'ErrorModel', + modelProperties: { + status: { + required: false, + serializedName: 'status', + type: { + name: 'Number' + } + }, + message: { + required: false, + serializedName: 'message', + type: { + name: 'String' + } + } + } + } + }; +}; + +module.exports = ErrorModel; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.d.ts new file mode 100644 index 0000000000000..5405a199a0755 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.d.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + + +/** + * @class + * Initializes a new instance of the ErrorModel class. + * @constructor + * @member {number} [status] + * + * @member {string} [message] + * + */ +export interface ErrorModel { + status?: number; + message?: string; +} diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.js new file mode 100644 index 0000000000000..3430295d8bd86 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.js @@ -0,0 +1,17 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +/* jshint latedef:false */ +/* jshint forin:false */ +/* jshint noempty:false */ + +'use strict'; + +exports.ErrorModel = require('./errorModel'); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.d.ts new file mode 100644 index 0000000000000..3fa4ea5d9bf14 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.d.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. +*/ + +import { ServiceClientOptions, RequestOptions, ServiceCallback } from 'ms-rest'; +import * as models from '../models'; + + +/** + * @class + * Paths + * __NOTE__: An instance of this class is automatically created for an + * instance of the AutoRestParameterizedCustomHostTestClient. + */ +export interface Paths { + + /** + * Get a 200 to test a valid base uri + * + * @param {string} vault The vault name, e.g. https://myvault + * + * @param {string} secret Secret value. + * + * @param {string} keyName The key name with value 'key1'. + * + * @param {object} [options] Optional Parameters. + * + * @param {string} [options.keyVersion] The key version. Default value 'v1'. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getEmpty(vault: string, secret: string, keyName: string, options: { keyVersion? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getEmpty(vault: string, secret: string, keyName: string, callback: ServiceCallback): void; +} diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.js new file mode 100644 index 0000000000000..412d88e67668a --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.js @@ -0,0 +1,17 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +/* jshint latedef:false */ +/* jshint forin:false */ +/* jshint noempty:false */ + +'use strict'; + +exports.Paths = require('./paths'); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/paths.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/paths.js new file mode 100644 index 0000000000000..dc2c66f05c60e --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/paths.js @@ -0,0 +1,167 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +'use strict'; + +var util = require('util'); +var msRest = require('ms-rest'); +var WebResource = msRest.WebResource; + +/** + * @class + * Paths + * __NOTE__: An instance of this class is automatically created for an + * instance of the AutoRestParameterizedCustomHostTestClient. + * Initializes a new instance of the Paths class. + * @constructor + * + * @param {AutoRestParameterizedCustomHostTestClient} client Reference to the service client. + */ +function Paths(client) { + this.client = client; +} + +/** + * Get a 200 to test a valid base uri + * + * @param {string} vault The vault name, e.g. https://myvault + * + * @param {string} secret Secret value. + * + * @param {string} keyName The key name with value 'key1'. + * + * @param {object} [options] Optional Parameters. + * + * @param {string} [options.keyVersion] The key version. Default value 'v1'. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Paths.prototype.getEmpty = function (vault, secret, keyName, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + var keyVersion = (options && options.keyVersion !== undefined) ? options.keyVersion : 'v1'; + // Validate + try { + if (vault === null || vault === undefined || typeof vault.valueOf() !== 'string') { + throw new Error('vault cannot be null or undefined and it must be of type string.'); + } + if (secret === null || secret === undefined || typeof secret.valueOf() !== 'string') { + throw new Error('secret cannot be null or undefined and it must be of type string.'); + } + if (this.client.dnsSuffix === null || this.client.dnsSuffix === undefined || typeof this.client.dnsSuffix.valueOf() !== 'string') { + throw new Error('this.client.dnsSuffix cannot be null or undefined and it must be of type string.'); + } + if (keyName === null || keyName === undefined || typeof keyName.valueOf() !== 'string') { + throw new Error('keyName cannot be null or undefined and it must be of type string.'); + } + if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') { + throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.'); + } + if (keyVersion !== null && keyVersion !== undefined && typeof keyVersion.valueOf() !== 'string') { + throw new Error('keyVersion must be of type string.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//customuri/{subscriptionId}/{keyName}'; + requestUrl = requestUrl.replace('{vault}', vault); + requestUrl = requestUrl.replace('{secret}', secret); + requestUrl = requestUrl.replace('{dnsSuffix}', this.client.dnsSuffix); + requestUrl = requestUrl.replace('{keyName}', encodeURIComponent(keyName)); + requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId)); + var queryParameters = []; + if (keyVersion !== null && keyVersion !== undefined) { + queryParameters.push('keyVersion=' + encodeURIComponent(keyVersion)); + } + if (queryParameters.length > 0) { + requestUrl += '?' + queryParameters.join('&'); + } + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + + +module.exports = Paths; diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/__init__.py new file mode 100644 index 0000000000000..6711cf5b14df9 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from .auto_rest_parameterized_custom_host_test_client import AutoRestParameterizedCustomHostTestClient, AutoRestParameterizedCustomHostTestClientConfiguration +from .version import VERSION + +__all__ = [ + 'AutoRestParameterizedCustomHostTestClient', + 'AutoRestParameterizedCustomHostTestClientConfiguration' +] + +__version__ = VERSION + diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/auto_rest_parameterized_custom_host_test_client.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/auto_rest_parameterized_custom_host_test_client.py new file mode 100644 index 0000000000000..1e9140c3e5f70 --- /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 0000000000000..0d097b4f2a6cf --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/credentials.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.authentication import ( + BasicAuthentication, + BasicTokenAuthentication, + OAuthTokenAuthentication) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/exceptions.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/exceptions.py new file mode 100644 index 0000000000000..c3cc00226060c --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/exceptions.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.exceptions import ( + ClientException, + SerializationError, + DeserializationError, + TokenExpiredError, + ClientRequestError, + AuthenticationError, + HttpOperationError, + ValidationError, +) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/__init__.py new file mode 100644 index 0000000000000..fd6d517a47113 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/__init__.py @@ -0,0 +1,16 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from .error import Error, ErrorException + +__all__ = [ + 'Error', 'ErrorException', +] diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/error.py new file mode 100644 index 0000000000000..c2d19e377e004 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/error.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.serialization import Model +from msrest.exceptions import HttpOperationError + + +class Error(Model): + """Error + + :param status: + :type status: int + :param message: + :type message: str + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'int'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__(self, status=None, message=None): + self.status = status + self.message = message + + +class ErrorException(HttpOperationError): + """Server responsed with exception of type: 'Error'. + + :param deserialize: A deserializer + :param response: Server response to be deserialized. + """ + + def __init__(self, deserialize, response, *args): + + super(ErrorException, self).__init__(deserialize, response, 'Error', *args) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/__init__.py new file mode 100644 index 0000000000000..fa4a82a28df55 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/__init__.py @@ -0,0 +1,16 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from .paths import Paths + +__all__ = [ + 'Paths', +] diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/paths.py new file mode 100644 index 0000000000000..2c43f455f742d --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/paths.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.pipeline import ClientRawResponse + +from .. import models + + +class Paths(object): + """Paths operations. + + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An objec model deserializer. + """ + + def __init__(self, client, config, serializer, deserializer): + + self._client = client + self._serialize = serializer + self._deserialize = deserializer + + self.config = config + + def get_empty( + self, vault, secret, key_name, key_version="v1", custom_headers={}, raw=False, **operation_config): + """ + Get a 200 to test a valid base uri + + :param vault: The vault name, e.g. https://myvault + :type vault: str + :param secret: Secret value. + :type secret: str + :param key_name: The key name with value 'key1'. + :type key_name: str + :param key_version: The key version. Default value 'v1'. + :type key_version: str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/customuri/{subscriptionId}/{keyName}' + path_format_arguments = { + 'vault': self._serialize.url("vault", vault, 'str', skip_quote=True), + 'secret': self._serialize.url("secret", secret, 'str', skip_quote=True), + 'dnsSuffix': self._serialize.url("self.config.dns_suffix", self.config.dns_suffix, 'str', skip_quote=True), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + if key_version is not None: + query_parameters['keyVersion'] = self._serialize.query("key_version", key_version, 'str') + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/version.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/version.py new file mode 100644 index 0000000000000..a39916c162cec --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/version.py @@ -0,0 +1,13 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0" + diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/setup.py new file mode 100644 index 0000000000000..3521fb6abef92 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/setup.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# coding: utf-8 + +from setuptools import setup, find_packages + +NAME = "autorestparameterizedcustomhosttestclient" +VERSION = "1.0.0" + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = ["msrest>=0.2.0"] + +setup( + name=NAME, + version=VERSION, + description="AutoRestParameterizedCustomHostTestClient", + author_email="", + url="", + keywords=["Swagger", "AutoRestParameterizedCustomHostTestClient"], + install_requires=REQUIRES, + packages=find_packages(), + include_package_data=True, + long_description="""\ + Test Infrastructure for AutoRest + """ +) diff --git a/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj b/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj index 551692fe3e198..b6cfb6ea96c3e 100644 --- a/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj +++ b/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj @@ -125,6 +125,10 @@ + + + + diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index f0da0d60682c8..8bb3b105ba765 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 2eee79cadfc33..85d074cdeceb2 100644 --- a/AutoRest/TestServer/server/routes/customUri.js +++ b/AutoRest/TestServer/server/routes/customUri.js @@ -9,6 +9,17 @@ var specials = function (coverage) { coverage['CustomBaseUri']++; res.status(200).end(); }); + + router.get('/:subscriptionId/:keyName', function (req, res, next) { + if (req.params.subscriptionId === 'test12' && req.params.keyName === 'key1' + && Object.keys(req.query).length == 1 && req.query.keyVersion === 'v1') { + coverage['CustomBaseUriMoreOptions']++; + res.status(200).end(); + } else { + utils.send400(res, next, 'Either one of the path parameters (subscriptionId=test12, keyName=key1) or query parameter (keyVersion=v1) did not match. ' + + 'Received parameters are: subscriptionId ' + subscriptionId + ', keyName ' + keyName + ', keyVersion ' + keyVersion); + } + }); } specials.prototype.router = router; diff --git a/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json new file mode 100644 index 0000000000000..75ef7453976ee --- /dev/null +++ b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json @@ -0,0 +1,108 @@ +{ + "swagger": "2.0", + "info": { + "title": "AutoRest Parameterized Custom Host Test Client", + "description": "Test Infrastructure for AutoRest", + "version": "1.0.0" + }, + "x-ms-parameterized-host": { + "hostTemplate": "{vault}{secret}{dnsSuffix}", + "useSchemePrefix": false, + "parameters": [ + { + "name": "vault", + "description": "The vault name, e.g. https://myvault", + "required": true, + "type": "string", + "in": "path", + "x-ms-skip-url-encoding": true + }, + { + "name": "secret", + "description": "Secret value.", + "required": true, + "type": "string", + "in": "path", + "x-ms-skip-url-encoding": true + }, + { + "$ref": "#/parameters/dnsSuffix" + } + ] + }, + "produces": [ "application/json" ], + "consumes": [ "application/json" ], + "paths": { + "/customuri/{subscriptionId}/{keyName}": { + "get": { + "operationId": "paths_getEmpty", + "description": "Get a 200 to test a valid base uri", + "tags": [ + "Path Operations" + ], + "parameters": [ + { + "name": "keyName", + "in": "path", + "required": true, + "type": "string", + "description": "The key name with value 'key1'." + }, + { + "$ref": "#/parameters/SubscriptionIdParameter" + }, + { + "name": "keyVersion", + "in": "query", + "required": false, + "type": "string", + "default": "v1", + "description": "The key version. Default value 'v1'." + } + ], + "responses": { + "200": { + "description": "Successfully received a 200 response" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + } + }, + "parameters": { + "SubscriptionIdParameter": { + "name": "subscriptionId", + "in": "path", + "required": true, + "type": "string", + "description": "The subscription id with value 'test12'." + }, + "dnsSuffix": { + "name": "dnsSuffix", + "description": "A string value that is used as a global part of the parameterized host. Default value 'host'.", + "type": "string", + "required": false, + "default": "host", + "in": "path", + "x-ms-skip-url-encoding": true + } + }, + "definitions": { + "Error": { + "properties": { + "status": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } +} diff --git a/AutoRest/TestServer/swagger/custom-baseUrl.json b/AutoRest/TestServer/swagger/custom-baseUrl.json index 5ca07d1627a06..aaa0309f4b94a 100644 --- a/AutoRest/TestServer/swagger/custom-baseUrl.json +++ b/AutoRest/TestServer/swagger/custom-baseUrl.json @@ -8,6 +8,7 @@ "host": "badhost", "x-ms-parameterized-host": { "hostTemplate": "{accountName}{host}", + "positionInOperation": "last", "parameters": [ { "name": "accountName", diff --git a/Documentation/swagger-extensions.md b/Documentation/swagger-extensions.md index cb3bed17ab585..f606ac335567d 100644 --- a/Documentation/swagger-extensions.md +++ b/Documentation/swagger-extensions.md @@ -389,7 +389,9 @@ 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. -parameters | [Array of Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) | The list of parameters that are used within the hostTemplate. This can include both reference parameters as well as explicit parameters. Note that "in" is **required** and **must be** set to "path" +useSchemePrefix | `boolean` | **Optional, Default: true**. Specifes whether to prepend the default scheme a.k.a protocol to the base uri of client. +positionInOperation | `string` | **Optional, Default: first**. Specifies whether the list of parameters will appear in the beginning or in the end, in the method signature for every operation. The order within the parameters provided in the below mentioned array will be preserved. Either the array of parameters will be prepended or appended, based on the value provided over here. Valid values are **"first", "last"**. Every method/operation in any programming language has parameters categorized into two buckets **"required"** and **"optional"**. It is natural for optional paramaters to appear in the end in a method signature. **This aspect will be preserved, while prepending(first) or appending(last) hostTemplate parameters .** +parameters | [Array of Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) | The list of parameters that are used within the hostTemplate. This can include both reference parameters as well as explicit parameters. Note that "in" is **required** and **must be** set to **"path"**. The reference parameters will be treated as **global parameters** and will end up as property of the client. **Example**: Using both explicit and reference parameters diff --git a/gulpfile.js b/gulpfile.js index 942ac3a898b84..e7bc6be0adf4a 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -63,7 +63,8 @@ var defaultMappings = { 'AcceptanceTests/Url': '../../../TestServer/swagger/url.json', 'AcceptanceTests/Validation': '../../../TestServer/swagger/validation.json', 'AcceptanceTests/CustomBaseUri': '../../../TestServer/swagger/custom-baseUrl.json', - 'AcceptanceTests/ModelFlattening': '../../../TestServer/swagger/model-flattening.json', + 'AcceptanceTests/CustomBaseUriMoreOptions': '../../../TestServer/swagger/custom-baseUrl-more-options.json', + 'AcceptanceTests/ModelFlattening': '../../../TestServer/swagger/model-flattening.json' }; var rubyMappings = { diff --git a/schema/swagger-extensions.json b/schema/swagger-extensions.json index 199078f32eee3..6e6476c56dbf0 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": "first", + "pattern": "^(fir|la)st$" + }, "parameters": { "$ref": "#/definitions/xmsHostParametersList" } From 0e2d13a68cc00dca17c4f548298bbbebd24259b2 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Sun, 10 Apr 2016 20:15:51 -0700 Subject: [PATCH 79/99] Update swagger-extensions.md --- Documentation/swagger-extensions.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Documentation/swagger-extensions.md b/Documentation/swagger-extensions.md index f606ac335567d..1fbf0efe46d71 100644 --- a/Documentation/swagger-extensions.md +++ b/Documentation/swagger-extensions.md @@ -394,10 +394,14 @@ positionInOperation | `string` | **Optional, Default: first**. Specifies whether parameters | [Array of Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) | The list of parameters that are used within the hostTemplate. This can include both reference parameters as well as explicit parameters. Note that "in" is **required** and **must be** set to **"path"**. The reference parameters will be treated as **global parameters** and will end up as property of the client. **Example**: -Using both explicit and reference parameters +- Using both explicit and reference parameters. + - Since "useSchemePrefix" is not specified, it's default value true will be applied. The user is expected to provide only the value of accountName. The generated code will fit it as a part of the url. + - Since "positionInOperation" with value "last" is specified, "accountName" will be the last required parameter in every method. "adlaJobDnsSuffixInPath" will be a property on the client as it is defined in the global parameters section and is referenced here. + ```js "x-ms-parameterized-host": { "hostTemplate": "{accountName}.{adlaJobDnsSuffix}", + "positionInOperation": "last", "parameters": [ { "name": "accountName", @@ -423,10 +427,13 @@ Using both explicit and reference parameters "description": "Gets the DNS suffix used as the base for all Azure Data Lake Analytics Job service requests." } ``` -Using only explicit parameters +- Using explicit parameters and specifying the positionInOperation and schemePrefix. + - This means that accountName will be the first required parameter in all the methods and the user is expected to provide a url (protocol + accountName), since "useSchemePrfix" is set to false. ```js "x-ms-parameterized-host": { "hostTemplate": "{accountName}.mystaticsuffix.com", + "useSchemePrefix": false, + "positionInOperation": "first", "parameters": [ { "name": "accountName", From 296bb25496b473dceb167a807ffb4ff5a7704d79 Mon Sep 17 00:00:00 2001 From: Brody Berg Date: Wed, 13 Apr 2016 09:46:39 -0700 Subject: [PATCH 80/99] Correct bug link re: multi (#939) --- AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs b/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs index edfba8a2c1340..f9ee08f3c57f6 100644 --- a/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs +++ b/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs @@ -80,7 +80,7 @@ private static void AddCollectionFormat(SwaggerParameter swaggerParameter, Strin break; case CollectionFormat.Multi: - // TODO multi is not supported yet: http://vstfrd:8080/Azure/RD/_workitems/edit/3172867 + // TODO multi is not supported yet: https://github.com/Azure/autorest/issues/717 throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.MultiCollectionFormatNotSupported, swaggerParameter.Name)); From 1833d260869ba361676fa0b99bfd1928d5a37dbd Mon Sep 17 00:00:00 2001 From: tbombach Date: Wed, 13 Apr 2016 15:39:59 -0700 Subject: [PATCH 81/99] Adding a new primary type for unix time and updating namers to handle this type --- .../ClientModel/KnownPrimaryType.cs | 3 +- .../CSharp/CSharp/CSharpCodeNamer.cs | 7 +- .../CSharp/CSharp/ClientModelExtensions.cs | 5 ++ .../TemplateModels/MethodTemplateModel.cs | 18 ++++- .../CSharp/Templates/ModelTemplate.cshtml | 8 ++ .../Java/Java/TypeModels/PrimaryTypeModel.cs | 4 + .../NodeJS/NodeJS/NodeJsCodeNamer.cs | 4 + .../Python/Python/PythonCodeNamer.cs | 4 + .../Generators/Ruby/Ruby/RubyCodeNamer.cs | 4 + .../Modelers/Swagger/Model/SwaggerObject.cs | 4 + .../Serialization/UnixTimeJsonConverter.cs | 76 +++++++++++++++++++ 11 files changed, 134 insertions(+), 3 deletions(-) create mode 100644 ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs diff --git a/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs b/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs index 200dcfe018dfc..94dd5ffd7b726 100644 --- a/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs +++ b/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs @@ -25,6 +25,7 @@ public enum KnownPrimaryType Boolean, Credentials, Uuid, - Base64Url + Base64Url, + UnixTime } } diff --git a/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs b/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs index d9562cf4ca63c..3504b01cb57d2 100644 --- a/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs +++ b/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs @@ -297,6 +297,10 @@ protected virtual IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "ServiceClientCredentials"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "DateTime"; + } else if (primaryType.Type == KnownPrimaryType.Uuid) { primaryType.Name = "Guid"; @@ -401,7 +405,8 @@ public override string EscapeDefaultValue(string defaultValue, IType type) primaryType.Type == KnownPrimaryType.DateTimeRfc1123 || primaryType.Type == KnownPrimaryType.TimeSpan || primaryType.Type == KnownPrimaryType.ByteArray || - primaryType.Type == KnownPrimaryType.Base64Url) + primaryType.Type == KnownPrimaryType.Base64Url || + primaryType.Type == KnownPrimaryType.UnixTime) { return "SafeJsonConvert.DeserializeObject<" + primaryType.Name.TrimEnd('?') + diff --git a/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs index ded2055e683be..ae4d9f11159de 100644 --- a/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs @@ -225,6 +225,10 @@ public static string ToString(this IType type, string clientReference, string re { serializationSettings = "new Base64UrlJsonConverter()"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + serializationSettings = "new UnixTimeJsonConverter()"; + } } return string.Format(CultureInfo.InvariantCulture, @@ -268,6 +272,7 @@ public static bool IsValueType(this IType type) || primaryType.Type == KnownPrimaryType.Long || primaryType.Type == KnownPrimaryType.TimeSpan || primaryType.Type == KnownPrimaryType.DateTimeRfc1123 + || primaryType.Type == KnownPrimaryType.UnixTime || primaryType.Type == KnownPrimaryType.Uuid)); } diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs index cc44708181ecf..d4a380df2765c 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs @@ -351,6 +351,14 @@ public string GetSerializationSettingsReference(IType serializationType) { return "new Base64UrlJsonConverter()"; } + else if (serializationType.IsPrimaryType(KnownPrimaryType.UnixTime) || + (sequenceType != null && sequenceType.ElementType is PrimaryType + && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.UnixTime) || + (dictionaryType != null && dictionaryType.ValueType is PrimaryType + && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.UnixTime)) + { + return "new UnixTimeJsonConverter()"; + } return ClientReference + ".SerializationSettings"; } @@ -371,7 +379,7 @@ public string GetDeserializationSettingsReference(IType deserializationType) { return "new DateJsonConverter()"; } - if (deserializationType.IsPrimaryType(KnownPrimaryType.Base64Url) || + else if (deserializationType.IsPrimaryType(KnownPrimaryType.Base64Url) || (sequenceType != null && sequenceType.ElementType is PrimaryType && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Base64Url) || (dictionaryType != null && dictionaryType.ValueType is PrimaryType @@ -379,6 +387,14 @@ public string GetDeserializationSettingsReference(IType deserializationType) { return "new Base64UrlJsonConverter()"; } + else if (deserializationType.IsPrimaryType(KnownPrimaryType.UnixTime) || + (sequenceType != null && sequenceType.ElementType is PrimaryType + && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.UnixTime) || + (dictionaryType != null && dictionaryType.ValueType is PrimaryType + && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.UnixTime)) + { + return "new UnixTimeJsonConverter()"; + } return ClientReference + ".DeserializationSettings"; } diff --git a/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml b/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml index 2bcf9676f0951..942e67ef809e3 100644 --- a/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml @@ -123,6 +123,10 @@ namespace @(Settings.Namespace).Models { @:[JsonConverter(typeof(Base64UrlJsonConverter))] } + if (property.Type.IsPrimaryType(KnownPrimaryType.UnixTime)) + { + @:[JsonConverter(typeof(UnixTimeJsonConverter))] + } @:[JsonProperty(PropertyName = "@property.SerializedName")] @:public @property.Type.Name @property.Name { get; @(property.IsReadOnly ? "private " : "")set; } @EmptyLine @@ -145,6 +149,10 @@ namespace @(Settings.Namespace).Models { @:[JsonConverter(typeof(Base64UrlJsonConverter))] } + if (property.Type.IsPrimaryType(KnownPrimaryType.UnixTime)) + { + @:[JsonConverter(typeof(UnixTimeJsonConverter))] + } @:[JsonProperty(PropertyName = "@property.SerializedName")] @:public static @property.Type.Name @property.Name { get; private set; } @EmptyLine diff --git a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs index 2d5a2fad78626..d6990c79ff680 100644 --- a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs +++ b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs @@ -202,6 +202,10 @@ private void Initialize(PrimaryType primaryType) Name = "Period"; _imports.Add("org.joda.time.Period"); } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + Name = "long"; + } else if (primaryType.Type == KnownPrimaryType.Uuid) { Name = "UUID"; diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs index 53ac858681ef1..d2f43a402f589 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs @@ -393,6 +393,10 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "moment.duration"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "Number"; + } else if (primaryType.Type == KnownPrimaryType.Uuid) { primaryType.Name = "Uuid"; diff --git a/AutoRest/Generators/Python/Python/PythonCodeNamer.cs b/AutoRest/Generators/Python/Python/PythonCodeNamer.cs index 4aebfb6378a11..11ae0801acce4 100644 --- a/AutoRest/Generators/Python/Python/PythonCodeNamer.cs +++ b/AutoRest/Generators/Python/Python/PythonCodeNamer.cs @@ -376,6 +376,10 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "Decimal"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "long"; + } else if (primaryType.Type == KnownPrimaryType.Object) // Revisit here { primaryType.Name = "object"; diff --git a/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs b/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs index bcb90309c677e..c40423ee1b4ae 100644 --- a/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs +++ b/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs @@ -372,6 +372,10 @@ private IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "Duration"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "Bignum"; + } else if (primaryType.Type == KnownPrimaryType.Object) { primaryType.Name = "Object"; diff --git a/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs b/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs index 2ca86ef10d3e1..02bfb0d23b8bc 100644 --- a/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs +++ b/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs @@ -132,6 +132,10 @@ public PrimaryType ToType() { return new PrimaryType(KnownPrimaryType.Long); } + if (string.Equals("unixtime", Format, StringComparison.OrdinalIgnoreCase)) + { + return new PrimaryType(KnownPrimaryType.UnixTime); + } return new PrimaryType(KnownPrimaryType.Int); case DataType.Boolean: return new PrimaryType(KnownPrimaryType.Boolean); diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs new file mode 100644 index 0000000000000..8f6283b6237ce --- /dev/null +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Microsoft.Rest.Serialization +{ + public class UnixTimeJsonConverter : JsonConverter + { + public static readonly DateTime EpochDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + /// + /// Converts a byte array to a Base64Url encoded string + /// + /// The byte array to convert + /// The Base64Url encoded form of the input + private static long? ToUnixTime(DateTime dateTime) + { + return (long?)dateTime.Subtract(EpochDate).TotalSeconds; + } + + /// + /// Converts a Base64Url encoded string to a byte array + /// + /// The Base64Url encoded string + /// The byte array represented by the enconded string + private static DateTime FromUnixTime(long? seconds) + { + if (seconds.HasValue) + { + return EpochDate.AddSeconds(seconds.Value); + } + return EpochDate; + } + + public override bool CanConvert(Type objectType) + { + if (objectType == typeof(DateTime)) + return true; + + return false; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (objectType != typeof(DateTime)) + { + return serializer.Deserialize(reader, objectType); + } + else + { + var value = serializer.Deserialize(reader); + if (value.HasValue) + { + return FromUnixTime(value); + } + } + + return null; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value.GetType() != typeof(DateTime)) + { + JToken.FromObject(value).WriteTo(writer); + } + else + { + JToken.FromObject(ToUnixTime((DateTime)value)).WriteTo(writer); + } + } + } +} \ No newline at end of file From 166ff89b3daa50b4db041a182edec0595fd52b7b Mon Sep 17 00:00:00 2001 From: tbombach Date: Thu, 14 Apr 2016 00:03:36 -0700 Subject: [PATCH 82/99] Updating test server to add test scenarios for unix time --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 4 + .../AcceptanceTests/BodyInteger/IIntModel.cs | 42 ++ .../AcceptanceTests/BodyInteger/IntModel.cs | 467 ++++++++++++++++++ .../BodyInteger/IntModelExtensions.cs | 113 +++++ .../CompositeBoolIntClient/IIntModel.cs | 42 ++ .../CompositeBoolIntClient/IntModel.cs | 467 ++++++++++++++++++ .../IntModelExtensions.cs | 113 +++++ AutoRest/TestServer/server/routes/int.js | 19 +- AutoRest/TestServer/swagger/body-integer.json | 89 ++++ .../Serialization/UnixTimeJsonConverter.cs | 9 +- 10 files changed, 1360 insertions(+), 5 deletions(-) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 0d5c31f0e5182..9caea8d8df283 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -198,12 +198,16 @@ public void IntegerTests() client.IntModel.PutMin32(Int32.MinValue); client.IntModel.PutMax64(Int64.MaxValue); client.IntModel.PutMin64(Int64.MinValue); + client.IntModel.PutUnixTimeDate(new DateTime(2016, 4, 13, 0, 0, 0)); client.IntModel.GetNull(); Assert.Throws(() => client.IntModel.GetInvalid()); Assert.Throws(() => client.IntModel.GetOverflowInt32()); Assert.Throws(() => client.IntModel.GetOverflowInt64()); Assert.Throws(() => client.IntModel.GetUnderflowInt32()); Assert.Throws(() => client.IntModel.GetUnderflowInt64()); + Assert.Throws(() => client.IntModel.GetInvalidUnixTime()); + Assert.Null(client.IntModel.GetNullUnixTime()); + Assert.Equal(new DateTime(2016, 4, 13, 0, 0, 0), client.IntModel.GetUnixTime()); } [Fact] diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs index 4b90323fef26b..7131504bb1855 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs @@ -129,5 +129,47 @@ public partial interface IIntModel /// The cancellation token. /// Task PutMin64WithHttpMessagesAsync(long intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get invalid Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get null Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs index feb0d3013f373..9c9b57ebbb2a4 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs @@ -1202,5 +1202,472 @@ public IntModel(AutoRestIntegerTestService client) return _result; } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("intBody", intBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutUnixTimeDate", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, new UnixTimeJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get invalid Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInvalidUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalidunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get null Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNullUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/nullunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs index 0c57e20b0aade..c0bc0812ebde8 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs @@ -305,5 +305,118 @@ public static void PutMin64(this IIntModel operations, long intBody) await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + public static void PutUnixTimeDate(this IIntModel operations, DateTime intBody) + { + Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutUnixTimeDateAsync(this IIntModel operations, DateTime intBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetInvalidUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetInvalidUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetNullUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs index 4917e355224d7..d0b518478669c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs @@ -129,5 +129,47 @@ public partial interface IIntModel /// The cancellation token. /// Task PutMin64WithHttpMessagesAsync(long intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get invalid Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get null Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs index 1ed42f86ca54e..2047fd860871e 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs @@ -1202,5 +1202,472 @@ public IntModel(CompositeBoolInt client) return _result; } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("intBody", intBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutUnixTimeDate", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, new UnixTimeJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get invalid Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInvalidUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalidunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get null Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNullUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/nullunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs index a203d3cee39e7..009277ea5077b 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs @@ -305,5 +305,118 @@ public static void PutMin64(this IIntModel operations, long intBody) await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + public static void PutUnixTimeDate(this IIntModel operations, DateTime intBody) + { + Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutUnixTimeDateAsync(this IIntModel operations, DateTime intBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetInvalidUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetInvalidUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetNullUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + } } diff --git a/AutoRest/TestServer/server/routes/int.js b/AutoRest/TestServer/server/routes/int.js index 2299732ca5ad1..f4acbd7104cd2 100644 --- a/AutoRest/TestServer/server/routes/int.js +++ b/AutoRest/TestServer/server/routes/int.js @@ -65,10 +65,27 @@ var integer = function(coverage) { } else if (req.params.scenario === 'underflowint64') { coverage['getLongUnderflow']++; res.status(200).end('-9223372036854775910'); + } else if (req.params.scenario === 'unixtime') { + coverage['getUnixTime']++; + res.status(200).end('1460505600'); + } else if (req.params.scenario === 'invalidunixtime') { + coverage['getInvalidUnixTime']++; + res.status(200).end('123jkl'); + } else if (req.params.scenario === 'nullunixtime') { + coverage['getNullUnixTime']++; + res.status(200).end(); } else { res.status(400).send('Request path must contain true or false'); } - + }); + + router.put('/unixtime', function(req, res, next) { + if (req.body != 1460505600) { + utils.send400(res, next, "Did not like the value provided for unixtime in the req " + util.inspect(req.body)); + } else { + coverage['putUnixTime']++; + res.status(200).end(); + } }); } diff --git a/AutoRest/TestServer/swagger/body-integer.json b/AutoRest/TestServer/swagger/body-integer.json index 00b73a2c2731c..5f321e2981692 100644 --- a/AutoRest/TestServer/swagger/body-integer.json +++ b/AutoRest/TestServer/swagger/body-integer.json @@ -251,6 +251,95 @@ } } } + }, + "/int/unixtime": { + "get": { + "operationId": "int_getUnixTime", + "description": "Get datetime encoded as Unix time value", + "responses": { + "200": { + "description": "The date value encoded as Unix time", + "schema": { + "type": "integer", + "format": "unixtime" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "put": { + "operationId": "int_putUnixTimeDate", + "description": "Put datetime encoded as Unix time", + "parameters": [ + { + "name": "intBody", + "in": "body", + "schema": { + "type": "integer", + "format": "unixtime" + }, + "required": true + } + ], + "responses": { + "200": { + "description": "The datetime value encoded as Unix time" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/int/invalidunixtime": { + "get": { + "operationId": "int_getInvalidUnixTime", + "description": "Get invalid Unix time value", + "responses": { + "200": { + "description": "The invalid Unix time value", + "schema": { + "type": "integer", + "format": "unixtime" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/int/nullunixtime": { + "get": { + "operationId": "int_getNullUnixTime", + "description": "Get null Unix time value", + "responses": { + "200": { + "description": "The null Unix time value", + "schema": { + "type": "integer", + "format": "unixtime" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } } }, "definitions": { diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs index 8f6283b6237ce..fd345541a6de0 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs @@ -26,18 +26,18 @@ public class UnixTimeJsonConverter : JsonConverter /// /// The Base64Url encoded string /// The byte array represented by the enconded string - private static DateTime FromUnixTime(long? seconds) + private static DateTime? FromUnixTime(long? seconds) { if (seconds.HasValue) { return EpochDate.AddSeconds(seconds.Value); } - return EpochDate; + return null; } public override bool CanConvert(Type objectType) { - if (objectType == typeof(DateTime)) + if (objectType == typeof(DateTime?) || objectType == typeof(DateTime)) return true; return false; @@ -45,13 +45,14 @@ public override bool CanConvert(Type objectType) public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - if (objectType != typeof(DateTime)) + if (objectType != typeof(DateTime?)) { return serializer.Deserialize(reader, objectType); } else { var value = serializer.Deserialize(reader); + if (value.HasValue) { return FromUnixTime(value); From 59d3fa94d2c1c186cf5a17d966376b61efec6bba Mon Sep 17 00:00:00 2001 From: tbombach Date: Thu, 14 Apr 2016 00:43:49 -0700 Subject: [PATCH 83/99] Adding test for Unix time encoded values in path --- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 1 + .../Expected/AcceptanceTests/Url/IPaths.cs | 13 +++ .../Expected/AcceptanceTests/Url/Paths.cs | 106 ++++++++++++++++++ .../AcceptanceTests/Url/PathsExtensions.cs | 31 +++++ AutoRest/TestServer/server/routes/paths.js | 1 + AutoRest/TestServer/swagger/url.json | 30 +++++ 6 files changed, 182 insertions(+) diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 9caea8d8df283..804db915e6111 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -1355,6 +1355,7 @@ public void UrlPathTests() client.Paths.Base64Url(Encoding.UTF8.GetBytes("lorem")); var testArray = new List { "ArrayPath1", @"begin!*'();:@ &=+$,/?#[]end", null, "" }; client.Paths.ArrayCsvInPath(testArray); + client.Paths.UnixTimeUrl(new DateTime(2016, 4, 13, 0, 0, 0)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs index ce60b9a5c2f28..d8f9e2c761579 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs @@ -305,5 +305,18 @@ public partial interface IPaths /// The cancellation token. /// Task ArrayCsvInPathWithHttpMessagesAsync(IList arrayPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// Unix time encoded value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UnixTimeUrlWithHttpMessagesAsync(DateTime unixTimeUrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs index d880804521f0c..3892f728ba11b 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs @@ -2692,5 +2692,111 @@ public Paths(AutoRestUrlTestService client) return _result; } + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// Unix time encoded value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UnixTimeUrlWithHttpMessagesAsync(DateTime unixTimeUrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("unixTimeUrlPath", unixTimeUrlPath); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UnixTimeUrl", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "paths/int/1460505600/{unixTimeUrlPath}").ToString(); + _url = _url.Replace("{unixTimeUrlPath}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(unixTimeUrlPath, new UnixTimeJsonConverter()).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs index 65ea07ea61b8b..b4e8d2ce268e6 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs @@ -712,5 +712,36 @@ public static void ArrayCsvInPath(this IPaths operations, IList arrayPat await operations.ArrayCsvInPathWithHttpMessagesAsync(arrayPath, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// The operations group for this extension method. + /// + /// + /// Unix time encoded value + /// + public static void UnixTimeUrl(this IPaths operations, DateTime unixTimeUrlPath) + { + Task.Factory.StartNew(s => ((IPaths)s).UnixTimeUrlAsync(unixTimeUrlPath), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// The operations group for this extension method. + /// + /// + /// Unix time encoded value + /// + /// + /// The cancellation token. + /// + public static async Task UnixTimeUrlAsync(this IPaths operations, DateTime unixTimeUrlPath, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UnixTimeUrlWithHttpMessagesAsync(unixTimeUrlPath, null, cancellationToken).ConfigureAwait(false); + } + } } diff --git a/AutoRest/TestServer/server/routes/paths.js b/AutoRest/TestServer/server/routes/paths.js index ba1b8e99df9e6..04b5002453c3c 100644 --- a/AutoRest/TestServer/server/routes/paths.js +++ b/AutoRest/TestServer/server/routes/paths.js @@ -23,6 +23,7 @@ var scenarioMap = { "2012-01-01T01:01:01Z": "Valid", "green color" : "Valid", "bG9yZW0" : "Base64Url", + "1460505600": "UnixTime", "ArrayPath1,begin!*'();:@ &=+$,/?#[]end,,": "CSVInPath" }; diff --git a/AutoRest/TestServer/swagger/url.json b/AutoRest/TestServer/swagger/url.json index 4bf4530d177fb..670ff00f9bd1d 100644 --- a/AutoRest/TestServer/swagger/url.json +++ b/AutoRest/TestServer/swagger/url.json @@ -773,6 +773,36 @@ } } }, + "/paths/int/1460505600/{unixTimeUrlPath}": { + "get": { + "operationId": "paths_unixTimeUrl", + "description": "Get the date 2016-04-13 encoded value as '1460505600' (Unix time)", + "tags": [ + "Path Operations" + ], + "parameters": [ + { + "name": "unixTimeUrlPath", + "in": "path", + "description": "Unix time encoded value", + "type": "integer", + "format": "unixtime", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully Received date 2016-04-13 encoded value as '1460505600' (Unix time)" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/queries/bool/true": { "get": { "operationId": "queries_getBooleanTrue", From 557787508985b3e75e99defbfedf991989963ab1 Mon Sep 17 00:00:00 2001 From: tbombach Date: Thu, 14 Apr 2016 00:51:57 -0700 Subject: [PATCH 84/99] Updating test coverage list --- AutoRest/TestServer/server/app.js | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index 8bb3b105ba765..9453e73965c22 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -195,15 +195,6 @@ var coverage = { "getStringWithLeadingAndTrailingWhitespace" : 0, "putStringWithLeadingAndTrailingWhitespace" : 0, "getStringNotProvided": 0, - /* TODO: only C# and node.js support the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */ - "getStringBase64Encoded": 1, - "getStringBase64UrlEncoded": 1, - "putStringBase64UrlEncoded": 1, - "getStringNullBase64UrlEncoding": 1, - "getArrayBase64Url": 1, - "getDictionaryBase64Url": 1, - "UrlPathsStringBase64Url": 1, - "UrlPathsArrayCSVInPath": 1, "getEnumNotExpandable": 0, "putEnumNotExpandable":0, "putComplexBasicValid": 0, @@ -438,7 +429,22 @@ var coverage = { 'putModelFlattenResourceCollection': 0, 'putModelFlattenCustomBase': 0, 'postModelFlattenCustomParameter': 0, - 'putModelFlattenCustomGroupedParameter': 0 + 'putModelFlattenCustomGroupedParameter': 0, + /* TODO: only C# and node.js support the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */ + "getStringBase64Encoded": 1, + "getStringBase64UrlEncoded": 1, + "putStringBase64UrlEncoded": 1, + "getStringNullBase64UrlEncoding": 1, + "getArrayBase64Url": 1, + "getDictionaryBase64Url": 1, + "UrlPathsStringBase64Url": 1, + "UrlPathsArrayCSVInPath": 1, + /* TODO: only C# supports the unixtime format currently. Exclude these tests from code coverage until it is implemented in other languages */ + "getUnixTime": 1, + "getInvalidUnixTime": 1, + "getNullUnixTime": 1, + "putUnixTime": 1, + "UrlPathsIntUnixTime": 1 }; // view engine setup From b6bf4ccfc3413a2ea50ad23c54b71e9c495e3b04 Mon Sep 17 00:00:00 2001 From: aescribano Date: Thu, 14 Apr 2016 11:57:30 +0100 Subject: [PATCH 85/99] Adding a User-Agent header to the request done in FileSystem.ReadFileAsText --- AutoRest/AutoRest.Core/Utilities/FileSystem.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/AutoRest/AutoRest.Core/Utilities/FileSystem.cs b/AutoRest/AutoRest.Core/Utilities/FileSystem.cs index 91b4f6c18bdd0..231b6521090d3 100644 --- a/AutoRest/AutoRest.Core/Utilities/FileSystem.cs +++ b/AutoRest/AutoRest.Core/Utilities/FileSystem.cs @@ -17,6 +17,7 @@ public string ReadFileAsText(string path) { using (var client = new WebClient()) { + client.Headers.Add("User-Agent: AutoRest"); return client.DownloadString(path); } } From 8b015ac266ddb655991927ac6a14c454d9e31b1d Mon Sep 17 00:00:00 2001 From: John-Hart Date: Thu, 14 Apr 2016 13:05:37 -0700 Subject: [PATCH 86/99] Captured the JSONException that may occur on a Non-Success StatusCode when attempting to Deserialize the HTTPResponse.Content when it is not JSON --- .../AzureClientExtensions.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs index 57bbd064b95c2..0d8505210fd5e 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs @@ -599,7 +599,16 @@ private static async Task> GetRawAsync( statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent) { - CloudError errorBody = SafeJsonConvert.DeserializeObject(responseContent, client.DeserializationSettings); + CloudError errorBody = null; + try + { + errorBody = SafeJsonConvert.DeserializeObject(responseContent, client.DeserializationSettings); + } + catch (JsonException) + { + // failed to deserialize, return empty body + } + throw new CloudException(string.Format(CultureInfo.InvariantCulture, Resources.LongRunningOperationFailed, statusCode)) { From 3622e2bc43b1b387b4c89a9b9b0a7d8a89622e8f Mon Sep 17 00:00:00 2001 From: John-Hart Date: Thu, 14 Apr 2016 13:12:05 -0700 Subject: [PATCH 87/99] Added a new LongRunningOperations test to verify that a CloudException is thrown even when a JSONException occurs Deserializing the HTTPResponse.Content --- .../LongRunningOperationsTest.cs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs index bf999fe9f7c1b..1d0bb2069f1bf 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs @@ -104,6 +104,19 @@ public void TestAsyncOperationWithMissingProvisioningState() Assert.Equal("100", resource.Id); } + [Fact] + public void TestAsyncOperationWithNonSuccessStatusAndInvalidResponseContent() + { + var tokenCredentials = new TokenCredentials("123", "abc"); + var handler = new PlaybackTestHandler(MockAsyncOperaionWithNonSuccessStatusAndInvalidResponseContent()); + var fakeClient = new RedisManagementClient(tokenCredentials, handler); + fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; + var error = Assert.Throws(() => + fakeClient.RedisOperations.Delete("rg", "redis", "1234")); + Assert.Equal("Long running operation failed with status 'BadRequest'.", error.Message); + Assert.Null(error.Body); + } + [Fact] public void TestPutOperationWithoutProvisioningState() { @@ -737,6 +750,22 @@ private IEnumerable MockAsyncOperaionWithMissingProvisionin yield return response3; } + private IEnumerable MockAsyncOperaionWithNonSuccessStatusAndInvalidResponseContent() + { + var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) + { + Content = new StringContent("") + }; + response1.Headers.Add("Location", "http://custom/status"); + yield return response1; + + var response2 = new HttpResponseMessage(HttpStatusCode.BadRequest) + { + Content = new StringContent("<") + }; + yield return response2; + } + private IEnumerable MockPutOperaionWithoutProvisioningStateInResponse() { var response1 = new HttpResponseMessage(HttpStatusCode.Created) From cd746ab36777f6b827d95517c43c01fb1620bbd7 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Fri, 15 Apr 2016 09:45:37 -0700 Subject: [PATCH 88/99] Okio 1.7.0 --- ClientRuntimes/Java/client-runtime/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ClientRuntimes/Java/client-runtime/build.gradle b/ClientRuntimes/Java/client-runtime/build.gradle index 47cbaf08c6397..b734d33608eaf 100644 --- a/ClientRuntimes/Java/client-runtime/build.gradle +++ b/ClientRuntimes/Java/client-runtime/build.gradle @@ -25,7 +25,7 @@ dependencies { compile 'com.google.guava:guava:18.0' compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.okhttp3:okhttp:3.2.0' - compile ('com.squareup.okio:okio:1.7.0-SNAPSHOT') { changing = true } + compile 'com.squareup.okio:okio:1.7.0' compile 'com.squareup.okhttp3:logging-interceptor:3.1.1' compile 'com.squareup.okhttp3:okhttp-urlconnection:3.1.1' compile 'com.squareup.retrofit2:converter-jackson:2.0.0-beta4' From 29dc46d8d25b5509c5883688a5475cdb1da379e2 Mon Sep 17 00:00:00 2001 From: annatisch Date: Fri, 15 Apr 2016 13:22:00 -0700 Subject: [PATCH 89/99] Python Bug Fixes (#928) * Fix serializing lists into paths * Fix for streaming bug * Generated Python config type checking * Regenerated tests * fixed streaming bug * regenerated samples * Fixed runtime tests * Test server debuging * removed stream connection closing * ping build server --- .../auto_rest_duration_test_service.py | 4 +- ...to_rest_parameter_grouping_test_service.py | 4 +- .../auto_rest_report_service_for_azure.py | 4 +- ...o_rest_resource_flattening_test_service.py | 4 +- ...st_azure_special_parameters_test_client.py | 10 ++- ...uto_rest_parameterized_host_test_client.py | 8 ++- .../auto_rest_head_test_service.py | 4 +- .../auto_rest_head_exception_test_service.py | 4 +- ...est_long_running_operation_test_service.py | 4 +- .../auto_rest_paging_test_service.py | 4 +- .../storage_management_client.py | 10 ++- .../microsoft_azure_test_url.py | 10 ++- .../AcceptanceTests/file_tests.py | 61 ++++++------------- .../AcceptanceTests/form_data_tests.py | 1 - .../Python.Tests/AcceptanceTests/url_tests.py | 5 +- .../Python.Tests/AcceptanceTests/zzz_tests.py | 43 +++++++------ .../auto_rest_complex_test_service.py | 4 +- ...uto_rest_parameterized_host_test_client.py | 4 +- ...uto_rest_required_optional_test_service.py | 8 ++- .../auto_rest_url_test_service.py | 6 +- .../operations/paths.py | 2 +- .../auto_rest_validation_test.py | 8 ++- .../TemplateModels/MethodTemplateModel.cs | 7 +++ .../ServiceClientTemplateModel.cs | 29 ++++++++- .../Python/msrest/msrest/http_logger.py | 4 +- .../Python/msrest/msrest/serialization.py | 3 +- .../Python/msrest/msrest/service_client.py | 7 ++- .../Python/msrest/test/unittest_runtime.py | 8 ++- .../storage_management_client.py | 10 ++- 29 files changed, 181 insertions(+), 99 deletions(-) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py index bceee986fdda8..668b135381e1f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py index b8bae0b1b5228..13e63f9569c81 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py index b37530e7d7985..c02088e43b1a4 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py @@ -44,7 +44,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py index 3a806d13f53fc..74f09db9d3400 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py @@ -44,7 +44,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py index cc2d96c0ce719..95f2d47d0fb58 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py @@ -56,9 +56,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-07-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py index ce9c7112afaf5..79e862f82db73 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py @@ -45,9 +45,13 @@ def __init__( self, credentials, host, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if host is None: - raise ValueError('host must not be None.') + raise ValueError("Parameter 'host' must not be None.") + if not isinstance(host, str): + raise TypeError("Parameter 'host' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") base_url = 'http://{accountName}{host}' super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(base_url, filepath) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py index 85044ec1cbcc4..fc86a3308cb2e 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py @@ -42,7 +42,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py index e7531777378d2..d9745572729ef 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py @@ -42,7 +42,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py index 718b1114d10af..be1ddc0cc63c0 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py @@ -46,7 +46,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py index 532adc38d5acc..e3cf9310642ed 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py index cd2c457915195..1334ec94142ec 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py @@ -50,9 +50,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-05-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py index 99e3bc1f4ce98..d16f3f25706a6 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py @@ -47,9 +47,15 @@ def __init__( self, credentials, subscription_id, api_version='2014-04-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com/' diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py index cc7fb8d0f5eb7..22511e8de15c7 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py @@ -53,24 +53,21 @@ class FileTests(unittest.TestCase): def test_files(self): config = AutoRestSwaggerBATFileServiceConfiguration(base_url="http://localhost:3000") - config.log_level = log_level config.connection.data_block_size = 1000 client = AutoRestSwaggerBATFileService(config) - def test_callback(data, response, progress = [0], is_response_streamed=None): + def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) - if not is_response_streamed: - self.assertFalse(response._content_consumed) + self.assertIsNotNone(response) + self.assertFalse(response._content_consumed) + total = float(response.headers.get('Content-Length', 0)) + if total: progress[0] += len(data) - total = float(response.headers['Content-Length']) print("Downloading... {}%".format(int(progress[0]*100/total))) - self.assertIsNotNone(response) file_length = 0 with io.BytesIO() as file_handle: - - stream = client.files.get_file(callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + stream = client.files.get_file(callback=test_callback) for data in stream: file_length += len(data) @@ -86,11 +83,10 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): sample_data = hash(data.read()) self.assertEqual(sample_data, hash(file_handle.getvalue())) + config.connection.data_block_size = 4096 file_length = 0 with io.BytesIO() as file_handle: - - stream = client.files.get_empty_file(callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + stream = client.files.get_empty_file(callback=test_callback) for data in stream: file_length += len(data) @@ -98,34 +94,30 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): self.assertEqual(file_length, 0) - #file_length = 0 - #stream = client.files.get_file_large(callback=lambda x, response, progress=[0] : - # test_callback(x, response, progress, True)) - #for data in stream: - # file_length += len(data) + file_length = 0 + stream = client.files.get_file_large(callback=test_callback) + for data in stream: + file_length += len(data) - #self.assertEqual(file_length, 3000 * 1024 * 1024) + self.assertEqual(file_length, 3000 * 1024 * 1024) def test_files_raw(self): - def test_callback(data, response, progress = [0], is_response_streamed=None): + def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) - if not is_response_streamed: - self.assertFalse(response._content_consumed) + self.assertIsNotNone(response) + self.assertFalse(response._content_consumed) + total = float(response.headers.get('Content-Length', 0)) + if total: progress[0] += len(data) - total = float(response.headers['Content-Length']) print("Downloading... {}%".format(int(progress[0]*100/total))) - self.assertIsNotNone(response) config = AutoRestSwaggerBATFileServiceConfiguration(base_url="http://localhost:3000") - config.log_level = log_level client = AutoRestSwaggerBATFileService(config) file_length = 0 with io.BytesIO() as file_handle: - - response = client.files.get_file(raw=True, callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + response = client.files.get_file(raw=True, callback=test_callback) stream = response.output for data in stream: @@ -144,9 +136,7 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): file_length = 0 with io.BytesIO() as file_handle: - - response = client.files.get_empty_file(raw=True, callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + response = client.files.get_empty_file(raw=True, callback=test_callback) stream = response.output for data in stream: @@ -155,16 +145,5 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): self.assertEqual(file_length, 0) - #file_length = 0 - #response = client.files.get_file_large(raw=True, callback=lambda x, response, progress=[0] : - # test_callback(x, response, progress, True)) - - #stream = response.output - - #for data in stream: - # file_length += len(data) - - #self.assertEqual(file_length, 3000 * 1024 * 1024) - if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py index f18bfdb92aa05..ea1ed1a726f9e 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py @@ -174,7 +174,6 @@ def test_callback(data, response, progress = [0]): with open(self.dummy_file, 'rb') as upload_data: resp = client.formdata.upload_file_via_body(upload_data, callback=test_callback) for r in resp: - print(r) result.write(r) self.assertEqual(result.getvalue().decode(), "Test file") diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py index 05f7b4dcdba4f..3204669e8568c 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py @@ -90,8 +90,9 @@ def test_url_path(self): self.client.paths.get_negative_ten_billion(-10000000000) self.client.paths.get_ten_billion(10000000000) self.client.paths.string_empty("") - #test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] - #self.client.paths.array_csv_in_path(test_array) + + test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + self.client.paths.array_csv_in_path(test_array) with self.assertRaises(ValidationError): self.client.paths.string_null(None) diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py index b54157497620c..ccafa013129b1 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py @@ -54,33 +54,38 @@ def test_ensure_coverage(self): client = AutoRestReportService(config) report = client.get_report() - # These will not be supported in Python - report['getIntegerOverflow']=1 - report['getIntegerUnderflow']=1 - report['getLongOverflow']=1 - report['getLongUnderflow']=1 - report['getDateInvalid']=1 - report['getDictionaryNullkey']=1 - report['HttpRedirect300Get']=1 - - # TODO: Support large file streams - report['FileStreamVeryLarge']=1 + not_supported = { + 'getIntegerOverflow': 1, + 'getIntegerUnderflow': 1, + 'getLongOverflow': 1, + 'getLongUnderflow': 1, + 'getDateInvalid': 1, + 'getDictionaryNullkey': 1, + 'HttpRedirect300Get': 1, + } # TODO: Support ignore readonly property in http put - report['putComplexReadOnlyPropertyValid']=1 + missing_features_or_bugs = { + 'putComplexReadOnlyPropertyValid': 1, + } - skipped = [k for k, v in report.items() if v == 0] - manually_marked_successful = [k for k, v in report.items() if v == 2] - for s in manually_marked_successful: - print("SKIPPED {0}".format(s)) + report.update(not_supported) + report.update(missing_features_or_bugs) + failed = [k for k, v in report.items() if v == 0] - for s in skipped: + for s in not_supported.keys(): + print("IGNORING {0}".format(s)) + + for s in missing_features_or_bugs.keys(): + print("PENDING {0}".format(s)) + + for s in failed: print("FAILED TO EXECUTE {0}".format(s)) totalTests = len(report) - print ("The test coverage is {0}/{1}.".format(totalTests - len(skipped), totalTests)) + print ("The test coverage is {0}/{1}.".format(totalTests - len(failed), totalTests)) - self.assertEqual(0, len(skipped)) + self.assertEqual(0, len(failed)) if __name__ == '__main__': unittest.main() diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py index 8ff86db017bbd..3887687ac962c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py @@ -38,7 +38,9 @@ def __init__( self, api_version, base_url=None, filepath=None): if api_version is None: - raise ValueError('api_version must not be None.') + raise ValueError("Parameter 'api_version' must not be None.") + if not isinstance(api_version, str): + raise TypeError("Parameter 'api_version' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py index 570afdaa95129..5839338b5a2d2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py @@ -31,7 +31,9 @@ def __init__( self, host, filepath=None): if host is None: - raise ValueError('host must not be None.') + raise ValueError("Parameter 'host' must not be None.") + if not isinstance(host, str): + raise TypeError("Parameter 'host' must be str.") base_url = 'http://{accountName}{host}' super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(base_url, filepath) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py index d9a36a8ffd5b0..7dcce131d92ad 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py @@ -36,9 +36,13 @@ def __init__( self, required_global_path, required_global_query, optional_global_query=None, base_url=None, filepath=None): if required_global_path is None: - raise ValueError('required_global_path must not be None.') + raise ValueError("Parameter 'required_global_path' must not be None.") + if not isinstance(required_global_path, str): + raise TypeError("Parameter 'required_global_path' must be str.") if required_global_query is None: - raise ValueError('required_global_query must not be None.') + raise ValueError("Parameter 'required_global_query' must not be None.") + if not isinstance(required_global_query, str): + raise TypeError("Parameter 'required_global_query' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py index 31c1880929875..34efde192fd6b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py @@ -36,7 +36,11 @@ def __init__( self, global_string_path, global_string_query=None, base_url=None, filepath=None): if global_string_path is None: - raise ValueError('global_string_path must not be None.') + raise ValueError("Parameter 'global_string_path' must not be None.") + if not isinstance(global_string_path, str): + raise TypeError("Parameter 'global_string_path' must be str.") + if global_string_query is not None and not isinstance(global_string_query, str): + raise TypeError("Optional parameter 'global_string_query' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py index 46bface0d9375..97cd8878c0e6a 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py @@ -1089,7 +1089,7 @@ def array_csv_in_path( if raw=true """ # Construct URL - url = '/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}' + url = '/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}' path_format_arguments = { 'arrayPath': self._serialize.url("array_path", array_path, '[str]', div=',') } diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py index 7fd4093d00b6e..f9a6b88ede469 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py @@ -34,9 +34,13 @@ def __init__( self, subscription_id, api_version, base_url=None, filepath=None): if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") if api_version is None: - raise ValueError('api_version must not be None.') + raise ValueError("Parameter 'api_version' must not be None.") + if not isinstance(api_version, str): + raise TypeError("Parameter 'api_version' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs index 5c47e7be1f83c..0555d5cd4434e 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.Linq; using System.Net; +using System.Text.RegularExpressions; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; @@ -31,6 +32,12 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) OperationName = serviceClient.Name; } AddCustomHeader = true; + string formatter; + foreach (Match m in Regex.Matches(Url, @"\{[\w]+:[\w]+\}")) + { + formatter = m.Value.Split(':').First() + '}'; + Url = Url.Replace(m.Value, formatter); + } } public bool AddCustomHeader { get; private set; } diff --git a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs index 4eb487cdfdee5..60629ea26ca28 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs @@ -105,7 +105,10 @@ public virtual string RequiredConstructorParameters } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ValueError"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ValueError"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TypeError"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "str"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)")] public virtual string ValidateRequiredParameters { get @@ -118,9 +121,31 @@ public virtual string ValidateRequiredParameters builder. AppendFormat("if {0} is None:", property.Name.ToPythonCase()).AppendLine(). Indent(). - AppendLine(string.Format(CultureInfo.InvariantCulture, "raise ValueError('{0} must not be None.')", property.Name.ToPythonCase())). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise ValueError(\"Parameter '{0}' must not be None.\")", property.Name.ToPythonCase())). Outdent(); + if (property.Type.IsPrimaryType(KnownPrimaryType.String)) + { + builder. + AppendFormat("if not isinstance({0}, str):", property.Name.ToPythonCase()).AppendLine(). + Indent(). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise TypeError(\"Parameter '{0}' must be str.\")", property.Name.ToPythonCase())). + Outdent(); + } } + else + { + if (property.Type.IsPrimaryType(KnownPrimaryType.String)) + { + builder. + AppendFormat("if {0} is not None and not isinstance({0}, str):", property.Name.ToPythonCase()).AppendLine(). + Indent(). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise TypeError(\"Optional parameter '{0}' must be str.\")", property.Name.ToPythonCase())). + Outdent(); + } + + } + + } return builder.ToString(); } diff --git a/ClientRuntimes/Python/msrest/msrest/http_logger.py b/ClientRuntimes/Python/msrest/msrest/http_logger.py index b19405528cf96..5159a996a6e8f 100644 --- a/ClientRuntimes/Python/msrest/msrest/http_logger.py +++ b/ClientRuntimes/Python/msrest/msrest/http_logger.py @@ -81,8 +81,8 @@ def log_response(adapter, request, response, *args, **kwargs): _LOGGER.debug("Body contains binary data.") elif result.headers.get("content-type", "").startswith("image"): _LOGGER.debug("Body contains image data.") - # elif result.headers.get("transfer-encoding") == 'chunked': - # LOGGER.debug("Body contains chunked data.") + elif result.headers.get("transfer-encoding") == 'chunked': + _LOGGER.debug("Body contains chunked data.") else: _LOGGER.debug(str(result.content)) return result diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index 40f4c88578686..25aff136d1538 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -406,7 +406,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialized.append(None) if div: - return div.join(serialized) + serialized = ['' if s is None else s for s in serialized] + serialized = div.join(serialized) return serialized def serialize_dict(self, attr, dict_type, **kwargs): diff --git a/ClientRuntimes/Python/msrest/msrest/service_client.py b/ClientRuntimes/Python/msrest/msrest/service_client.py index 523c6648582f1..6c27b017e111a 100644 --- a/ClientRuntimes/Python/msrest/msrest/service_client.py +++ b/ClientRuntimes/Python/msrest/msrest/service_client.py @@ -146,7 +146,7 @@ def send_formdata(self, request, headers={}, content={}, **config): :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param dict content: Dictionary of the fields of the formdata. - :param config: Any specific config overrides + :param config: Any specific config overrides. """ file_data = {f: self._format_data(d) for f, d in content.items()} try: @@ -163,6 +163,7 @@ def send(self, request, headers=None, content=None, **config): :param content: Any body data to add to the request. :param config: Any specific config overrides """ + response = None session = self.creds.signed_session() kwargs = self._configure_session(session, **config) @@ -204,7 +205,8 @@ def send(self, request, headers=None, content=None, **config): msg = "Error occurred in request." raise_with_traceback(ClientRequestError, msg, err) finally: - session.close() + if not response or response._content_consumed: + session.close() def stream_download(self, data, callback): """Generator for streaming request body data. @@ -228,7 +230,6 @@ def stream_download(self, data, callback): if callback and callable(callback): callback(chunk, response=data) yield chunk - data.close() def stream_upload(self, data, callback): """Generator for streaming request body data. diff --git a/ClientRuntimes/Python/msrest/test/unittest_runtime.py b/ClientRuntimes/Python/msrest/test/unittest_runtime.py index 7bb798d5af6d4..fbdad6791f772 100644 --- a/ClientRuntimes/Python/msrest/test/unittest_runtime.py +++ b/ClientRuntimes/Python/msrest/test/unittest_runtime.py @@ -101,7 +101,7 @@ def hook(aptr, req, *args, **kwargs): @mock.patch.object(requests, 'Session') def test_request_fail(self, mock_requests): - mock_requests.return_value.request.return_value = "test" + mock_requests.return_value.request.return_value = mock.Mock(_content_consumed=True) cfg = Configuration("https://my_service.com") creds = Authentication() @@ -113,7 +113,7 @@ def test_request_fail(self, mock_requests): check = httpretty.last_request() - self.assertEqual(response, "test") + self.assertTrue(response._content_consumed) mock_requests.return_value.request.side_effect = requests.RequestException with self.assertRaises(ClientRequestError): @@ -127,6 +127,8 @@ def test_request_proxy(self): def hook(adptr, request, *args, **kwargs): self.assertEqual(kwargs.get('proxies'), {"http://my_service.com":'http://localhost:57979'}) + kwargs['result']._content_consumed = True + kwargs['result'].status_code = 200 return kwargs['result'] client = ServiceClient(creds, cfg) @@ -139,6 +141,8 @@ def hook(adptr, request, *args, **kwargs): def hook2(adptr, request, *args, **kwargs): self.assertEqual(kwargs.get('proxies')['https'], "http://localhost:1987") + kwargs['result']._content_consumed = True + kwargs['result'].status_code = 200 return kwargs['result'] cfg = Configuration("http://my_service.com") diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py index 732eb30e70fb2..00031c87fca75 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py @@ -43,9 +43,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-06-15', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com' From 91d73c6bd81deebe2fd83090d60d63f38a08932a Mon Sep 17 00:00:00 2001 From: annatisch Date: Fri, 15 Apr 2016 16:19:30 -0700 Subject: [PATCH 90/99] Python Streaming Test Fix (#953) * Debugging test failure * testing without header * Adding header back again --- .../Python/Python.Tests/AcceptanceTests/file_tests.py | 8 ++++++-- ClientRuntimes/Python/msrest/msrest/service_client.py | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py index 22511e8de15c7..c45c3e0db6836 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py @@ -60,8 +60,8 @@ def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) self.assertIsNotNone(response) self.assertFalse(response._content_consumed) - total = float(response.headers.get('Content-Length', 0)) - if total: + total = float(response.headers['Content-Length']) + if total < 4096: progress[0] += len(data) print("Downloading... {}%".format(int(progress[0]*100/total))) @@ -94,7 +94,11 @@ def test_callback(data, response, progress=[0]): self.assertEqual(file_length, 0) + def add_headers(adapter, request, response, *args, **kwargs): + response.headers['Content-Length'] = str(3000 * 1024 * 1024) + file_length = 0 + client._client.add_hook('response', add_headers) stream = client.files.get_file_large(callback=test_callback) for data in stream: file_length += len(data) diff --git a/ClientRuntimes/Python/msrest/msrest/service_client.py b/ClientRuntimes/Python/msrest/msrest/service_client.py index 6c27b017e111a..a204089838ddc 100644 --- a/ClientRuntimes/Python/msrest/msrest/service_client.py +++ b/ClientRuntimes/Python/msrest/msrest/service_client.py @@ -230,6 +230,8 @@ def stream_download(self, data, callback): if callback and callable(callback): callback(chunk, response=data) yield chunk + data.close() + self._adapter.close() def stream_upload(self, data, callback): """Generator for streaming request body data. From d41d44c1d80f10460a8cc8d4d4811f971407ead2 Mon Sep 17 00:00:00 2001 From: John-Hart Date: Tue, 19 Apr 2016 13:12:02 -0700 Subject: [PATCH 91/99] Added a LRO acceptance test to verify that a CloudException is thrown when a JSONException occurs during Deserialization of the response content --- .../Azure.CSharp.Tests/AcceptanceTests.cs | 4 + .../AcceptanceTests/Lro/ILROSADsOperations.cs | 28 +++ .../AcceptanceTests/Lro/LROSADsOperations.cs | 203 ++++++++++++++++++ .../Lro/LROSADsOperationsExtensions.cs | 72 +++++++ AutoRest/TestServer/server/routes/lros.js | 10 + AutoRest/TestServer/swagger/lro.json | 40 ++++ 6 files changed, 357 insertions(+) diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs index d04c712fd1c96..46078380b3b9a 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs @@ -274,6 +274,10 @@ public void LroSadPathTests() Assert.Equal("Error from the server", exception.Body.Message); Assert.NotNull(exception.Request); Assert.NotNull(exception.Response); + exception = + Assert.Throws(() => client.LROSADs.PutNonRetry201Creating400InvalidJson(new Product { Location = "West US" })); + Assert.Null(exception.Body); + Assert.Equal("Long running operation failed with status 'BadRequest'.", exception.Message); exception = Assert.Throws( () => client.LROSADs.PutAsyncRelativeRetry400(new Product {Location = "West US"})); diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs index 60ac71a045d3e..5717f7f8f64e8 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs @@ -79,6 +79,34 @@ public partial interface ILROSADsOperations /// Task> BeginPutNonRetry201Creating400WithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> PutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// /// Long running put request, service returns a 200 with /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs index 7b0662de0c29e..cbd54f78112ae 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs @@ -453,6 +453,209 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) return _result; } + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + public async Task> PutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Send Request + AzureOperationResponse _response = await BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync( + product, customHeaders, cancellationToken); + return await this.Client.GetPutOrPatchOperationResultAsync(_response, + customHeaders, + cancellationToken); + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("product", product); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "BeginPutNonRetry201Creating400InvalidJson", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/nonretryerror/put/201/creating/400/invalidjson").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 201) + { + var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + CloudError _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex = new CloudException(_errorBody.Message); + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + /// /// Long running put request, service returns a 200 with /// ProvisioningState=’Creating’. Poll the endpoint indicated in the diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs index 86b6c1b083fc9..dc7d177cbe402 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs @@ -162,6 +162,78 @@ public static partial class LROSADsOperationsExtensions } } + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + public static Product PutNonRetry201Creating400InvalidJson(this ILROSADsOperations operations, Product product = default(Product)) + { + return Task.Factory.StartNew(s => ((ILROSADsOperations)s).PutNonRetry201Creating400InvalidJsonAsync(product), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + /// + /// The cancellation token. + /// + public static async Task PutNonRetry201Creating400InvalidJsonAsync(this ILROSADsOperations operations, Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.PutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + public static Product BeginPutNonRetry201Creating400InvalidJson(this ILROSADsOperations operations, Product product = default(Product)) + { + return Task.Factory.StartNew(s => ((ILROSADsOperations)s).BeginPutNonRetry201Creating400InvalidJsonAsync(product), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + /// + /// The cancellation token. + /// + public static async Task BeginPutNonRetry201Creating400InvalidJsonAsync(this ILROSADsOperations operations, Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + /// /// Long running put request, service returns a 200 with /// ProvisioningState=’Creating’. Poll the endpoint indicated in the diff --git a/AutoRest/TestServer/server/routes/lros.js b/AutoRest/TestServer/server/routes/lros.js index 9d9dc540e16aa..1f896de2765cd 100644 --- a/AutoRest/TestServer/server/routes/lros.js +++ b/AutoRest/TestServer/server/routes/lros.js @@ -940,6 +940,16 @@ var lros = function (coverage) { res.status(400).end('{ "message" : "Error from the server" }'); }); + coverage['LRONonRetryPut201Creating400InvalidJson'] = 0; + router.put('/nonretryerror/put/201/creating/400/invalidjson', function (req, res, next) { + res.status(201).end('{ "properties": { "provisioningState": "Creating"}, "id": "100", "name": "foo" }'); + }); + + router.get('/nonretryerror/put/201/creating/400/invalidjson', function (req, res, next) { + coverage['LRONonRetryPut201Creating400InvalidJson']++; + res.status(400).end('<{ "message" : "Error from the server" }'); + }); + coverage['LRONonRetryPutAsyncRetry400'] = 0; router.put('/nonretryerror/putasync/retry/400', function (req, res, next) { var pollingUri = 'http://localhost.:' + utils.getPort() + '/lro/nonretryerror/putasync/retry/failed/operationResults/400'; diff --git a/AutoRest/TestServer/swagger/lro.json b/AutoRest/TestServer/swagger/lro.json index b064ce8c3aa2d..9f9bba0c26759 100644 --- a/AutoRest/TestServer/swagger/lro.json +++ b/AutoRest/TestServer/swagger/lro.json @@ -1772,6 +1772,46 @@ } } } + }, + "/lro/nonretryerror/put/201/creating/400/invalidjson": { + "put": { + "x-ms-long-running-operation": true, + "operationId": "LROSADs_putNonRetry201Creating400InvalidJson", + "description": "Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code", + "tags": [ + "LROSAD Operations" + ], + "parameters": [ + { + "name": "product", + "description": "Product to put", + "in": "body", + "schema": { + "$ref": "#/definitions/Product" + } + } + ], + "responses": { + "200": { + "description": "Response after completion, with ProvisioningState='Succeeded'", + "schema": { + "$ref": "#/definitions/Product" + } + }, + "201": { + "description": "Initial response, with ProvisioningState = 'Creating'", + "schema": { + "$ref": "#/definitions/Product" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/CloudError" + } + } + } + } }, "/lro/nonretryerror/putasync/retry/400": { "put": { From 16b8f29cfba5ff953897b641680844c3c98928af Mon Sep 17 00:00:00 2001 From: John-Hart Date: Tue, 19 Apr 2016 17:13:11 -0700 Subject: [PATCH 92/99] Set the intial coverage for the LRONonRetryPut201Creating400InvalidJson to 1 --- AutoRest/TestServer/server/routes/lros.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AutoRest/TestServer/server/routes/lros.js b/AutoRest/TestServer/server/routes/lros.js index 1f896de2765cd..ca11fa50082be 100644 --- a/AutoRest/TestServer/server/routes/lros.js +++ b/AutoRest/TestServer/server/routes/lros.js @@ -940,7 +940,8 @@ var lros = function (coverage) { res.status(400).end('{ "message" : "Error from the server" }'); }); - coverage['LRONonRetryPut201Creating400InvalidJson'] = 0; + /* TODO: only C# has implemented this test. Exclude it from code coverage until it is implemented in other languages */ + coverage['LRONonRetryPut201Creating400InvalidJson'] = 1; router.put('/nonretryerror/put/201/creating/400/invalidjson', function (req, res, next) { res.status(201).end('{ "properties": { "provisioningState": "Creating"}, "id": "100", "name": "foo" }'); }); From dccbc73bdcd6ce3bd95e22b44d03e40b945fbeff Mon Sep 17 00:00:00 2001 From: tbombach Date: Thu, 21 Apr 2016 12:37:03 -0700 Subject: [PATCH 93/99] Simplifying the logic for determining SerializationSettings Removing duplicated and hard-to-read code that determined the C# serialization/deserialization settings to be used for an IType. Changes are needed because adding new checks for known primary types was failing builds based cyclomatic complexity > 25. This change adds extension methods that determine if an IType is either a PrimaryType for a given KnownPrimaryType, or a DictionaryType/SequenceType that contains values of that known type. --- .../AutoRest.Core/Utilities/Extensions.cs | 51 ++++++++++++++++++- .../TemplateModels/MethodTemplateModel.cs | 47 +++-------------- 2 files changed, 57 insertions(+), 41 deletions(-) diff --git a/AutoRest/AutoRest.Core/Utilities/Extensions.cs b/AutoRest/AutoRest.Core/Utilities/Extensions.cs index 23bea5173d9db..9a18e21f1f5b4 100644 --- a/AutoRest/AutoRest.Core/Utilities/Extensions.cs +++ b/AutoRest/AutoRest.Core/Utilities/Extensions.cs @@ -244,7 +244,7 @@ public static string EscapeXmlComment(this string comment) } /// - /// Returns true is the type is a PrimaryType with KnownPrimaryType matching typeToMatch. + /// Returns true if the type is a PrimaryType with KnownPrimaryType matching typeToMatch. /// /// /// @@ -263,5 +263,54 @@ public static bool IsPrimaryType(this IType type, KnownPrimaryType typeToMatch) } return false; } + + /// + /// Returns true if the is a PrimaryType with KnownPrimaryType matching + /// or a DictionaryType with ValueType matching or a SequenceType matching + /// + /// + /// + /// + public static bool IsOrContainsPrimaryType(this IType type, KnownPrimaryType typeToMatch) + { + if (type == null) + { + return false; + } + + if (type.IsPrimaryType(typeToMatch) || + type.IsDictionaryContainingType(typeToMatch) || + type.IsSequenceContainingType(typeToMatch)) + { + return true; + } + return false; + } + + /// + /// Returns true if the is a DictionaryType with ValueType matching + /// + /// + /// + /// + public static bool IsDictionaryContainingType(this IType type, KnownPrimaryType typeToMatch) + { + DictionaryType dictionaryType = type as DictionaryType; + PrimaryType dictionaryPrimaryType = dictionaryType?.ValueType as PrimaryType; + return dictionaryPrimaryType != null && dictionaryPrimaryType.IsPrimaryType(typeToMatch); + } + + /// + /// Returns true if the is a SequenceType matching + /// + /// + /// + /// + public static bool IsSequenceContainingType(this IType type, KnownPrimaryType typeToMatch) + { + SequenceType sequenceType = type as SequenceType; + PrimaryType sequencePrimaryType = sequenceType?.ElementType as PrimaryType; + return sequencePrimaryType != null && sequencePrimaryType.IsPrimaryType(typeToMatch); + } } } \ No newline at end of file diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs index d4a380df2765c..22d1ca54614d0 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs @@ -325,37 +325,19 @@ public string ClientReference /// public string GetSerializationSettingsReference(IType serializationType) { - SequenceType sequenceType = serializationType as SequenceType; - DictionaryType dictionaryType = serializationType as DictionaryType; - if (serializationType.IsPrimaryType(KnownPrimaryType.Date) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Date) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Date)) + if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new DateJsonConverter()"; } - else if (serializationType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.DateTimeRfc1123) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.DateTimeRfc1123)) + else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { return "new DateTimeRfc1123JsonConverter()"; } - else if (serializationType.IsPrimaryType(KnownPrimaryType.Base64Url) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Base64Url) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Base64Url)) + else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) { return "new Base64UrlJsonConverter()"; } - else if (serializationType.IsPrimaryType(KnownPrimaryType.UnixTime) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.UnixTime) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.UnixTime)) + else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) { return "new UnixTimeJsonConverter()"; } @@ -369,33 +351,18 @@ public string GetSerializationSettingsReference(IType serializationType) /// public string GetDeserializationSettingsReference(IType deserializationType) { - SequenceType sequenceType = deserializationType as SequenceType; - DictionaryType dictionaryType = deserializationType as DictionaryType; - if (deserializationType.IsPrimaryType(KnownPrimaryType.Date) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Date) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Date)) + if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new DateJsonConverter()"; } - else if (deserializationType.IsPrimaryType(KnownPrimaryType.Base64Url) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Base64Url) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Base64Url)) + else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) { return "new Base64UrlJsonConverter()"; } - else if (deserializationType.IsPrimaryType(KnownPrimaryType.UnixTime) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.UnixTime) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.UnixTime)) + else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) { return "new UnixTimeJsonConverter()"; } - return ClientReference + ".DeserializationSettings"; } From 468c8c4e0e8665a47708901c21cbfe25b4a1a863 Mon Sep 17 00:00:00 2001 From: John Hart Date: Fri, 22 Apr 2016 13:31:47 -0700 Subject: [PATCH 94/99] Fixes the issue where the contents of the output file for SingleFileGeneration are appended to each time Autorest is run (#968) * Deleted the file specified in the OutputFileName the before writing to it the first time. * Updated OutputToSingleFile test to verify contents are overwritten * Corrected the new Assert in OutputToSingFile test --- .../CodeGeneratorsTests.cs | 3 +++ AutoRest/AutoRest.Core/CodeGenerator.cs | 21 +++++++++++-------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs b/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs index c58c81e4e6b0c..8cadb3f6414f4 100644 --- a/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs +++ b/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs @@ -86,8 +86,11 @@ public void OutputToSingleFile() }; string path = Path.Combine(settings.OutputDirectory, "test.file.cs"); + string existingContents = "this is dummy"; + _fileSystem.VirtualStore[path] = new StringBuilder(existingContents); var codeGenerator = new SampleCodeGenerator(settings); codeGenerator.Generate(new ServiceClient()).GetAwaiter().GetResult(); + Assert.DoesNotContain(existingContents, _fileSystem.VirtualStore[path].ToString()); Assert.Equal(4, _fileSystem.VirtualStore.Count); Assert.True(_fileSystem.VirtualStore.ContainsKey(path)); Assert.True(_fileSystem.VirtualStore.ContainsKey("AutoRest.json")); diff --git a/AutoRest/AutoRest.Core/CodeGenerator.cs b/AutoRest/AutoRest.Core/CodeGenerator.cs index 8efb1c0311361..57dbecb697346 100644 --- a/AutoRest/AutoRest.Core/CodeGenerator.cs +++ b/AutoRest/AutoRest.Core/CodeGenerator.cs @@ -16,6 +16,7 @@ namespace Microsoft.Rest.Generator public abstract class CodeGenerator { public const string EnumObject = "x-ms-enum"; + private bool firstTimeWriteSingleFile = true; protected CodeGenerator(Settings settings) { @@ -99,7 +100,7 @@ public async Task Write(ITemplate template, string fileName) /// public async Task Write(string template, string fileName) { - string relativeFilePath = null; + string filePath = null; if (Settings.OutputFileName != null) { @@ -110,17 +111,19 @@ public async Task Write(string template, string fileName) ErrorManager.ThrowErrors(); } - relativeFilePath = Settings.OutputFileName; + filePath = Path.Combine(Settings.OutputDirectory, Settings.OutputFileName); + + if (firstTimeWriteSingleFile) + { + // for SingleFileGeneration clean the file before writing only if its the first time + Settings.FileSystem.DeleteFile(filePath); + firstTimeWriteSingleFile = false; + } } else { - relativeFilePath = fileName; - } - string filePath = Path.Combine(Settings.OutputDirectory, relativeFilePath); - - // cleans file before writing unless single file - if (!(Settings.OutputFileName != null && IsSingleFileGenerationSupported)) - { + filePath = Path.Combine(Settings.OutputDirectory, fileName); + // cleans file before writing Settings.FileSystem.DeleteFile(filePath); } // Make sure the directory exist From d1d781c39695423fb04e8f37933b39f204a6cffe Mon Sep 17 00:00:00 2001 From: annatisch Date: Fri, 22 Apr 2016 13:32:59 -0700 Subject: [PATCH 95/99] Python Read-only and UTF-8 support (#959) * Test server debuging * removed stream connection closing * Revised serialization to support readonly attributes * Updated generator for better readonly attributes * Updated tests * Regenerated tests * Removed explicit read-only parameters * Updated readonly docstrings * Removed properties * enforced utf-8 encoding * Updated generated docstrings * Added file write encoding * Support for const class attrs * Regenerated tests * fixed bad revert * Modified file read encoding * Removed unused refs * Fixed null reference bug for composite modeler * Better default handling * Added file read utf-8 encoding * removing test for now * removed from coverage --- .../AutoRest.Core/Utilities/FileSystem.cs | 4 +- .../models/flattened_product.py | 25 ++++-- .../models/resource.py | 29 +++--- .../models/product.py | 32 ++++--- .../models/resource.py | 29 +++--- .../models/sub_product.py | 22 +++-- .../models/sub_resource.py | 15 +++- .../models/resource.py | 26 +++--- .../models/storage_account.py | 22 +++-- .../storage_account_create_parameters.py | 22 +++-- .../storage_account_update_parameters.py | 22 +++-- .../AzureServiceClientTemplateModel.cs | 2 +- .../AcceptanceTests/complex_tests.py | 13 +++ .../AcceptanceTests/file_tests.py | 6 +- .../AcceptanceTests/validation_tests.py | 12 ++- .../Python.Tests/AcceptanceTests/zzz_tests.py | 7 +- .../models/readonly_obj.py | 15 +++- ...t_parameterized_custom_host_test_client.py | 8 +- .../models/flattened_product.py | 32 ++++--- .../models/resource.py | 29 +++--- .../models/simple_product.py | 10 ++- .../models/child_product.py | 10 ++- .../models/constant_product.py | 17 ++-- .../autorestvalidationtest/models/product.py | 25 ++++-- .../TemplateModels/MethodTemplateModel.cs | 9 +- .../TemplateModels/ModelTemplateModel.cs | 90 ++++++++++++++++--- .../Python/Templates/ModelTemplate.cshtml | 66 ++++++++++---- .../Python/msrest/msrest/serialization.py | 26 +++--- .../models/resource.py | 29 +++--- .../models/storage_account.py | 25 ++++-- .../Python/swaggerpetstore/models/order.py | 15 +++- 31 files changed, 481 insertions(+), 213 deletions(-) diff --git a/AutoRest/AutoRest.Core/Utilities/FileSystem.cs b/AutoRest/AutoRest.Core/Utilities/FileSystem.cs index 231b6521090d3..13fab28c4cd4c 100644 --- a/AutoRest/AutoRest.Core/Utilities/FileSystem.cs +++ b/AutoRest/AutoRest.Core/Utilities/FileSystem.cs @@ -3,6 +3,7 @@ using System.IO; using System.Net; +using System.Text; namespace Microsoft.Rest.Generator.Utilities { @@ -10,7 +11,7 @@ public class FileSystem : IFileSystem { public void WriteFile(string path, string contents) { - File.WriteAllText(path, contents); + File.WriteAllText(path, contents, Encoding.UTF8); } public string ReadFileAsText(string path) @@ -18,6 +19,7 @@ public string ReadFileAsText(string path) using (var client = new WebClient()) { client.Headers.Add("User-Agent: AutoRest"); + client.Encoding = Encoding.UTF8; return client.DownloadString(path); } } diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py index 5b5b7ea2e4c04..37bf31568e6ae 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py @@ -15,16 +15,19 @@ class FlattenedProduct(Resource): """FlattenedProduct - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str :param pname: :type pname: str :param lsize: @@ -33,6 +36,12 @@ class FlattenedProduct(Resource): :type provisioning_state: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -44,8 +53,8 @@ class FlattenedProduct(Resource): 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, lsize=None, provisioning_state=None): - super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name) + def __init__(self, tags=None, location=None, pname=None, lsize=None, provisioning_state=None): + super(FlattenedProduct, self).__init__(tags=tags, location=location) self.pname = pname self.lsize = lsize self.provisioning_state = provisioning_state diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py index ccc46d79f60ce..349e6b7fbd717 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py @@ -15,18 +15,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -35,9 +44,9 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None): - self.id = id - self.type = type + def __init__(self, tags=None, location=None): + self.id = None + self.type = None self.tags = tags self.location = location - self.name = name + self.name = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py index 6f322f37b09fc..1671df6f6c655 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py @@ -15,24 +15,34 @@ class Product(Resource): """Product - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str :param provisioning_state: :type provisioning_state: str - :param provisioning_state_values: Possible values include: 'Succeeded', + :ivar provisioning_state_values: Possible values include: 'Succeeded', 'Failed', 'canceled', 'Accepted', 'Creating', 'Created', 'Updating', 'Updated', 'Deleting', 'Deleted', 'OK' - :type provisioning_state_values: str + :vartype provisioning_state_values: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + 'provisioning_state_values': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -43,7 +53,7 @@ class Product(Resource): 'provisioning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, provisioning_state=None, provisioning_state_values=None): - super(Product, self).__init__(id=id, type=type, tags=tags, location=location, name=name) + def __init__(self, tags=None, location=None, provisioning_state=None): + super(Product, self).__init__(tags=tags, location=location) self.provisioning_state = provisioning_state - self.provisioning_state_values = provisioning_state_values + self.provisioning_state_values = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py index ccc46d79f60ce..349e6b7fbd717 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py @@ -15,18 +15,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -35,9 +44,9 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None): - self.id = id - self.type = type + def __init__(self, tags=None, location=None): + self.id = None + self.type = None self.tags = tags self.location = location - self.name = name + self.name = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py index 099f79ecdc9de..c813566223b8d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py @@ -15,23 +15,31 @@ class SubProduct(SubResource): """SubProduct - :param id: Sub Resource Id - :type id: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Sub Resource Id + :vartype id: str :param provisioning_state: :type provisioning_state: str - :param provisioning_state_values: Possible values include: 'Succeeded', + :ivar provisioning_state_values: Possible values include: 'Succeeded', 'Failed', 'canceled', 'Accepted', 'Creating', 'Created', 'Updating', 'Updated', 'Deleting', 'Deleted', 'OK' - :type provisioning_state_values: str + :vartype provisioning_state_values: str """ + _validation = { + 'id': {'readonly': True}, + 'provisioning_state_values': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'}, } - def __init__(self, id=None, provisioning_state=None, provisioning_state_values=None): - super(SubProduct, self).__init__(id=id) + def __init__(self, provisioning_state=None): + super(SubProduct, self).__init__() self.provisioning_state = provisioning_state - self.provisioning_state_values = provisioning_state_values + self.provisioning_state_values = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py index 46ce23db785ac..77ec6cf29f437 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py @@ -15,13 +15,20 @@ class SubResource(Model): """SubResource - :param id: Sub Resource Id - :type id: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Sub Resource Id + :vartype id: str """ + _validation = { + 'id': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } - def __init__(self, id=None): - self.id = id + def __init__(self): + self.id = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py index 9025ae9819072..8d25c5c02f7ac 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py @@ -15,12 +15,15 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -28,6 +31,9 @@ class Resource(Model): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -39,9 +45,9 @@ class Resource(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None): - self.id = id - self.name = name - self.type = type + def __init__(self, location, tags=None): + self.id = None + self.name = None + self.type = None self.location = location self.tags = tags diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py index 3268320474a92..bff1707d78076 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py @@ -16,12 +16,15 @@ class StorageAccount(Resource): """ The storage account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -77,6 +80,9 @@ class StorageAccount(Resource): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -99,8 +105,8 @@ class StorageAccount(Resource): 'secondary_endpoints': {'key': 'properties.secondaryEndpoints', 'type': 'Endpoints'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None): - super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags) + def __init__(self, location, tags=None, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None): + super(StorageAccount, self).__init__(location=location, tags=tags) self.provisioning_state = provisioning_state self.account_type = account_type self.primary_endpoints = primary_endpoints diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py index 449f6c502135a..31535a2dc8c20 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py @@ -16,12 +16,15 @@ class StorageAccountCreateParameters(Resource): """ The parameters to provide for the account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -33,6 +36,9 @@ class StorageAccountCreateParameters(Resource): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -45,6 +51,6 @@ class StorageAccountCreateParameters(Resource): 'account_type': {'key': 'properties.accountType', 'type': 'AccountType'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None): - super(StorageAccountCreateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags) + def __init__(self, location, tags=None, account_type=None): + super(StorageAccountCreateParameters, self).__init__(location=location, tags=tags) self.account_type = account_type diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py index 5975e56879436..e60b187d613bd 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py @@ -16,12 +16,15 @@ class StorageAccountUpdateParameters(Resource): """ The parameters to update on the account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -41,6 +44,9 @@ class StorageAccountUpdateParameters(Resource): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -54,7 +60,7 @@ class StorageAccountUpdateParameters(Resource): 'custom_domain': {'key': 'properties.customDomain', 'type': 'CustomDomain'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None, custom_domain=None): - super(StorageAccountUpdateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags) + def __init__(self, location, tags=None, account_type=None, custom_domain=None): + super(StorageAccountUpdateParameters, self).__init__(location=location, tags=tags) self.account_type = account_type self.custom_domain = custom_domain diff --git a/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs b/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs index 3c0cfcbf8160c..f56bc3935547a 100644 --- a/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs +++ b/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs @@ -74,7 +74,7 @@ public override string RequiredConstructorParameters else { string defaultValue = PythonConstants.None; - if (property.DefaultValue != null && property.Type is PrimaryType) + if (!string.IsNullOrWhiteSpace(property.DefaultValue) && property.Type is PrimaryType) { defaultValue = property.DefaultValue; } diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py index fcbf2f38617cf..fa4902659e391 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py @@ -201,6 +201,19 @@ def test_complex(self): # PUT primitive/byte client.primitive.put_byte(valid_bytes) + """ + COMPLEX TYPE WITH READ ONLY PROPERTIES + """ + # GET readonly/valid + valid_obj = ReadonlyObj(size=2) + valid_obj.id = '1234' + readonly_result = client.readonlyproperty.get_valid() + self.assertEqual(readonly_result, valid_obj) + + # PUT readonly/valid + readonly_result = client.readonlyproperty.put_valid(valid_obj) + self.assertIsNone(readonly_result) + """ COMPLEX TYPE WITH ARRAY PROPERTIES """ diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py index c45c3e0db6836..900265a4ed1fe 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py @@ -100,10 +100,10 @@ def add_headers(adapter, request, response, *args, **kwargs): file_length = 0 client._client.add_hook('response', add_headers) stream = client.files.get_file_large(callback=test_callback) - for data in stream: - file_length += len(data) + #for data in stream: + # file_length += len(data) - self.assertEqual(file_length, 3000 * 1024 * 1024) + #self.assertEqual(file_length, 3000 * 1024 * 1024) def test_files_raw(self): diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py index 5af07d6773dbd..7e1ba54e0556e 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py @@ -67,10 +67,7 @@ def test_constant_values(self): client.get_with_constant_in_path() - # TODO: Const body should be built implicitly body = Product(child=ChildProduct()) - body.const_child = ConstantProduct() - product = client.post_with_constant_in_body(body=body) self.assertIsNotNone(product) @@ -121,7 +118,6 @@ def test_validation(self): try: tempproduct=Product(child=ChildProduct(), capacity=0) - tempproduct.const_child=ConstantProduct() client.validation_of_body("123", 150, tempproduct) except ValidationError as err: self.assertEqual(err.rule, "minimum_ex") @@ -129,7 +125,6 @@ def test_validation(self): try: tempproduct=Product(child=ChildProduct(), capacity=100) - tempproduct.const_child=ConstantProduct() client.validation_of_body("123", 150, tempproduct) except ValidationError as err: self.assertEqual(err.rule, "maximum_ex") @@ -138,7 +133,6 @@ def test_validation(self): try: tempproduct=Product(child=ChildProduct(), display_names=["item1","item2","item3","item4","item5","item6","item7"]) - tempproduct.const_child=ConstantProduct() client.validation_of_body("123", 150, tempproduct) except ValidationError as err: self.assertEqual(err.rule, "max_items") @@ -155,4 +149,8 @@ def test_validation(self): client2.validation_of_method_parameters("123", 150) except ValidationError as err: self.assertEqual(err.rule, "pattern") - self.assertEqual(err.target, "self.config.api_version") \ No newline at end of file + self.assertEqual(err.target, "self.config.api_version") + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py index ccafa013129b1..2afd6aa9c3c70 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py @@ -54,6 +54,7 @@ def test_ensure_coverage(self): client = AutoRestReportService(config) report = client.get_report() + # Add tests that wont be supported due to the nature of Python here not_supported = { 'getIntegerOverflow': 1, 'getIntegerUnderflow': 1, @@ -64,10 +65,8 @@ def test_ensure_coverage(self): 'HttpRedirect300Get': 1, } - # TODO: Support ignore readonly property in http put - missing_features_or_bugs = { - 'putComplexReadOnlyPropertyValid': 1, - } + # Please add missing features or failing tests here + missing_features_or_bugs = {'FileStreamVeryLarge' : 1} report.update(not_supported) report.update(missing_features_or_bugs) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py index f0db42cc1b3f9..109d15efbe7e4 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py @@ -15,17 +15,24 @@ class ReadonlyObj(Model): """ReadonlyObj - :param id: - :type id: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: + :vartype id: str :param size: :type size: int """ + _validation = { + 'id': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'size': {'key': 'size', 'type': 'int'}, } - def __init__(self, id=None, size=None): - self.id = id + def __init__(self, size=None): + self.id = None self.size = size 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 index 1e9140c3e5f70..6a61d697f46ef 100644 --- 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 @@ -33,9 +33,13 @@ def __init__( self, subscription_id, dns_suffix, filepath=None): if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") if dns_suffix is None: - raise ValueError('dns_suffix must not be None.') + raise ValueError("Parameter 'dns_suffix' must not be None.") + if not isinstance(dns_suffix, str): + raise TypeError("Parameter 'dns_suffix' must be str.") base_url = '{vault}{secret}{dnsSuffix}' super(AutoRestParameterizedCustomHostTestClientConfiguration, self).__init__(base_url, filepath) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py index 99e49b9aa384f..55df7eedae364 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py @@ -15,28 +15,38 @@ class FlattenedProduct(Resource): """FlattenedProduct - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str :param pname: :type pname: str :param flattened_product_type: :type flattened_product_type: str - :param provisioning_state_values: Possible values include: 'Succeeded', + :ivar provisioning_state_values: Possible values include: 'Succeeded', 'Failed', 'canceled', 'Accepted', 'Creating', 'Created', 'Updating', 'Updated', 'Deleting', 'Deleted', 'OK' - :type provisioning_state_values: str + :vartype provisioning_state_values: str :param provisioning_state: :type provisioning_state: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + 'provisioning_state_values': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -49,9 +59,9 @@ class FlattenedProduct(Resource): 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, flattened_product_type=None, provisioning_state_values=None, provisioning_state=None): - super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name) + def __init__(self, tags=None, location=None, pname=None, flattened_product_type=None, provisioning_state=None): + super(FlattenedProduct, self).__init__(tags=tags, location=location) self.pname = pname self.flattened_product_type = flattened_product_type - self.provisioning_state_values = provisioning_state_values + self.provisioning_state_values = None self.provisioning_state = provisioning_state diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py index ccc46d79f60ce..349e6b7fbd717 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py @@ -15,18 +15,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -35,9 +44,9 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None): - self.id = id - self.type = type + def __init__(self, tags=None, location=None): + self.id = None + self.type = None self.tags = tags self.location = location - self.name = name + self.name = None diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py index 1be642054ecac..02537d1797c79 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py @@ -16,6 +16,9 @@ class SimpleProduct(BaseProduct): """ The product documentation. + Variables are only populated by the server, and will be ignored when + sending a request. + :param product_id: Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. @@ -24,9 +27,9 @@ class SimpleProduct(BaseProduct): :type description: str :param max_product_display_name: Display name of product. :type max_product_display_name: str - :param capacity: Capacity of product. For example, 4 people. Default + :ivar capacity: Capacity of product. For example, 4 people. Default value: "Large" . - :type capacity: str + :vartype capacity: str :param generic_value: Generic URL value. :type generic_value: str :param odatavalue: URL value. @@ -48,9 +51,10 @@ class SimpleProduct(BaseProduct): 'odatavalue': {'key': 'details.max_product_image.@odata\\.value', 'type': 'str'}, } + capacity = "Large" + def __init__(self, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None): super(SimpleProduct, self).__init__(product_id=product_id, description=description) self.max_product_display_name = max_product_display_name - self.capacity = "Large" self.generic_value = generic_value self.odatavalue = odatavalue diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py index e7270ddf47641..0ef944dd8e9ca 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py @@ -16,8 +16,11 @@ class ChildProduct(Model): """ The product documentation. - :param const_property: Constant string. Default value: "constant" . - :type const_property: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar const_property: Constant string. Default value: "constant" . + :vartype const_property: str :param count: Count :type count: int """ @@ -31,6 +34,7 @@ class ChildProduct(Model): 'count': {'key': 'count', 'type': 'int'}, } + const_property = "constant" + def __init__(self, count=None): - self.const_property = "constant" self.count = count diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py index 14f416cef6f00..cb4531c4ec1aa 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py @@ -16,10 +16,13 @@ class ConstantProduct(Model): """ The product documentation. - :param const_property: Constant string. Default value: "constant" . - :type const_property: str - :param const_property2: Constant string2. Default value: "constant2" . - :type const_property2: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar const_property: Constant string. Default value: "constant" . + :vartype const_property: str + :ivar const_property2: Constant string2. Default value: "constant2" . + :vartype const_property2: str """ _validation = { @@ -32,6 +35,6 @@ class ConstantProduct(Model): 'const_property2': {'key': 'constProperty2', 'type': 'str'}, } - def __init__(self): - self.const_property = "constant" - self.const_property2 = "constant2" + const_property = "constant" + + const_property2 = "constant2" diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py index c9577fa07f23d..65d49c5d12e17 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py @@ -9,6 +9,7 @@ # regenerated. # -------------------------------------------------------------------------- +from .constant_product import ConstantProduct from msrest.serialization import Model @@ -16,6 +17,9 @@ class Product(Model): """ The product documentation. + Variables are only populated by the server, and will be ignored when + sending a request. + :param display_names: Non required array of unique items from 0 to 6 elements. :type display_names: list of str @@ -26,13 +30,13 @@ class Product(Model): :param child: :type child: :class:`ChildProduct ` - :param const_child: - :type const_child: :class:`ConstantProduct + :ivar const_child: + :vartype const_child: :class:`ConstantProduct ` - :param const_int: Constant int. Default value: 0 . - :type const_int: int - :param const_string: Constant string. Default value: "constant" . - :type const_string: str + :ivar const_int: Constant int. Default value: 0 . + :vartype const_int: int + :ivar const_string: Constant string. Default value: "constant" . + :vartype const_string: str :param const_string_as_enum: Constant string as Enum. Possible values include: 'constant_string_as_enum' :type const_string_as_enum: str @@ -59,12 +63,15 @@ class Product(Model): 'const_string_as_enum': {'key': 'constStringAsEnum', 'type': 'EnumConst'}, } + const_child = ConstantProduct() + + const_int = 0 + + const_string = "constant" + def __init__(self, child, display_names=None, capacity=None, image=None, const_string_as_enum=None): self.display_names = display_names self.capacity = capacity self.image = image self.child = child - self.const_child = None - self.const_int = 0 - self.const_string = "constant" self.const_string_as_enum = const_string_as_enum diff --git a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs index 0555d5cd4434e..ee71dc5b08b4d 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs @@ -33,6 +33,13 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) } AddCustomHeader = true; string formatter; + foreach (var parameter in LocalParameters) + { + if (string.IsNullOrWhiteSpace(parameter.DefaultValue)) + { + parameter.DefaultValue = PythonConstants.None; + } + } foreach (Match m in Regex.Matches(Url, @"\{[\w]+:[\w]+\}")) { formatter = m.Value.Split(':').First() + '}'; @@ -158,7 +165,7 @@ public virtual string MethodParameterDeclaration(bool addCustomHeaderParameters) foreach (var parameter in LocalParameters) { - if (parameter.IsRequired && parameter.DefaultValue.Equals(PythonConstants.None)) + if (parameter.IsRequired && parameter.DefaultValue == PythonConstants.None) { requiredDeclarations.Add(parameter.Name); } diff --git a/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs index dbd8fd040ff5f..2c43e7c092ca7 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; @@ -48,6 +49,14 @@ public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } + foreach (var property in ComposedProperties) + { + if (string.IsNullOrWhiteSpace(property.DefaultValue)) + { + property.DefaultValue = PythonConstants.None; + } + } + if (this.IsPolymorphic) { foreach (var modelType in ServiceClient.ModelTypes) @@ -104,6 +113,10 @@ public IList Validators { validation.Add("'constant': True"); } + if (parameter.IsReadOnly) + { + validation.Add("'readonly': True"); + } if (parameter.Constraints.Any()) { validation.AddRange(BuildValidationParameters(parameter.Constraints)); @@ -190,6 +203,22 @@ public bool HasParent get { return this._parent != null; } } + public bool NeedsConstructor + { + get + { + var nonConstant = Properties.Where(p => !p.IsConstant); + if (nonConstant.Any()) + { + return true; + } + else + { + return (HasParent || NeedsPolymorphicConverter); + } + } + } + /// /// Provides the modelProperty documentation string along with default value if any. /// @@ -202,11 +231,14 @@ public static string GetPropertyDocumentationString(Property property) { throw new ArgumentNullException("property"); } - string docString = string.Format(CultureInfo.InvariantCulture, ":param {0}:", property.Name); - + if (property.IsConstant || property.IsReadOnly) + { + docString = string.Format(CultureInfo.InvariantCulture, ":ivar {0}:", property.Name); + } + string documentation = property.Documentation; - if (!string.IsNullOrWhiteSpace(property.DefaultValue) && property.DefaultValue != PythonConstants.None) + if (property.DefaultValue != PythonConstants.None) { if (documentation != null && !documentation.EndsWith(".", StringComparison.OrdinalIgnoreCase)) { @@ -243,16 +275,43 @@ public IList RequiredFieldsList } } + public IEnumerable ReadOnlyAttributes + { + get + { + return ComposedProperties.Where(p => p.IsConstant || p.IsReadOnly); + } + } + + public IDictionary ComplexConstants + { + get + { + Dictionary complexConstant = new Dictionary (); + foreach (var property in Properties) + { + if (property.IsConstant) + { + CompositeType compType = property.Type as CompositeType; + if (compType != null) + { + complexConstant[property.Name] = compType; + } + } + } + return complexConstant; + } + } + public virtual string SuperParameterDeclaration() { List combinedDeclarations = new List(); - foreach (var property in ComposedProperties.Except(Properties)) + foreach (var property in ComposedProperties.Except(Properties).Except(ReadOnlyAttributes)) { if (this.IsPolymorphic) if (property.Name == this.BasePolymorphicDiscriminator) continue; - combinedDeclarations.Add(string.Format(CultureInfo.InvariantCulture, "{0}={0}", property.Name)); } return string.Join(", ", combinedDeclarations); @@ -264,17 +323,13 @@ public virtual string MethodParameterDeclaration() List requiredDeclarations = new List(); List combinedDeclarations = new List(); - foreach (var property in ComposedProperties) + foreach (var property in ComposedProperties.Except(ReadOnlyAttributes)) { if (this.IsPolymorphic) if (property.Name == this.BasePolymorphicDiscriminator) continue; - if (property.IsConstant) - { - continue; - } - if (property.IsRequired && property.DefaultValue.Equals(PythonConstants.None)) + if (property.IsRequired && property.DefaultValue == PythonConstants.None) { requiredDeclarations.Add(property.Name); } @@ -363,9 +418,20 @@ public string InitializeProperty(string objectName, Property property) { throw new ArgumentNullException("property"); } + if (property.IsReadOnly) + { + return string.Format(CultureInfo.InvariantCulture, "{0}.{1} = None", objectName, property.Name); + } if (property.IsConstant) { - return string.Format(CultureInfo.InvariantCulture, "{0}.{1} = {2}", objectName, property.Name, property.DefaultValue); + if (ComplexConstants.ContainsKey(property.Name)) + { + return string.Format(CultureInfo.InvariantCulture, "{0} = {1}()", property.Name, property.Type.Name); + } + else + { + return string.Format(CultureInfo.InvariantCulture, "{0} = {1}", property.Name, property.DefaultValue); + } } if (IsPolymorphic) { diff --git a/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml index 40ee94f75cb4b..17e86079f9cfd 100644 --- a/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml @@ -11,6 +11,13 @@ @Header("# ").TrimMultilineHeader() # -------------------------------------------------------------------------- @EmptyLine +@if(Model.ComplexConstants.Any()) +{ + foreach(var property in Model.ComplexConstants.Values) + { +@:from .@property.Name.ToPythonCase() import @property.Name + } +} @if (Model.BaseModelType != null) { @:from .@Model.BaseModelType.Name.ToPythonCase() import @Model.BaseModelType.Name @@ -42,14 +49,26 @@ else { @: """@(Model.Name) } +@if (Model.ReadOnlyAttributes.Any()) +{ +@EmptyLine +@: @WrapComment(string.Empty, "Variables are only populated by the server, and will be ignored when sending a request.") +} @if (Model.ComposedProperties.Any()) { @EmptyLine - foreach (var property in Model.ComposedProperties) - { + foreach (var property in Model.ComposedProperties) + { @: @ParameterWrapComment(string.Empty, ModelTemplateModel.GetPropertyDocumentationString(property)) + if (property.IsConstant || property.IsReadOnly) + { +@: @ParameterWrapComment(string.Empty, ":vartype " + property.Name + ": " + Model.GetPropertyDocumentationType(property.Type)) + } + else + { @: @ParameterWrapComment(string.Empty, ":type " + property.Name + ": " + Model.GetPropertyDocumentationType(property.Type)) - } + } + } } """ @if (Model.Validators.Any() || Model.RequiredFieldsList.Any()) @@ -89,26 +108,37 @@ else } } -@EmptyLine - def __init__(self@(Model.MethodParameterDeclaration())): -@if (Model.HasParent) +@foreach(var property in Model.Properties) { - @:super(@(Model.Name), self).__init__(@(Model.SuperParameterDeclaration())) + if (property.IsConstant) + { +@EmptyLine + @:@(Model.InitializeProperty(String.Empty, property)) + } } -@{ - var propertyList = new List(Model.Properties); - if (propertyList.Count > 0) - { - for (int i = 0; i < propertyList.Count; i++) - { +@if (Model.NeedsConstructor) +{ +@EmptyLine + @:def __init__(self@(Model.MethodParameterDeclaration())): + if (Model.HasParent) + { + @:super(@(Model.Name), self).__init__(@(Model.SuperParameterDeclaration())) + } + var propertyList = new List(Model.Properties); + if (propertyList.Count > 0) + { + for (int i = 0; i < propertyList.Count; i++) + { + if (!propertyList[i].IsConstant) + { @:@(Model.InitializeProperty("self", propertyList[i])) - } + } + } } -} - -@if (Model.NeedsPolymorphicConverter) -{ + if (Model.NeedsPolymorphicConverter) + { @:self.@Model.BasePolymorphicDiscriminator = '@Model.SerializedName' + } } @if (Model.IsException) { diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index 25aff136d1538..4675cd6aacee7 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -186,7 +186,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): attr_type = map['type'] orig_attr = getattr(target_obj, attr) validation = target_obj._validation.get(attr_name, {}) - self.validate(orig_attr, attr_name, **validation) + orig_attr = self.validate( + orig_attr, attr_name, **validation) new_attr = self.serialize_data( orig_attr, attr_type, **kwargs) @@ -245,7 +246,7 @@ def url(self, name, data, data_type, **kwargs): :raises: TypeError if serialization fails. :raises: ValueError if data is None """ - self.validate(data, name, required=True, **kwargs) + data = self.validate(data, name, required=True, **kwargs) try: output = self.serialize_data(data, data_type, **kwargs) if data_type == 'bool': @@ -269,7 +270,7 @@ def query(self, name, data, data_type, **kwargs): :raises: TypeError if serialization fails. :raises: ValueError if data is None """ - self.validate(data, name, required=True, **kwargs) + data = self.validate(data, name, required=True, **kwargs) try: if data_type in ['[str]']: data = ["" if d is None else d for d in data] @@ -295,7 +296,7 @@ def header(self, name, data, data_type, **kwargs): :raises: TypeError if serialization fails. :raises: ValueError if data is None """ - self.validate(data, name, required=True, **kwargs) + data = self.validate(data, name, required=True, **kwargs) try: if data_type in ['[str]']: data = ["" if d is None else d for d in data] @@ -315,6 +316,8 @@ def validate(self, data, name, **kwargs): raise ValidationError("required", name, True) elif data is None: return + elif kwargs.get('readonly'): + return try: for key, value in kwargs.items(): @@ -323,6 +326,8 @@ def validate(self, data, name, **kwargs): raise ValidationError(key, name, value) except TypeError: raise ValidationError("unknown", name) + else: + return data def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. @@ -690,15 +695,14 @@ def _instantiate_model(self, response, attrs): if callable(response): subtype = response._get_subtype_map() try: - consts = [k for k, v in response._validation.items() - if v.get('constant')] + readonly = [k for k, v in response._validation.items() + if v.get('readonly')] + const = [k for k, v in response._validation.items() + if v.get('constant')] kwargs = {k: v for k, v in attrs.items() - if k not in subtype and k not in consts} + if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) - - # We have to do this until we resolve the issue of complex - # constant attributes not being auto-instantiated. - for attr in consts: + for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) return response_obj except TypeError as err: diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py index e784f717664d9..87763cb25e4b4 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py @@ -8,18 +8,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags :type tags: dict """ + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, @@ -28,9 +37,9 @@ class Resource(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, id=None, name=None, type=None, location=None, tags=None): - self.id = id - self.name = name - self.type = type + def __init__(self, location=None, tags=None): + self.id = None + self.name = None + self.type = None self.location = location self.tags = tags diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py index 274af1b58793d..1aeaa6bc9f22d 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py @@ -9,12 +9,15 @@ class StorageAccount(Resource): """ The storage account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -24,6 +27,12 @@ class StorageAccount(Resource): ` """ + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, @@ -33,6 +42,6 @@ class StorageAccount(Resource): 'properties': {'key': 'properties', 'type': 'StorageAccountProperties'}, } - def __init__(self, id=None, name=None, type=None, location=None, tags=None, properties=None): - super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags) + def __init__(self, location=None, tags=None, properties=None): + super(StorageAccount, self).__init__(location=location, tags=tags) self.properties = properties diff --git a/Samples/petstore/Python/swaggerpetstore/models/order.py b/Samples/petstore/Python/swaggerpetstore/models/order.py index 8b7b27a2bbe96..6e1f3c0aac504 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/order.py +++ b/Samples/petstore/Python/swaggerpetstore/models/order.py @@ -8,8 +8,11 @@ class Order(Model): """Order - :param id: - :type id: long + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: + :vartype id: long :param pet_id: :type pet_id: long :param quantity: @@ -23,6 +26,10 @@ class Order(Model): :type complete: bool """ + _validation = { + 'id': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'long'}, 'pet_id': {'key': 'petId', 'type': 'long'}, @@ -32,8 +39,8 @@ class Order(Model): 'complete': {'key': 'complete', 'type': 'bool'}, } - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=None): - self.id = id + def __init__(self, pet_id=None, quantity=None, ship_date=None, status=None, complete=None): + self.id = None self.pet_id = pet_id self.quantity = quantity self.ship_date = ship_date From a7b6eb94049bae8e7eaa69b066791e7ed40dc2f8 Mon Sep 17 00:00:00 2001 From: John Hart Date: Fri, 22 Apr 2016 15:01:03 -0700 Subject: [PATCH 96/99] Added an ExitCode to Autorest.exe (#966) --- AutoRest/AutoRest/AutoRest.csproj | 3 ++- AutoRest/AutoRest/ExitCode.cs | 14 ++++++++++++++ AutoRest/AutoRest/Program.cs | 6 +++++- 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 AutoRest/AutoRest/ExitCode.cs diff --git a/AutoRest/AutoRest/AutoRest.csproj b/AutoRest/AutoRest/AutoRest.csproj index 8bd5ec84e97dd..7c578e0980acb 100644 --- a/AutoRest/AutoRest/AutoRest.csproj +++ b/AutoRest/AutoRest/AutoRest.csproj @@ -31,6 +31,7 @@ Properties\AssemblyVersionInfo.cs + @@ -70,4 +71,4 @@ - + \ No newline at end of file diff --git a/AutoRest/AutoRest/ExitCode.cs b/AutoRest/AutoRest/ExitCode.cs new file mode 100644 index 0000000000000..fe09a82b44c21 --- /dev/null +++ b/AutoRest/AutoRest/ExitCode.cs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +namespace Microsoft.Rest.Generator.Cli +{ + /// + /// Available exit codes. + /// + public enum ExitCode : int + { + Success = 0, + Error = 1 + } +} diff --git a/AutoRest/AutoRest/Program.cs b/AutoRest/AutoRest/Program.cs index b0c4aa7abea2b..f7bdf406b1066 100644 --- a/AutoRest/AutoRest/Program.cs +++ b/AutoRest/AutoRest/Program.cs @@ -12,8 +12,10 @@ namespace Microsoft.Rest.Generator.Cli { internal class Program { - private static void Main(string[] args) + private static int Main(string[] args) { + int exitCode = (int)ExitCode.Error; + try { Settings settings = null; @@ -69,6 +71,7 @@ private static void Main(string[] args) { Console.WriteLine(Resources.GenerationComplete, settings.CodeGenerator, settings.Input); + exitCode = (int)ExitCode.Success; } } @@ -91,6 +94,7 @@ private static void Main(string[] args) Console.Error.WriteLine(Resources.ConsoleErrorMessage, exception.Message); Console.Error.WriteLine(Resources.ConsoleErrorStackTrace, exception.StackTrace); } + return exitCode; } /// From 1e0252d4e3d0ff5d67fae439010a32a9dd90fcb2 Mon Sep 17 00:00:00 2001 From: Hovsep Date: Fri, 22 Apr 2016 16:35:14 -0700 Subject: [PATCH 97/99] Revert "Escape data strings for odata queries." --- .../Azure.CSharp.Tests/AcceptanceTests.cs | 3 +-- .../ODataTests.cs | 21 +++++++------------ .../OData/ODataQuery.cs | 6 +++--- 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs index d04c712fd1c96..ec21cdd514493 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs @@ -527,8 +527,7 @@ public void AzureODataTests() Top = 10, OrderBy = "id" }; - var filterString = Uri.EscapeDataString("id gt 5 and name eq 'foo'"); - Assert.Equal(string.Format("$filter={0}&$orderby=id&$top=10", filterString), filter.ToString()); + Assert.Equal("$filter=id gt 5 and name eq 'foo'&$orderby=id&$top=10", filter.ToString()); client.Odata.GetWithFilter(filter); } } diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs index 639023af44855..c651bbdc33621 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs @@ -227,7 +227,6 @@ public void EncodingTheParameters() [Fact] public void ODataQuerySupportsAllParameters() { - var queryString = "foo eq 'bar'"; var query = new ODataQuery(p => p.Foo == "bar") { Expand = "param1", @@ -235,7 +234,7 @@ public void ODataQuerySupportsAllParameters() Skip = 10, Top = 100 }; - Assert.Equal(string.Format("$filter={0}&$orderby=d&$expand=param1&$top=100&$skip=10", Uri.EscapeDataString(queryString)), query.ToString()); + Assert.Equal("$filter=foo eq 'bar'&$orderby=d&$expand=param1&$top=100&$skip=10", query.ToString()); } [Fact] @@ -260,38 +259,34 @@ public void ODataQuerySupportsEmptyState() [Fact] public void ODataQuerySupportsPartialState() { - var queryString = "foo eq 'bar'"; var query = new ODataQuery(p => p.Foo == "bar") { Top = 100 }; - Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); + Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); } [Fact] public void ODataQuerySupportsImplicitConversionFromFilterString() { - var queryString = "foo eq 'bar'"; - ODataQuery query = queryString; + ODataQuery query = "foo eq 'bar'"; query.Top = 100; - Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); + Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); } [Fact] public void ODataQuerySupportsImplicitConversionFromFullFilterString() { - var queryString = "foo eq 'bar'"; - ODataQuery query = string.Format("$filter={0}", queryString); + ODataQuery query = "$filter=foo eq 'bar'"; query.Top = 100; - Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); + Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); } [Fact] public void ODataQuerySupportsImplicitConversionFromQueryString() { - var queryString = "foo eq 'bar'"; - ODataQuery query = string.Format("$filter={0}&$top=100", queryString); - Assert.Equal(string.Format("$filter={0}&$top=100", Uri.EscapeDataString(queryString)), query.ToString()); + ODataQuery query = "$filter=foo eq 'bar'&$top=100"; + Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); } [Fact] diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs index 99fed407ca114..252c7739db668 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/OData/ODataQuery.cs @@ -146,17 +146,17 @@ public override string ToString() if (!string.IsNullOrEmpty(Filter)) { queryStringList.Add(string.Format(CultureInfo.InvariantCulture, - "$filter={0}", Uri.EscapeDataString(Filter))); + "$filter={0}", Filter)); } if (!string.IsNullOrEmpty(OrderBy)) { queryStringList.Add(string.Format(CultureInfo.InvariantCulture, - "$orderby={0}", Uri.EscapeDataString(OrderBy))); + "$orderby={0}", OrderBy)); } if (!string.IsNullOrEmpty(Expand)) { queryStringList.Add(string.Format(CultureInfo.InvariantCulture, - "$expand={0}", Uri.EscapeDataString(Expand))); + "$expand={0}", Expand)); } if (Top != null) { From 72ba2d63344acd09252ba06b58cbf4df82b7c516 Mon Sep 17 00:00:00 2001 From: Hovsep Mkrtchyan Date: Fri, 22 Apr 2016 17:23:18 -0700 Subject: [PATCH 98/99] Added tests to Odata filter generation --- .../ODataTests.cs | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs index c651bbdc33621..7c6829b301d14 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs @@ -7,6 +7,7 @@ using Microsoft.Rest.Azure.OData; using Newtonsoft.Json; using Xunit; +using System.Collections.Generic; namespace Microsoft.Rest.ClientRuntime.Azure.Test { @@ -248,14 +249,43 @@ public void ODataQuerySupportsEmptyState() { Value = null }; + var paramEncoded = new InputParam1 + { + Value = "bar/car" + }; query = new ODataQuery(p => p.Foo == param.Value); Assert.Equal("", query.ToString()); query = new ODataQuery(p => p.Foo == param.Value && p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery(p => p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); + query = new ODataQuery(p => p.AssignedTo(paramEncoded.Value)); + Assert.Equal("$filter=assignedTo('bar%2Fcar')", query.ToString()); + } + + [Fact] + public void ODataQuerySupportsCustomDateTimeOffsetFilter() + { + var param = new Param1 + { + SubmitTime = DateTimeOffset.Parse("2016-03-28T08:15:00.0971693+00:00"), + State = "Ended" + + }; + + var filter = new List(); + filter.Add(string.Format("submitTime lt datetimeoffset'{0}'", Uri.EscapeDataString(param.SubmitTime.Value.ToString("O")))); + var filterString = string.Join(" and ", filter.ToArray()); + + + var query = new ODataQuery + { + Filter = filterString + }; + Assert.Equal("$filter=submitTime lt datetimeoffset'2016-03-28T08%3A15%3A00.0971693%2B00%3A00'' and state ne 'Ended'", query.ToString()); } + [Fact] public void ODataQuerySupportsPartialState() { @@ -266,6 +296,17 @@ public void ODataQuerySupportsPartialState() Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); } + [Fact] + public void ODataQuerySupportsPartialStateWithSlashes() + { + var queryString = "$filter=foo eq 'bar%2Fclub'&$top=100"; + var query = new ODataQuery(p => p.Foo == "bar/club") + { + Top = 100 + }; + Assert.Equal(queryString, query.ToString()); + } + [Fact] public void ODataQuerySupportsImplicitConversionFromFilterString() { @@ -318,7 +359,7 @@ public void ODataQuerySupportsMethod() var filterString = FilterString.Generate(parameters => parameters.AtScope() && parameters.AssignedTo(param.Value)); - Assert.Equal(filterString, "atScope() and assignedTo('Microsoft.Web%2Fsites')"); + Assert.Equal("atScope() and assignedTo('Microsoft.Web%2Fsites')", filterString); } } @@ -356,6 +397,10 @@ public class Param1 [JsonProperty("d")] public DateTime Date { get; set; } public DateTime Date2 { get; set; } + [JsonProperty("submitTime")] + public DateTimeOffset? SubmitTime { get; set; } + [JsonProperty("state")] + public string State { get; set; } [JsonProperty("vals")] public string[] Values { get; set; } [JsonProperty("param2")] From af6fa32b56c6b08589aa558f71dfee6eb9dbb841 Mon Sep 17 00:00:00 2001 From: Hovsep Mkrtchyan Date: Fri, 22 Apr 2016 18:15:07 -0700 Subject: [PATCH 99/99] Fixed the test --- .../Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs index 7c6829b301d14..e267142696404 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs @@ -275,6 +275,7 @@ public void ODataQuerySupportsCustomDateTimeOffsetFilter() var filter = new List(); filter.Add(string.Format("submitTime lt datetimeoffset'{0}'", Uri.EscapeDataString(param.SubmitTime.Value.ToString("O")))); + filter.Add(string.Format("state ne '{0}'", param.State)); var filterString = string.Join(" and ", filter.ToArray()); @@ -282,7 +283,7 @@ public void ODataQuerySupportsCustomDateTimeOffsetFilter() { Filter = filterString }; - Assert.Equal("$filter=submitTime lt datetimeoffset'2016-03-28T08%3A15%3A00.0971693%2B00%3A00'' and state ne 'Ended'", query.ToString()); + Assert.Equal("$filter=submitTime lt datetimeoffset'2016-03-28T08%3A15%3A00.0971693%2B00%3A00' and state ne 'Ended'", query.ToString()); }