com.microsoft.windowsazure.management.compute.ServiceCertificateOperationsImpl.java Source code

Java tutorial

Introduction

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

import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.OperationStatus;
import com.microsoft.windowsazure.core.OperationStatusResponse;
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.Base64;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.CloudError;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.compute.models.ServiceCertificateCreateParameters;
import com.microsoft.windowsazure.management.compute.models.ServiceCertificateDeleteParameters;
import com.microsoft.windowsazure.management.compute.models.ServiceCertificateGetParameters;
import com.microsoft.windowsazure.management.compute.models.ServiceCertificateGetResponse;
import com.microsoft.windowsazure.management.compute.models.ServiceCertificateListResponse;
import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler;
import com.microsoft.windowsazure.tracing.CloudTracing;
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.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.ExecutionException;
import java.util.concurrent.Future;

/**
* Operations for managing service certificates for your subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for more
* information)
*/
public class ServiceCertificateOperationsImpl
        implements ServiceOperations<ComputeManagementClientImpl>, ServiceCertificateOperations {
    /**
    * Initializes a new instance of the ServiceCertificateOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    ServiceCertificateOperationsImpl(ComputeManagementClientImpl client) {
        this.client = client;
    }

    private ComputeManagementClientImpl client;

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

    /**
    * The Begin Creating Service Certificate operation adds a certificate to a
    * hosted service. This operation is an asynchronous operation. To
    * determine whether the management service has finished processing the
    * request, call Get Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for
    * more information)
    *
    * @param serviceName Required. The DNS prefix name of your service.
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Service Certificate operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginCreatingAsync(final String serviceName,
            final ServiceCertificateCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginCreating(serviceName, parameters);
            }
        });
    }

    /**
    * The Begin Creating Service Certificate operation adds a certificate to a
    * hosted service. This operation is an asynchronous operation. To
    * determine whether the management service has finished processing the
    * request, call Get Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for
    * more information)
    *
    * @param serviceName Required. The DNS prefix name of your service.
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Service Certificate 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginCreating(String serviceName, ServiceCertificateCreateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        // TODO: Validate serviceName is a valid DNS name.
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getCertificateFormat() == null) {
            throw new NullPointerException("parameters.CertificateFormat");
        }
        if (parameters.getData() == null) {
            throw new NullPointerException("parameters.Data");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginCreatingAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/certificates";
        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", "2015-04-01");

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

        Element certificateFileElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "CertificateFile");
        requestDoc.appendChild(certificateFileElement);

        Element dataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Data");
        dataElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData())));
        certificateFileElement.appendChild(dataElement);

        Element certificateFormatElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "CertificateFormat");
        certificateFormatElement.appendChild(requestDoc.createTextNode(
                ComputeManagementClientImpl.certificateFormatToString(parameters.getCertificateFormat())));
        certificateFileElement.appendChild(certificateFormatElement);

        if (parameters.getPassword() != null) {
            Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Password");
            passwordElement.appendChild(requestDoc.createTextNode(parameters.getPassword()));
            certificateFileElement.appendChild(passwordElement);
        }

        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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, 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 Begin Deleting Service Certificate operation deletes a service
    * certificate from the certificate store of a hosted service. This
    * operation is an asynchronous operation. To determine whether the
    * management service has finished processing the request, call Get
    * Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Begin Deleting
    * Service Certificate operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginDeletingAsync(final ServiceCertificateDeleteParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginDeleting(parameters);
            }
        });
    }

    /**
    * The Begin Deleting Service Certificate operation deletes a service
    * certificate from the certificate store of a hosted service. This
    * operation is an asynchronous operation. To determine whether the
    * management service has finished processing the request, call Get
    * Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Begin Deleting
    * Service Certificate 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginDeleting(ServiceCertificateDeleteParameters parameters)
            throws IOException, ServiceException {
        // Validate
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getServiceName() == null) {
            throw new NullPointerException("parameters.ServiceName");
        }
        // TODO: Validate parameters.ServiceName is a valid DNS name.
        if (parameters.getThumbprint() == null) {
            throw new NullPointerException("parameters.Thumbprint");
        }
        if (parameters.getThumbprintAlgorithm() == null) {
            throw new NullPointerException("parameters.ThumbprintAlgorithm");
        }

        // 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, "beginDeletingAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(parameters.getServiceName(), "UTF-8");
        url = url + "/certificates/";
        url = url + URLEncoder.encode(parameters.getThumbprintAlgorithm(), "UTF-8");
        url = url + "-";
        url = url + URLEncoder.encode(parameters.getThumbprint(), "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", "2015-04-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_ACCEPTED) {
                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 Create Service Certificate operation adds a certificate to a hosted
    * service. This operation is an asynchronous operation. To determine
    * whether the management service has finished processing the request, call
    * Get Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for
    * more information)
    *
    * @param serviceName Required. The DNS prefix name of your service.
    * @param parameters Required. Parameters supplied to the Create Service
    * Certificate operation.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request. If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request and error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> createAsync(final String serviceName,
            final ServiceCertificateCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return create(serviceName, parameters);
            }
        });
    }

    /**
    * The Create Service Certificate operation adds a certificate to a hosted
    * service. This operation is an asynchronous operation. To determine
    * whether the management service has finished processing the request, call
    * Get Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for
    * more information)
    *
    * @param serviceName Required. The DNS prefix name of your service.
    * @param parameters Required. Parameters supplied to the Create Service
    * Certificate operation.
    * @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 ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @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 ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request. If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request and error information regarding the failure.
    */
    @Override
    public OperationStatusResponse create(String serviceName, ServiceCertificateCreateParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException,
            ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getServiceCertificatesOperations()
                    .beginCreatingAsync(serviceName, parameters).get();
            OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(OperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

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

            if (result.getStatus() != OperationStatus.Succeeded) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

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

    /**
    * The Delete Service Certificate operation deletes a service certificate
    * from the certificate store of a hosted service. This operation is an
    * asynchronous operation. To determine whether the management service has
    * finished processing the request, call Get Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Delete Service
    * Certificate operation.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request. If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request and error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> deleteAsync(final ServiceCertificateDeleteParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return delete(parameters);
            }
        });
    }

    /**
    * The Delete Service Certificate operation deletes a service certificate
    * from the certificate store of a hosted service. This operation is an
    * asynchronous operation. To determine whether the management service has
    * finished processing the request, call Get Operation Status.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Delete Service
    * Certificate 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 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 ServiceException Thrown if the server returned an error for the
    * request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request. If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request and error information regarding the failure.
    */
    @Override
    public OperationStatusResponse delete(ServiceCertificateDeleteParameters parameters)
            throws IOException, ServiceException, InterruptedException, ExecutionException {
        ComputeManagementClient 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("parameters", parameters);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getServiceCertificatesOperations().beginDeletingAsync(parameters)
                    .get();
            OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(OperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

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

            if (result.getStatus() != OperationStatus.Succeeded) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

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

    /**
    * The Get Service Certificate operation returns the public data for the
    * specified X.509 certificate associated with a hosted service.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Get Service
    * Certificate operation.
    * @return The Get Service Certificate operation response.
    */
    @Override
    public Future<ServiceCertificateGetResponse> getAsync(final ServiceCertificateGetParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<ServiceCertificateGetResponse>() {
            @Override
            public ServiceCertificateGetResponse call() throws Exception {
                return get(parameters);
            }
        });
    }

    /**
    * The Get Service Certificate operation returns the public data for the
    * specified X.509 certificate associated with a hosted service.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Get Service
    * Certificate 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 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 Get Service Certificate operation response.
    */
    @Override
    public ServiceCertificateGetResponse get(ServiceCertificateGetParameters parameters)
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getServiceName() == null) {
            throw new NullPointerException("parameters.ServiceName");
        }
        // TODO: Validate parameters.ServiceName is a valid DNS name.
        if (parameters.getThumbprint() == null) {
            throw new NullPointerException("parameters.Thumbprint");
        }
        if (parameters.getThumbprintAlgorithm() == null) {
            throw new NullPointerException("parameters.ThumbprintAlgorithm");
        }

        // 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, "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/hostedservices/";
        url = url + URLEncoder.encode(parameters.getServiceName(), "UTF-8");
        url = url + "/certificates/";
        url = url + URLEncoder.encode(parameters.getThumbprintAlgorithm(), "UTF-8");
        url = url + "-";
        url = url + URLEncoder.encode(parameters.getThumbprint(), "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", "2015-04-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
            ServiceCertificateGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ServiceCertificateGetResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element certificateElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "Certificate");
                if (certificateElement != null) {
                    Element dataElement = XmlUtility.getElementByTagNameNS(certificateElement,
                            "http://schemas.microsoft.com/windowsazure", "Data");
                    if (dataElement != null) {
                        byte[] dataInstance;
                        dataInstance = dataElement.getTextContent() != null
                                ? Base64.decode(dataElement.getTextContent())
                                : null;
                        result.setData(dataInstance);
                    }
                }

            }
            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 Service Certificates operation lists all of the service
    * certificates associated with the specified hosted service.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for
    * more information)
    *
    * @param serviceName Required. The DNS prefix name of your hosted service.
    * @return The List Service Certificates operation response.
    */
    @Override
    public Future<ServiceCertificateListResponse> listAsync(final String serviceName) {
        return this.getClient().getExecutorService().submit(new Callable<ServiceCertificateListResponse>() {
            @Override
            public ServiceCertificateListResponse call() throws Exception {
                return list(serviceName);
            }
        });
    }

    /**
    * The List Service Certificates operation lists all of the service
    * certificates associated with the specified hosted service.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for
    * more information)
    *
    * @param serviceName Required. The DNS prefix name of your hosted service.
    * @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 Service Certificates operation response.
    */
    @Override
    public ServiceCertificateListResponse list(String serviceName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        // TODO: Validate serviceName is a valid DNS name.

        // 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("serviceName", serviceName);
            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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/certificates";
        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", "2015-04-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
            ServiceCertificateListResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ServiceCertificateListResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element certificatesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "Certificates");
                if (certificatesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(certificatesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "Certificate")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element certificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(certificatesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Certificate")
                                .get(i1));
                        ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate();
                        result.getCertificates().add(certificateInstance);

                        Element certificateUrlElement = XmlUtility.getElementByTagNameNS(certificatesElement,
                                "http://schemas.microsoft.com/windowsazure", "CertificateUrl");
                        if (certificateUrlElement != null) {
                            URI certificateUrlInstance;
                            certificateUrlInstance = new URI(certificateUrlElement.getTextContent());
                            certificateInstance.setCertificateUri(certificateUrlInstance);
                        }

                        Element thumbprintElement = XmlUtility.getElementByTagNameNS(certificatesElement,
                                "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                        if (thumbprintElement != null) {
                            String thumbprintInstance;
                            thumbprintInstance = thumbprintElement.getTextContent();
                            certificateInstance.setThumbprint(thumbprintInstance);
                        }

                        Element thumbprintAlgorithmElement = XmlUtility.getElementByTagNameNS(certificatesElement,
                                "http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm");
                        if (thumbprintAlgorithmElement != null) {
                            String thumbprintAlgorithmInstance;
                            thumbprintAlgorithmInstance = thumbprintAlgorithmElement.getTextContent();
                            certificateInstance.setThumbprintAlgorithm(thumbprintAlgorithmInstance);
                        }

                        Element dataElement = XmlUtility.getElementByTagNameNS(certificatesElement,
                                "http://schemas.microsoft.com/windowsazure", "Data");
                        if (dataElement != null) {
                            byte[] dataInstance;
                            dataInstance = dataElement.getTextContent() != null
                                    ? Base64.decode(dataElement.getTextContent())
                                    : null;
                            certificateInstance.setData(dataInstance);
                        }
                    }
                }

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