com.microsoft.azure.management.resources.ResourceGroupOperationsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.microsoft.azure.management.resources.ResourceGroupOperationsImpl.java

Source

/**
 * 
 * Copyright (c) Microsoft and contributors.  All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * 
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

// Warning: This code was generated by a tool.
// 
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.azure.management.resources;

import com.microsoft.azure.management.resources.models.LongRunningOperationResponse;
import com.microsoft.azure.management.resources.models.ResourceGroup;
import com.microsoft.azure.management.resources.models.ResourceGroupCreateOrUpdateResult;
import com.microsoft.azure.management.resources.models.ResourceGroupExistsResult;
import com.microsoft.azure.management.resources.models.ResourceGroupExtended;
import com.microsoft.azure.management.resources.models.ResourceGroupGetResult;
import com.microsoft.azure.management.resources.models.ResourceGroupListParameters;
import com.microsoft.azure.management.resources.models.ResourceGroupListResult;
import com.microsoft.azure.management.resources.models.ResourceGroupPatchResult;
import com.microsoft.windowsazure.core.LazyCollection;
import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.OperationStatus;
import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete;
import com.microsoft.windowsazure.core.utils.CollectionStringBuilder;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler;
import com.microsoft.windowsazure.tracing.CloudTracing;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.NullNode;
import org.codehaus.jackson.node.ObjectNode;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Pattern;

/**
* Operations for managing resource groups.
*/
public class ResourceGroupOperationsImpl
        implements ServiceOperations<ResourceManagementClientImpl>, ResourceGroupOperations {
    /**
    * Initializes a new instance of the ResourceGroupOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    ResourceGroupOperationsImpl(ResourceManagementClientImpl client) {
        this.client = client;
    }

    private ResourceManagementClientImpl client;

    /**
    * Gets a reference to the
    * microsoft.azure.management.resources.ResourceManagementClientImpl.
    * @return The Client value.
    */
    public ResourceManagementClientImpl getClient() {
        return this.client;
    }

    /**
    * Begin deleting resource group.To determine whether the operation has
    * finished processing the request, call GetLongRunningOperationStatus.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * deleted. The name is case insensitive.
    * @return A standard service response for long running operations.
    */
    @Override
    public Future<LongRunningOperationResponse> beginDeletingAsync(final String resourceGroupName) {
        return this.getClient().getExecutorService().submit(new Callable<LongRunningOperationResponse>() {
            @Override
            public LongRunningOperationResponse call() throws Exception {
                return beginDeleting(resourceGroupName);
            }
        });
    }

    /**
    * Begin deleting resource group.To determine whether the operation has
    * finished processing the request, call GetLongRunningOperationStatus.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * deleted. The name is case insensitive.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response for long running operations.
    */
    @Override
    public LongRunningOperationResponse beginDeleting(String resourceGroupName)
            throws IOException, ServiceException {
        // Validate
        if (resourceGroupName == null) {
            throw new NullPointerException("resourceGroupName");
        }
        if (resourceGroupName != null && resourceGroupName.length() > 1000) {
            throw new IllegalArgumentException("resourceGroupName");
        }
        if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
            throw new IllegalArgumentException("resourceGroupName");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("resourceGroupName", resourceGroupName);
            CloudTracing.enter(invocationId, this, "beginDeletingAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/subscriptions/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/resourcegroups/";
        url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2014-04-01-preview");
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        CustomHttpDelete httpRequest = new CustomHttpDelete(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            LongRunningOperationResponse result = null;
            // Deserialize Response
            result = new LongRunningOperationResponse();
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("Location").length > 0) {
                result.setOperationStatusLink(httpResponse.getFirstHeader("Location").getValue());
            }
            if (httpResponse.getHeaders("Retry-After").length > 0) {
                result.setRetryAfter(
                        DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
            }
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }
            if (statusCode == HttpStatus.SC_CONFLICT) {
                result.setStatus(OperationStatus.Failed);
            }
            if (statusCode == HttpStatus.SC_OK) {
                result.setStatus(OperationStatus.Succeeded);
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Checks whether resource group exists.
    *
    * @param resourceGroupName Required. The name of the resource group to
    * check. The name is case insensitive.
    * @return Resource group information.
    */
    @Override
    public Future<ResourceGroupExistsResult> checkExistenceAsync(final String resourceGroupName) {
        return this.getClient().getExecutorService().submit(new Callable<ResourceGroupExistsResult>() {
            @Override
            public ResourceGroupExistsResult call() throws Exception {
                return checkExistence(resourceGroupName);
            }
        });
    }

    /**
    * Checks whether resource group exists.
    *
    * @param resourceGroupName Required. The name of the resource group to
    * check. The name is case insensitive.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return Resource group information.
    */
    @Override
    public ResourceGroupExistsResult checkExistence(String resourceGroupName) throws IOException, ServiceException {
        // Validate
        if (resourceGroupName == null) {
            throw new NullPointerException("resourceGroupName");
        }
        if (resourceGroupName != null && resourceGroupName.length() > 1000) {
            throw new IllegalArgumentException("resourceGroupName");
        }
        if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
            throw new IllegalArgumentException("resourceGroupName");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("resourceGroupName", resourceGroupName);
            CloudTracing.enter(invocationId, this, "checkExistenceAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "subscriptions/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/resourcegroups/";
        url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2014-04-01-preview");
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpHead httpRequest = new HttpHead(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_NOT_FOUND) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            ResourceGroupExistsResult result = null;
            // Deserialize Response
            result = new ResourceGroupExistsResult();
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }
            if (statusCode == HttpStatus.SC_NO_CONTENT) {
                result.setExists(true);
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Create a resource group.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * created or updated.
    * @param parameters Required. Parameters supplied to the create or update
    * resource group service operation.
    * @return Resource group information.
    */
    @Override
    public Future<ResourceGroupCreateOrUpdateResult> createOrUpdateAsync(final String resourceGroupName,
            final ResourceGroup parameters) {
        return this.getClient().getExecutorService().submit(new Callable<ResourceGroupCreateOrUpdateResult>() {
            @Override
            public ResourceGroupCreateOrUpdateResult call() throws Exception {
                return createOrUpdate(resourceGroupName, parameters);
            }
        });
    }

    /**
    * Create a resource group.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * created or updated.
    * @param parameters Required. Parameters supplied to the create or update
    * resource group service operation.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return Resource group information.
    */
    @Override
    public ResourceGroupCreateOrUpdateResult createOrUpdate(String resourceGroupName, ResourceGroup parameters)
            throws IOException, ServiceException, URISyntaxException {
        // Validate
        if (resourceGroupName == null) {
            throw new NullPointerException("resourceGroupName");
        }
        if (resourceGroupName != null && resourceGroupName.length() > 1000) {
            throw new IllegalArgumentException("resourceGroupName");
        }
        if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
            throw new IllegalArgumentException("resourceGroupName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getLocation() == null) {
            throw new NullPointerException("parameters.Location");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("resourceGroupName", resourceGroupName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "createOrUpdateAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/subscriptions/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/resourcegroups/";
        url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2014-04-01-preview");
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpPut httpRequest = new HttpPut(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Serialize Request
        String requestContent = null;
        JsonNode requestDoc = null;

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode resourceGroupValue = objectMapper.createObjectNode();
        requestDoc = resourceGroupValue;

        ((ObjectNode) resourceGroupValue).put("location", parameters.getLocation());

        if (parameters.getProperties() != null) {
            ((ObjectNode) resourceGroupValue).put("properties", objectMapper.readTree(parameters.getProperties()));
        }

        if (parameters.getTags() != null) {
            if (parameters.getTags() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getTags()).isInitialized()) {
                ObjectNode tagsDictionary = objectMapper.createObjectNode();
                for (Map.Entry<String, String> entry : parameters.getTags().entrySet()) {
                    String tagsKey = entry.getKey();
                    String tagsValue = entry.getValue();
                    ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue);
                }
                ((ObjectNode) resourceGroupValue).put("tags", tagsDictionary);
            }
        }

        if (parameters.getProvisioningState() != null) {
            ((ObjectNode) resourceGroupValue).put("provisioningState", parameters.getProvisioningState());
        }

        StringWriter stringWriter = new StringWriter();
        objectMapper.writeValue(stringWriter, requestDoc);
        requestContent = stringWriter.toString();
        StringEntity entity = new StringEntity(requestContent);
        httpRequest.setEntity(entity);
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
                ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            ResourceGroupCreateOrUpdateResult result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ResourceGroupCreateOrUpdateResult();
                JsonNode responseDoc = null;
                String responseDocContent = IOUtils.toString(responseContent);
                if (responseDocContent == null == false && responseDocContent.length() > 0) {
                    responseDoc = objectMapper.readTree(responseDocContent);
                }

                if (responseDoc != null && responseDoc instanceof NullNode == false) {
                    ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
                    result.setResourceGroup(resourceGroupInstance);

                    JsonNode idValue = responseDoc.get("id");
                    if (idValue != null && idValue instanceof NullNode == false) {
                        String idInstance;
                        idInstance = idValue.getTextValue();
                        resourceGroupInstance.setId(idInstance);
                    }

                    JsonNode nameValue = responseDoc.get("name");
                    if (nameValue != null && nameValue instanceof NullNode == false) {
                        String nameInstance;
                        nameInstance = nameValue.getTextValue();
                        resourceGroupInstance.setName(nameInstance);
                    }

                    JsonNode propertiesValue = responseDoc.get("properties");
                    if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                        JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                        if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                            String provisioningStateInstance;
                            provisioningStateInstance = provisioningStateValue.getTextValue();
                            resourceGroupInstance.setProvisioningState(provisioningStateInstance);
                        }
                    }

                    JsonNode locationValue = responseDoc.get("location");
                    if (locationValue != null && locationValue instanceof NullNode == false) {
                        String locationInstance;
                        locationInstance = locationValue.getTextValue();
                        resourceGroupInstance.setLocation(locationInstance);
                    }

                    JsonNode propertiesValue2 = responseDoc.get("properties");
                    if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                        String propertiesInstance;
                        propertiesInstance = propertiesValue2.getTextValue();
                        resourceGroupInstance.setProperties(propertiesInstance);
                    }

                    JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                    if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                        Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                        while (itr.hasNext()) {
                            Map.Entry<String, JsonNode> property = itr.next();
                            String tagsKey2 = property.getKey();
                            String tagsValue2 = property.getValue().getTextValue();
                            resourceGroupInstance.getTags().put(tagsKey2, tagsValue2);
                        }
                    }

                    JsonNode provisioningStateValue2 = responseDoc.get("provisioningState");
                    if (provisioningStateValue2 != null && provisioningStateValue2 instanceof NullNode == false) {
                        String provisioningStateInstance2;
                        provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                        resourceGroupInstance.setProvisioningState(provisioningStateInstance2);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Delete resource group and all of its resources.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * deleted. The name is case insensitive.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> deleteAsync(final String resourceGroupName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return delete(resourceGroupName);
            }
        });
    }

    /**
    * Delete resource group and all of its resources.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * deleted. The name is case insensitive.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse delete(String resourceGroupName)
            throws InterruptedException, ExecutionException, IOException, ServiceException {
        ResourceManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("resourceGroupName", resourceGroupName);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            LongRunningOperationResponse response = client2.getResourceGroupsOperations()
                    .beginDeletingAsync(resourceGroupName).get();
            LongRunningOperationResponse result = client2
                    .getLongRunningOperationStatusAsync(response.getOperationStatusLink()).get();
            int delayInSeconds = response.getRetryAfter();
            if (delayInSeconds == 0) {
                delayInSeconds = 30;
            }
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(OperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getLongRunningOperationStatusAsync(response.getOperationStatusLink()).get();
                delayInSeconds = result.getRetryAfter();
                if (delayInSeconds == 0) {
                    delayInSeconds = 15;
                }
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * Get a resource group.
    *
    * @param resourceGroupName Required. The name of the resource group to get.
    * The name is case insensitive.
    * @return Resource group information.
    */
    @Override
    public Future<ResourceGroupGetResult> getAsync(final String resourceGroupName) {
        return this.getClient().getExecutorService().submit(new Callable<ResourceGroupGetResult>() {
            @Override
            public ResourceGroupGetResult call() throws Exception {
                return get(resourceGroupName);
            }
        });
    }

    /**
    * Get a resource group.
    *
    * @param resourceGroupName Required. The name of the resource group to get.
    * The name is case insensitive.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return Resource group information.
    */
    @Override
    public ResourceGroupGetResult get(String resourceGroupName)
            throws IOException, ServiceException, URISyntaxException {
        // Validate
        if (resourceGroupName == null) {
            throw new NullPointerException("resourceGroupName");
        }
        if (resourceGroupName != null && resourceGroupName.length() > 1000) {
            throw new IllegalArgumentException("resourceGroupName");
        }
        if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
            throw new IllegalArgumentException("resourceGroupName");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("resourceGroupName", resourceGroupName);
            CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/subscriptions/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/resourcegroups/";
        url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2014-04-01-preview");
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpGet httpRequest = new HttpGet(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            ResourceGroupGetResult result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ResourceGroupGetResult();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode responseDoc = null;
                String responseDocContent = IOUtils.toString(responseContent);
                if (responseDocContent == null == false && responseDocContent.length() > 0) {
                    responseDoc = objectMapper.readTree(responseDocContent);
                }

                if (responseDoc != null && responseDoc instanceof NullNode == false) {
                    ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
                    result.setResourceGroup(resourceGroupInstance);

                    JsonNode idValue = responseDoc.get("id");
                    if (idValue != null && idValue instanceof NullNode == false) {
                        String idInstance;
                        idInstance = idValue.getTextValue();
                        resourceGroupInstance.setId(idInstance);
                    }

                    JsonNode nameValue = responseDoc.get("name");
                    if (nameValue != null && nameValue instanceof NullNode == false) {
                        String nameInstance;
                        nameInstance = nameValue.getTextValue();
                        resourceGroupInstance.setName(nameInstance);
                    }

                    JsonNode propertiesValue = responseDoc.get("properties");
                    if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                        JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                        if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                            String provisioningStateInstance;
                            provisioningStateInstance = provisioningStateValue.getTextValue();
                            resourceGroupInstance.setProvisioningState(provisioningStateInstance);
                        }
                    }

                    JsonNode locationValue = responseDoc.get("location");
                    if (locationValue != null && locationValue instanceof NullNode == false) {
                        String locationInstance;
                        locationInstance = locationValue.getTextValue();
                        resourceGroupInstance.setLocation(locationInstance);
                    }

                    JsonNode propertiesValue2 = responseDoc.get("properties");
                    if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                        String propertiesInstance;
                        propertiesInstance = propertiesValue2.getTextValue();
                        resourceGroupInstance.setProperties(propertiesInstance);
                    }

                    JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                    if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                        Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                        while (itr.hasNext()) {
                            Map.Entry<String, JsonNode> property = itr.next();
                            String tagsKey = property.getKey();
                            String tagsValue = property.getValue().getTextValue();
                            resourceGroupInstance.getTags().put(tagsKey, tagsValue);
                        }
                    }

                    JsonNode provisioningStateValue2 = responseDoc.get("provisioningState");
                    if (provisioningStateValue2 != null && provisioningStateValue2 instanceof NullNode == false) {
                        String provisioningStateInstance2;
                        provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                        resourceGroupInstance.setProvisioningState(provisioningStateInstance2);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Gets a collection of resource groups.
    *
    * @param parameters Optional. Query parameters. If null is passed returns
    * all resource groups.
    * @return List of resource groups.
    */
    @Override
    public Future<ResourceGroupListResult> listAsync(final ResourceGroupListParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<ResourceGroupListResult>() {
            @Override
            public ResourceGroupListResult call() throws Exception {
                return list(parameters);
            }
        });
    }

    /**
    * Gets a collection of resource groups.
    *
    * @param parameters Optional. Query parameters. If null is passed returns
    * all resource groups.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return List of resource groups.
    */
    @Override
    public ResourceGroupListResult list(ResourceGroupListParameters parameters)
            throws IOException, ServiceException, URISyntaxException {
        // Validate

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "listAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/subscriptions/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/resourcegroups";
        ArrayList<String> queryParameters = new ArrayList<String>();
        ArrayList<String> odataFilter = new ArrayList<String>();
        if (parameters != null && parameters.getTagName() != null) {
            odataFilter.add("tagname eq '" + URLEncoder.encode(parameters.getTagName(), "UTF-8") + "'");
        }
        if (parameters != null && parameters.getTagValue() != null) {
            odataFilter.add("tagvalue eq '" + URLEncoder.encode(parameters.getTagValue(), "UTF-8") + "'");
        }
        if (odataFilter.size() > 0) {
            queryParameters.add("$filter=" + CollectionStringBuilder.join(odataFilter, " and "));
        }
        if (parameters != null && parameters.getTop() != null) {
            queryParameters.add("$top=" + URLEncoder.encode(Integer.toString(parameters.getTop()), "UTF-8"));
        }
        queryParameters.add("api-version=" + "2014-04-01-preview");
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpGet httpRequest = new HttpGet(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            ResourceGroupListResult result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ResourceGroupListResult();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode responseDoc = null;
                String responseDocContent = IOUtils.toString(responseContent);
                if (responseDocContent == null == false && responseDocContent.length() > 0) {
                    responseDoc = objectMapper.readTree(responseDocContent);
                }

                if (responseDoc != null && responseDoc instanceof NullNode == false) {
                    JsonNode valueArray = responseDoc.get("value");
                    if (valueArray != null && valueArray instanceof NullNode == false) {
                        for (JsonNode valueValue : ((ArrayNode) valueArray)) {
                            ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
                            result.getResourceGroups().add(resourceGroupJsonFormatInstance);

                            JsonNode idValue = valueValue.get("id");
                            if (idValue != null && idValue instanceof NullNode == false) {
                                String idInstance;
                                idInstance = idValue.getTextValue();
                                resourceGroupJsonFormatInstance.setId(idInstance);
                            }

                            JsonNode nameValue = valueValue.get("name");
                            if (nameValue != null && nameValue instanceof NullNode == false) {
                                String nameInstance;
                                nameInstance = nameValue.getTextValue();
                                resourceGroupJsonFormatInstance.setName(nameInstance);
                            }

                            JsonNode propertiesValue = valueValue.get("properties");
                            if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                                JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                                if (provisioningStateValue != null
                                        && provisioningStateValue instanceof NullNode == false) {
                                    String provisioningStateInstance;
                                    provisioningStateInstance = provisioningStateValue.getTextValue();
                                    resourceGroupJsonFormatInstance.setProvisioningState(provisioningStateInstance);
                                }
                            }

                            JsonNode locationValue = valueValue.get("location");
                            if (locationValue != null && locationValue instanceof NullNode == false) {
                                String locationInstance;
                                locationInstance = locationValue.getTextValue();
                                resourceGroupJsonFormatInstance.setLocation(locationInstance);
                            }

                            JsonNode propertiesValue2 = valueValue.get("properties");
                            if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                                String propertiesInstance;
                                propertiesInstance = propertiesValue2.getTextValue();
                                resourceGroupJsonFormatInstance.setProperties(propertiesInstance);
                            }

                            JsonNode tagsSequenceElement = ((JsonNode) valueValue.get("tags"));
                            if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                                Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                                while (itr.hasNext()) {
                                    Map.Entry<String, JsonNode> property = itr.next();
                                    String tagsKey = property.getKey();
                                    String tagsValue = property.getValue().getTextValue();
                                    resourceGroupJsonFormatInstance.getTags().put(tagsKey, tagsValue);
                                }
                            }

                            JsonNode provisioningStateValue2 = valueValue.get("provisioningState");
                            if (provisioningStateValue2 != null
                                    && provisioningStateValue2 instanceof NullNode == false) {
                                String provisioningStateInstance2;
                                provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                                resourceGroupJsonFormatInstance.setProvisioningState(provisioningStateInstance2);
                            }
                        }
                    }

                    JsonNode nextLinkValue = responseDoc.get("nextLink");
                    if (nextLinkValue != null && nextLinkValue instanceof NullNode == false) {
                        String nextLinkInstance;
                        nextLinkInstance = nextLinkValue.getTextValue();
                        result.setNextLink(nextLinkInstance);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Get a list of deployments.
    *
    * @param nextLink Required. NextLink from the previous successful call to
    * List operation.
    * @return List of resource groups.
    */
    @Override
    public Future<ResourceGroupListResult> listNextAsync(final String nextLink) {
        return this.getClient().getExecutorService().submit(new Callable<ResourceGroupListResult>() {
            @Override
            public ResourceGroupListResult call() throws Exception {
                return listNext(nextLink);
            }
        });
    }

    /**
    * Get a list of deployments.
    *
    * @param nextLink Required. NextLink from the previous successful call to
    * List operation.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return List of resource groups.
    */
    @Override
    public ResourceGroupListResult listNext(String nextLink)
            throws IOException, ServiceException, URISyntaxException {
        // Validate
        if (nextLink == null) {
            throw new NullPointerException("nextLink");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("nextLink", nextLink);
            CloudTracing.enter(invocationId, this, "listNextAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + nextLink;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpGet httpRequest = new HttpGet(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            ResourceGroupListResult result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ResourceGroupListResult();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode responseDoc = null;
                String responseDocContent = IOUtils.toString(responseContent);
                if (responseDocContent == null == false && responseDocContent.length() > 0) {
                    responseDoc = objectMapper.readTree(responseDocContent);
                }

                if (responseDoc != null && responseDoc instanceof NullNode == false) {
                    JsonNode valueArray = responseDoc.get("value");
                    if (valueArray != null && valueArray instanceof NullNode == false) {
                        for (JsonNode valueValue : ((ArrayNode) valueArray)) {
                            ResourceGroupExtended resourceGroupJsonFormatInstance = new ResourceGroupExtended();
                            result.getResourceGroups().add(resourceGroupJsonFormatInstance);

                            JsonNode idValue = valueValue.get("id");
                            if (idValue != null && idValue instanceof NullNode == false) {
                                String idInstance;
                                idInstance = idValue.getTextValue();
                                resourceGroupJsonFormatInstance.setId(idInstance);
                            }

                            JsonNode nameValue = valueValue.get("name");
                            if (nameValue != null && nameValue instanceof NullNode == false) {
                                String nameInstance;
                                nameInstance = nameValue.getTextValue();
                                resourceGroupJsonFormatInstance.setName(nameInstance);
                            }

                            JsonNode propertiesValue = valueValue.get("properties");
                            if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                                JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                                if (provisioningStateValue != null
                                        && provisioningStateValue instanceof NullNode == false) {
                                    String provisioningStateInstance;
                                    provisioningStateInstance = provisioningStateValue.getTextValue();
                                    resourceGroupJsonFormatInstance.setProvisioningState(provisioningStateInstance);
                                }
                            }

                            JsonNode locationValue = valueValue.get("location");
                            if (locationValue != null && locationValue instanceof NullNode == false) {
                                String locationInstance;
                                locationInstance = locationValue.getTextValue();
                                resourceGroupJsonFormatInstance.setLocation(locationInstance);
                            }

                            JsonNode propertiesValue2 = valueValue.get("properties");
                            if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                                String propertiesInstance;
                                propertiesInstance = propertiesValue2.getTextValue();
                                resourceGroupJsonFormatInstance.setProperties(propertiesInstance);
                            }

                            JsonNode tagsSequenceElement = ((JsonNode) valueValue.get("tags"));
                            if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                                Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                                while (itr.hasNext()) {
                                    Map.Entry<String, JsonNode> property = itr.next();
                                    String tagsKey = property.getKey();
                                    String tagsValue = property.getValue().getTextValue();
                                    resourceGroupJsonFormatInstance.getTags().put(tagsKey, tagsValue);
                                }
                            }

                            JsonNode provisioningStateValue2 = valueValue.get("provisioningState");
                            if (provisioningStateValue2 != null
                                    && provisioningStateValue2 instanceof NullNode == false) {
                                String provisioningStateInstance2;
                                provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                                resourceGroupJsonFormatInstance.setProvisioningState(provisioningStateInstance2);
                            }
                        }
                    }

                    JsonNode nextLinkValue = responseDoc.get("nextLink");
                    if (nextLinkValue != null && nextLinkValue instanceof NullNode == false) {
                        String nextLinkInstance;
                        nextLinkInstance = nextLinkValue.getTextValue();
                        result.setNextLink(nextLinkInstance);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Resource groups can be updated through a simple PATCH operation to a
    * group address. The format of the request is the same as that for
    * creating a resource groups, though if a field is unspecified current
    * value will be carried over.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * created or updated. The name is case insensitive.
    * @param parameters Required. Parameters supplied to the update state
    * resource group service operation.
    * @return Resource group information.
    */
    @Override
    public Future<ResourceGroupPatchResult> patchAsync(final String resourceGroupName,
            final ResourceGroup parameters) {
        return this.getClient().getExecutorService().submit(new Callable<ResourceGroupPatchResult>() {
            @Override
            public ResourceGroupPatchResult call() throws Exception {
                return patch(resourceGroupName, parameters);
            }
        });
    }

    /**
    * Resource groups can be updated through a simple PATCH operation to a
    * group address. The format of the request is the same as that for
    * creating a resource groups, though if a field is unspecified current
    * value will be carried over.
    *
    * @param resourceGroupName Required. The name of the resource group to be
    * created or updated. The name is case insensitive.
    * @param parameters Required. Parameters supplied to the update state
    * resource group service operation.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return Resource group information.
    */
    @Override
    public ResourceGroupPatchResult patch(String resourceGroupName, ResourceGroup parameters)
            throws IOException, ServiceException {
        // Validate
        if (resourceGroupName == null) {
            throw new NullPointerException("resourceGroupName");
        }
        if (resourceGroupName != null && resourceGroupName.length() > 1000) {
            throw new IllegalArgumentException("resourceGroupName");
        }
        if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
            throw new IllegalArgumentException("resourceGroupName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getLocation() == null) {
            throw new NullPointerException("parameters.Location");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("resourceGroupName", resourceGroupName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "patchAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/subscriptions/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/resourcegroups/";
        url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2014-04-01-preview");
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpPatch httpRequest = new HttpPatch(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Serialize Request
        String requestContent = null;
        JsonNode requestDoc = null;

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode resourceGroupValue = objectMapper.createObjectNode();
        requestDoc = resourceGroupValue;

        ((ObjectNode) resourceGroupValue).put("location", parameters.getLocation());

        if (parameters.getProperties() != null) {
            ((ObjectNode) resourceGroupValue).put("properties", objectMapper.readTree(parameters.getProperties()));
        }

        if (parameters.getTags() != null) {
            if (parameters.getTags() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getTags()).isInitialized()) {
                ObjectNode tagsDictionary = objectMapper.createObjectNode();
                for (Map.Entry<String, String> entry : parameters.getTags().entrySet()) {
                    String tagsKey = entry.getKey();
                    String tagsValue = entry.getValue();
                    ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue);
                }
                ((ObjectNode) resourceGroupValue).put("tags", tagsDictionary);
            }
        }

        if (parameters.getProvisioningState() != null) {
            ((ObjectNode) resourceGroupValue).put("provisioningState", parameters.getProvisioningState());
        }

        StringWriter stringWriter = new StringWriter();
        objectMapper.writeValue(stringWriter, requestDoc);
        requestContent = stringWriter.toString();
        StringEntity entity = new StringEntity(requestContent);
        httpRequest.setEntity(entity);
        httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            ResourceGroupPatchResult result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ResourceGroupPatchResult();
                JsonNode responseDoc = null;
                String responseDocContent = IOUtils.toString(responseContent);
                if (responseDocContent == null == false && responseDocContent.length() > 0) {
                    responseDoc = objectMapper.readTree(responseDocContent);
                }

                if (responseDoc != null && responseDoc instanceof NullNode == false) {
                    ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
                    result.setResourceGroup(resourceGroupInstance);

                    JsonNode idValue = responseDoc.get("id");
                    if (idValue != null && idValue instanceof NullNode == false) {
                        String idInstance;
                        idInstance = idValue.getTextValue();
                        resourceGroupInstance.setId(idInstance);
                    }

                    JsonNode nameValue = responseDoc.get("name");
                    if (nameValue != null && nameValue instanceof NullNode == false) {
                        String nameInstance;
                        nameInstance = nameValue.getTextValue();
                        resourceGroupInstance.setName(nameInstance);
                    }

                    JsonNode propertiesValue = responseDoc.get("properties");
                    if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                        JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                        if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                            String provisioningStateInstance;
                            provisioningStateInstance = provisioningStateValue.getTextValue();
                            resourceGroupInstance.setProvisioningState(provisioningStateInstance);
                        }
                    }

                    JsonNode locationValue = responseDoc.get("location");
                    if (locationValue != null && locationValue instanceof NullNode == false) {
                        String locationInstance;
                        locationInstance = locationValue.getTextValue();
                        resourceGroupInstance.setLocation(locationInstance);
                    }

                    JsonNode propertiesValue2 = responseDoc.get("properties");
                    if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                        String propertiesInstance;
                        propertiesInstance = propertiesValue2.getTextValue();
                        resourceGroupInstance.setProperties(propertiesInstance);
                    }

                    JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                    if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                        Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                        while (itr.hasNext()) {
                            Map.Entry<String, JsonNode> property = itr.next();
                            String tagsKey2 = property.getKey();
                            String tagsValue2 = property.getValue().getTextValue();
                            resourceGroupInstance.getTags().put(tagsKey2, tagsValue2);
                        }
                    }

                    JsonNode provisioningStateValue2 = responseDoc.get("provisioningState");
                    if (provisioningStateValue2 != null && provisioningStateValue2 instanceof NullNode == false) {
                        String provisioningStateInstance2;
                        provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                        resourceGroupInstance.setProvisioningState(provisioningStateInstance2);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }
}