com.microsoft.windowsazure.management.mediaservices.AccountOperationsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.microsoft.windowsazure.management.mediaservices.AccountOperationsImpl.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.windowsazure.management.mediaservices;

import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete;
import com.microsoft.windowsazure.core.utils.BOMInputStream;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.mediaservices.models.MediaServicesAccount;
import com.microsoft.windowsazure.management.mediaservices.models.MediaServicesAccountCreateParameters;
import com.microsoft.windowsazure.management.mediaservices.models.MediaServicesAccountCreateResponse;
import com.microsoft.windowsazure.management.mediaservices.models.MediaServicesAccountGetResponse;
import com.microsoft.windowsazure.management.mediaservices.models.MediaServicesAccountListResponse;
import com.microsoft.windowsazure.management.mediaservices.models.MediaServicesCreatedAccount;
import com.microsoft.windowsazure.management.mediaservices.models.MediaServicesKeyType;
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.HttpPost;
import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.NullNode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

public class AccountOperationsImpl
        implements ServiceOperations<MediaServicesManagementClientImpl>, AccountOperations {
    /**
    * Initializes a new instance of the AccountOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    AccountOperationsImpl(MediaServicesManagementClientImpl client) {
        this.client = client;
    }

    private MediaServicesManagementClientImpl client;

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

    /**
    * The Create Media Services Account operation creates a new media services
    * account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Create Media
    * Services Account operation.
    * @return The Create Media Services Account operation response.
    */
    @Override
    public Future<MediaServicesAccountCreateResponse> createAsync(
            final MediaServicesAccountCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<MediaServicesAccountCreateResponse>() {
            @Override
            public MediaServicesAccountCreateResponse call() throws Exception {
                return create(parameters);
            }
        });
    }

    /**
    * The Create Media Services Account operation creates a new media services
    * account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Create Media
    * Services Account operation.
    * @throws ParserConfigurationException Thrown if there was an error
    * configuring the parser for the response body.
    * @throws SAXException Thrown if there was an error parsing the response
    * body.
    * @throws TransformerException Thrown if there was an error creating the
    * DOM transformer.
    * @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 The Create Media Services Account operation response.
    */
    @Override
    public MediaServicesAccountCreateResponse create(MediaServicesAccountCreateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getAccountName() == null) {
            throw new NullPointerException("parameters.AccountName");
        }
        if (parameters.getAccountName().length() < 3) {
            throw new IllegalArgumentException("parameters.AccountName");
        }
        if (parameters.getAccountName().length() > 24) {
            throw new IllegalArgumentException("parameters.AccountName");
        }
        if (parameters.getBlobStorageEndpointUri() == null) {
            throw new NullPointerException("parameters.BlobStorageEndpointUri");
        }
        if (parameters.getRegion() == null) {
            throw new NullPointerException("parameters.Region");
        }
        if (parameters.getRegion().length() < 3) {
            throw new IllegalArgumentException("parameters.Region");
        }
        if (parameters.getRegion().length() > 256) {
            throw new IllegalArgumentException("parameters.Region");
        }
        if (parameters.getStorageAccountKey() == null) {
            throw new NullPointerException("parameters.StorageAccountKey");
        }
        if (parameters.getStorageAccountKey().length() < 14) {
            throw new IllegalArgumentException("parameters.StorageAccountKey");
        }
        if (parameters.getStorageAccountKey().length() > 256) {
            throw new IllegalArgumentException("parameters.StorageAccountKey");
        }
        if (parameters.getStorageAccountName() == null) {
            throw new NullPointerException("parameters.StorageAccountName");
        }
        if (parameters.getStorageAccountName().length() < 3) {
            throw new IllegalArgumentException("parameters.StorageAccountName");
        }
        if (parameters.getStorageAccountName().length() > 24) {
            throw new IllegalArgumentException("parameters.StorageAccountName");
        }
        for (char storageAccountNameChar : parameters.getStorageAccountName().toCharArray()) {
            if (Character.isLowerCase(storageAccountNameChar) == false
                    && Character.isDigit(storageAccountNameChar) == false) {
                throw new IllegalArgumentException("parameters.StorageAccountName");
            }
        }

        // 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, "createAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/mediaservices/Accounts";
        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
        HttpPost httpRequest = new HttpPost(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/xml");
        httpRequest.setHeader("x-ms-version", "2011-10-01");

        // Serialize Request
        String requestContent = null;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document requestDoc = documentBuilder.newDocument();

        Element accountCreationRequestElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
                "AccountCreationRequest");
        requestDoc.appendChild(accountCreationRequestElement);

        Element accountNameElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
                "AccountName");
        accountNameElement.appendChild(requestDoc.createTextNode(parameters.getAccountName()));
        accountCreationRequestElement.appendChild(accountNameElement);

        Element blobStorageEndpointUriElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
                "BlobStorageEndpointUri");
        blobStorageEndpointUriElement
                .appendChild(requestDoc.createTextNode(parameters.getBlobStorageEndpointUri().toString()));
        accountCreationRequestElement.appendChild(blobStorageEndpointUriElement);

        Element regionElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
                "Region");
        regionElement.appendChild(requestDoc.createTextNode(parameters.getRegion()));
        accountCreationRequestElement.appendChild(regionElement);

        Element storageAccountKeyElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
                "StorageAccountKey");
        storageAccountKeyElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountKey()));
        accountCreationRequestElement.appendChild(storageAccountKeyElement);

        Element storageAccountNameElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models",
                "StorageAccountName");
        storageAccountNameElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountName()));
        accountCreationRequestElement.appendChild(storageAccountNameElement);

        DOMSource domSource = new DOMSource(requestDoc);
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(domSource, streamResult);
        requestContent = stringWriter.toString();
        StringEntity entity = new StringEntity(requestContent);
        httpRequest.setEntity(entity);
        httpRequest.setHeader("Content-Type", "application/xml");

        // 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_CREATED) {
                ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            MediaServicesAccountCreateResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_CREATED) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new MediaServicesAccountCreateResponse();
                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) {
                    MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount();
                    result.setAccount(accountInstance);

                    JsonNode accountIdValue = responseDoc.get("AccountId");
                    if (accountIdValue != null && accountIdValue instanceof NullNode == false) {
                        String accountIdInstance;
                        accountIdInstance = accountIdValue.getTextValue();
                        accountInstance.setAccountId(accountIdInstance);
                    }

                    JsonNode accountNameValue = responseDoc.get("AccountName");
                    if (accountNameValue != null && accountNameValue instanceof NullNode == false) {
                        String accountNameInstance;
                        accountNameInstance = accountNameValue.getTextValue();
                        accountInstance.setAccountName(accountNameInstance);
                    }

                    JsonNode subscriptionValue = responseDoc.get("Subscription");
                    if (subscriptionValue != null && subscriptionValue instanceof NullNode == false) {
                        String subscriptionInstance;
                        subscriptionInstance = subscriptionValue.getTextValue();
                        accountInstance.setSubscriptionId(subscriptionInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Delete Media Services Account operation deletes an existing media
    * services account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn194273.aspx for
    * more information)
    *
    * @param accountName Required. The name of the media services account.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> deleteAsync(final String accountName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return delete(accountName);
            }
        });
    }

    /**
    * The Delete Media Services Account operation deletes an existing media
    * services account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn194273.aspx for
    * more information)
    *
    * @param accountName Required. The name of the media services account.
    * @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 including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse delete(String accountName) throws IOException, ServiceException {
        // Validate
        if (accountName == null) {
            throw new NullPointerException("accountName");
        }

        // 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("accountName", accountName);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/mediaservices/Accounts/";
        url = url + URLEncoder.encode(accountName, "UTF-8");
        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("x-ms-version", "2011-10-01");

        // 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) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            OperationResponse result = null;
            // Deserialize Response
            result = new OperationResponse();
            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();
            }
        }
    }

    /**
    * The Get Media Services Account operation gets detailed information about
    * a media services account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166974.aspx for
    * more information)
    *
    * @param accountName Required. The name of the Media Services account.
    * @return The Get Media Services Account operation response.
    */
    @Override
    public Future<MediaServicesAccountGetResponse> getAsync(final String accountName) {
        return this.getClient().getExecutorService().submit(new Callable<MediaServicesAccountGetResponse>() {
            @Override
            public MediaServicesAccountGetResponse call() throws Exception {
                return get(accountName);
            }
        });
    }

    /**
    * The Get Media Services Account operation gets detailed information about
    * a media services account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166974.aspx for
    * more information)
    *
    * @param accountName Required. The name of the Media Services account.
    * @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 The Get Media Services Account operation response.
    */
    @Override
    public MediaServicesAccountGetResponse get(String accountName) throws IOException, ServiceException {
        // Validate
        if (accountName == null) {
            throw new NullPointerException("accountName");
        }

        // 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("accountName", accountName);
            CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/mediaservices/Accounts/";
        url = url + URLEncoder.encode(accountName, "UTF-8");
        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("x-ms-version", "2011-10-01");

        // 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
            MediaServicesAccountGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new MediaServicesAccountGetResponse();
                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) {
                    MediaServicesAccount accountInstance = new MediaServicesAccount();
                    result.setAccount(accountInstance);

                    JsonNode accountNameValue = responseDoc.get("AccountName");
                    if (accountNameValue != null && accountNameValue instanceof NullNode == false) {
                        String accountNameInstance;
                        accountNameInstance = accountNameValue.getTextValue();
                        accountInstance.setAccountName(accountNameInstance);
                    }

                    JsonNode accountKeyValue = responseDoc.get("AccountKey");
                    if (accountKeyValue != null && accountKeyValue instanceof NullNode == false) {
                        String accountKeyInstance;
                        accountKeyInstance = accountKeyValue.getTextValue();
                        accountInstance.setAccountKey(accountKeyInstance);
                    }

                    JsonNode accountKeysValue = responseDoc.get("AccountKeys");
                    if (accountKeysValue != null && accountKeysValue instanceof NullNode == false) {
                        MediaServicesAccount.AccountKeys accountKeysInstance = new MediaServicesAccount.AccountKeys();
                        accountInstance.setStorageAccountKeys(accountKeysInstance);

                        JsonNode primaryValue = accountKeysValue.get("Primary");
                        if (primaryValue != null && primaryValue instanceof NullNode == false) {
                            String primaryInstance;
                            primaryInstance = primaryValue.getTextValue();
                            accountKeysInstance.setPrimary(primaryInstance);
                        }

                        JsonNode secondaryValue = accountKeysValue.get("Secondary");
                        if (secondaryValue != null && secondaryValue instanceof NullNode == false) {
                            String secondaryInstance;
                            secondaryInstance = secondaryValue.getTextValue();
                            accountKeysInstance.setSecondary(secondaryInstance);
                        }
                    }

                    JsonNode accountRegionValue = responseDoc.get("AccountRegion");
                    if (accountRegionValue != null && accountRegionValue instanceof NullNode == false) {
                        String accountRegionInstance;
                        accountRegionInstance = accountRegionValue.getTextValue();
                        accountInstance.setAccountRegion(accountRegionInstance);
                    }

                    JsonNode storageAccountNameValue = responseDoc.get("StorageAccountName");
                    if (storageAccountNameValue != null && storageAccountNameValue instanceof NullNode == false) {
                        String storageAccountNameInstance;
                        storageAccountNameInstance = storageAccountNameValue.getTextValue();
                        accountInstance.setStorageAccountName(storageAccountNameInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The List Media Services Account operation gets information about all
    * existing media services accounts associated with the current
    * subscription in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166989.aspx for
    * more information)
    *
    * @return The List Media Accounts operation response.
    */
    @Override
    public Future<MediaServicesAccountListResponse> listAsync() {
        return this.getClient().getExecutorService().submit(new Callable<MediaServicesAccountListResponse>() {
            @Override
            public MediaServicesAccountListResponse call() throws Exception {
                return list();
            }
        });
    }

    /**
    * The List Media Services Account operation gets information about all
    * existing media services accounts associated with the current
    * subscription in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166989.aspx for
    * more information)
    *
    * @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 ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The List Media Accounts operation response.
    */
    @Override
    public MediaServicesAccountListResponse list()
            throws IOException, ServiceException, ParserConfigurationException, SAXException, 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>();
            CloudTracing.enter(invocationId, this, "listAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/mediaservices/Accounts";
        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("x-ms-version", "2011-10-01");

        // 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.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            MediaServicesAccountListResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new MediaServicesAccountListResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ServiceResources");
                if (serviceResourcesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                                .get(i1));
                        MediaServicesAccountListResponse.MediaServiceAccount serviceResourceInstance = new MediaServicesAccountListResponse.MediaServiceAccount();
                        result.getAccounts().add(serviceResourceInstance);

                        Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                                "http://schemas.microsoft.com/windowsazure", "Name");
                        if (nameElement != null) {
                            String nameInstance;
                            nameInstance = nameElement.getTextContent();
                            serviceResourceInstance.setName(nameInstance);
                        }

                        Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                                "http://schemas.microsoft.com/windowsazure", "Type");
                        if (typeElement != null) {
                            String typeInstance;
                            typeInstance = typeElement.getTextContent();
                            serviceResourceInstance.setType(typeInstance);
                        }

                        Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                                "http://schemas.microsoft.com/windowsazure", "State");
                        if (stateElement != null) {
                            String stateInstance;
                            stateInstance = stateElement.getTextContent();
                            serviceResourceInstance.setState(stateInstance);
                        }

                        Element selfLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                                "http://schemas.microsoft.com/windowsazure", "SelfLink");
                        if (selfLinkElement != null) {
                            URI selfLinkInstance;
                            selfLinkInstance = new URI(selfLinkElement.getTextContent());
                            serviceResourceInstance.setUri(selfLinkInstance);
                        }

                        Element parentLinkElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                                "http://schemas.microsoft.com/windowsazure", "ParentLink");
                        if (parentLinkElement != null) {
                            URI parentLinkInstance;
                            parentLinkInstance = new URI(parentLinkElement.getTextContent());
                            serviceResourceInstance.setParentUri(parentLinkInstance);
                        }

                        Element accountIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                                "http://schemas.microsoft.com/windowsazure", "AccountId");
                        if (accountIdElement != null) {
                            String accountIdInstance;
                            accountIdInstance = accountIdElement.getTextContent();
                            serviceResourceInstance.setAccountId(accountIdInstance);
                        }
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Regenerate Media Services Account Key operation regenerates an
    * account key for the given Media Services account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn167010.aspx for
    * more information)
    *
    * @param accountName Required. The name of the Media Services Account.
    * @param keyType Required. The type of key to regenerate (primary or
    * secondary)
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> regenerateKeyAsync(final String accountName,
            final MediaServicesKeyType keyType) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return regenerateKey(accountName, keyType);
            }
        });
    }

    /**
    * The Regenerate Media Services Account Key operation regenerates an
    * account key for the given Media Services account in Windows Azure.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn167010.aspx for
    * more information)
    *
    * @param accountName Required. The name of the Media Services Account.
    * @param keyType Required. The type of key to regenerate (primary or
    * secondary)
    * @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 including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse regenerateKey(String accountName, MediaServicesKeyType keyType)
            throws IOException, ServiceException {
        // Validate
        if (accountName == null) {
            throw new NullPointerException("accountName");
        }
        if (keyType == null) {
            throw new NullPointerException("keyType");
        }

        // 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("accountName", accountName);
            tracingParameters.put("keyType", keyType);
            CloudTracing.enter(invocationId, this, "regenerateKeyAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/mediaservices/Accounts/";
        url = url + URLEncoder.encode(accountName, "UTF-8");
        url = url + "/AccountKeys/";
        url = url + URLEncoder.encode(keyType.toString(), "UTF-8");
        url = url + "/Regenerate";
        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
        HttpPost httpRequest = new HttpPost(url);

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2011-10-01");

        // 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) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            OperationResponse result = null;
            // Deserialize Response
            result = new OperationResponse();
            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();
            }
        }
    }
}