Example usage for org.w3c.dom Document createElementNS

List of usage examples for org.w3c.dom Document createElementNS

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Walking Upgrade Domain By Deployment Slot operation specifies
* an update domain in which a role instance must be updated. For more
* information about updating role instances, see Update an Azure Service
* at http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx.
* This operation is an asynchronous operation. To determine whether the
* Management service has finished processing the request, call Get
* Operation Status. For more information on asynchronous operations, see
* Tracking Asynchronous Service Management Requests at
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
* Prior to calling the Walk Upgrade Domain operation you must have called
* Upgrade Deployment, Change Deployment Configuration, or Rollback Update
* Or Upgrade. By default, a service is deployed with five update domains,
* which are updated one at a time during an in-place update. For
* information on modifying the number of update domains in the service
* definition file, see the Azure Service Definition Schema (.csdef File).
* To perform a manual update of your deployment, proceed in this order:
* Call Upgrade Deployment with the Mode element set to manual. Call Walk
* Upgrade Domain to update each domain within the deployment. Update
* domains must be updated in order. For example, begin with domain 0,
* proceed to domain 1, and so on. Important: An update that adds or
* removes role instances will result in a configuration update to all
* roles that are deployed in the cloud service. Existing role instances
* need to be notified of new role instances so that all role instances can
* communicate together in the cloud service. While an update is in
* progress, call Get Deployment to determine its status. If the update is
* in progress, Get Deployment returns an UpgradeStatus element that
* contains information about the update. If the update is complete, or if
* no update is in progress, then the UpgradeStatus element is null.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460800.aspx for
* more information)//from   w w  w  .  j a va2s.  c om
*
* @param serviceName Required. The name of the cloud service.
* @param deploymentSlot Required. The deployment slot.
* @param parameters Required. Parameters supplied to the Begin Walking
* Upgrade Domain By Deployment Slot 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 beginWalkingUpgradeDomainByDeploymentSlot(String serviceName,
        DeploymentSlot deploymentSlot, DeploymentWalkUpgradeDomainParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentSlot == null) {
        throw new NullPointerException("deploymentSlot");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("deploymentSlot", deploymentSlot);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginWalkingUpgradeDomainByDeploymentSlotAsync",
                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 + "/deploymentslots/";
    url = url + URLEncoder.encode(deploymentSlot.toString(), "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=walkupgradedomain");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 walkUpgradeDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "WalkUpgradeDomain");
    requestDoc.appendChild(walkUpgradeDomainElement);

    Element upgradeDomainElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "UpgradeDomain");
    upgradeDomainElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getUpgradeDomain())));
    walkUpgradeDomainElement.appendChild(upgradeDomainElement);

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Updating Deployment Status By Deployment Name operation
* initiates a change in the running status of a deployment. The status of
* a deployment can be running or suspended. This operation is an
* asynchronous operation. To determine whether the Management service has
* finished processing the request, call Get Operation Status. For more
* information on asynchronous operations, see Tracking Asynchronous
* Service Management Requests at/*from   ww w.  j a  va2 s.c  o m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx
* for more information)
*
* @param serviceName Required. The cloud service to swap deployments for.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Begin Updating
* Deployment Status By Deployment Name 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 beginUpdatingStatusByDeploymentName(String serviceName, String deploymentName,
        DeploymentUpdateStatusParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getStatus() == null) {
        throw new NullPointerException("parameters.Status");
    }

    // 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("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingStatusByDeploymentNameAsync", 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 + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=status");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 updateDeploymentStatusElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateDeploymentStatus");
    requestDoc.appendChild(updateDeploymentStatusElement);

    Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Status");
    statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
    updateDeploymentStatusElement.appendChild(statusElement);

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Updating Deployment Status By Deployment Slot operation
* initiates a change in the running status of a deployment. The status of
* a deployment can be running or suspended. This operation is an
* asynchronous operation. To determine whether the Management service has
* finished processing the request, call Get Operation Status. For more
* information on asynchronous operations, see Tracking Asynchronous
* Service Management Requests at/*from w  w w.  ja  v a 2s  .  co  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460808.aspx
* for more information)
*
* @param serviceName Required. The cloud service to swap deployments for.
* @param deploymentSlot Required. The deployment slot.
* @param parameters Required. Parameters supplied to the Begin Updating
* Deployment Status By Deployment Slot 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 beginUpdatingStatusByDeploymentSlot(String serviceName, DeploymentSlot deploymentSlot,
        DeploymentUpdateStatusParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentSlot == null) {
        throw new NullPointerException("deploymentSlot");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getStatus() == null) {
        throw new NullPointerException("parameters.Status");
    }

    // 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("deploymentSlot", deploymentSlot);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingStatusByDeploymentSlotAsync", 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 + "/deploymentslots/";
    url = url + URLEncoder.encode(deploymentSlot.toString(), "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=status");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 updateDeploymentStatusElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateDeploymentStatus");
    requestDoc.appendChild(updateDeploymentStatusElement);

    Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Status");
    statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
    updateDeploymentStatusElement.appendChild(statusElement);

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Rollback Update Or Upgrade By Deployment Name operation cancels an
* in-progress configuration update and returns the deployment to its state
* before the update was started. This operation can only be called when an
* update is in progress on the deployment. The deployment status can be
* detected by calling the Get Deployment operation or Get Hosted Service
* Properties operation and inspecting the RollbackAllowed element. If the
* value returned is true a rollback can be performed.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for
* more information)/*from  ww w. ja  va2s .  c  o  m*/
*
* @param serviceName Required. The cloud service to swap deployments for.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters supplied to the Rollback Update Or
* Upgrade By Deployment Name 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 rollbackUpdateOrUpgradeByDeploymentName(String serviceName, String deploymentName,
        DeploymentRollbackUpdateOrUpgradeParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getMode() == null) {
        throw new NullPointerException("parameters.Mode");
    }

    // 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("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "rollbackUpdateOrUpgradeByDeploymentNameAsync",
                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 + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=rollback");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 rollbackUpdateOrUpgradeElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "RollbackUpdateOrUpgrade");
    requestDoc.appendChild(rollbackUpdateOrUpgradeElement);

    Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode");
    modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString()));
    rollbackUpdateOrUpgradeElement.appendChild(modeElement);

    Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force");
    forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase()));
    rollbackUpdateOrUpgradeElement.appendChild(forceElement);

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Rollback Update Or Upgrade By Deployment Slot operation cancels an
* in-progress configuration update and returns the deployment to its state
* before the update was started. This operation can only be called when an
* update is in progress on the deployment. The deployment status can be
* detected by calling the Get Deployment operation or Get Hosted Service
* Properties operation and inspecting the RollbackAllowed element. If the
* value returned is true a rollback can be performed.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/hh403977.aspx for
* more information)//from   ww  w.j av  a 2 s  . c o  m
*
* @param serviceName Required. The cloud service to swap deployments for.
* @param deploymentSlot Required. The deployment slot.
* @param parameters Required. Parameters supplied to the Rollback Update Or
* Upgrade By Deployment Slot 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 rollbackUpdateOrUpgradeByDeploymentSlot(String serviceName,
        DeploymentSlot deploymentSlot, DeploymentRollbackUpdateOrUpgradeParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentSlot == null) {
        throw new NullPointerException("deploymentSlot");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getMode() == null) {
        throw new NullPointerException("parameters.Mode");
    }

    // 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("deploymentSlot", deploymentSlot);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "rollbackUpdateOrUpgradeByDeploymentSlotAsync",
                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 + "/deploymentslots/";
    url = url + URLEncoder.encode(deploymentSlot.toString(), "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=rollback");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 rollbackUpdateOrUpgradeElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "RollbackUpdateOrUpgrade");
    requestDoc.appendChild(rollbackUpdateOrUpgradeElement);

    Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode");
    modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString()));
    rollbackUpdateOrUpgradeElement.appendChild(modeElement);

    Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force");
    forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase()));
    rollbackUpdateOrUpgradeElement.appendChild(forceElement);

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Changing Deployment Configuration By Name operation initiates a
* change to the deployment configuration. This operation is an
* asynchronous operation. To determine whether the Management service has
* finished processing the request, call Get Operation Status. For more
* information on asynchronous operations, see Tracking Asynchronous
* Service Management Requests at/*from w  w w.j  a v a2  s  .  c o  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx
* for more information)
*
* @param serviceName Required. The cloud service to change deployment
* configuration for.
* @param deploymentName Required. The deployment to change configuration
* for.
* @param parameters Required. Parameters supplied to the Begin Changing
* Configuration Deployment By Name 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 beginChangingConfigurationByName(String serviceName, String deploymentName,
        DeploymentChangeConfigurationParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getConfiguration() == null) {
        throw new NullPointerException("parameters.Configuration");
    }
    if (parameters.getExtensionConfiguration() != null) {
        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration()
                    .getAllRoles()) {
                if (allRolesParameterItem.getId() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id");
                }
            }
        }
        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters
                    .getExtensionConfiguration().getNamedRoles()) {
                if (namedRolesParameterItem.getExtensions() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions");
                }
                if (namedRolesParameterItem.getExtensions() != null) {
                    for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem
                            .getExtensions()) {
                        if (extensionsParameterItem.getId() == null) {
                            throw new NullPointerException(
                                    "parameters.ExtensionConfiguration.NamedRoles.Extensions.Id");
                        }
                    }
                }
                if (namedRolesParameterItem.getRoleName() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName");
                }
            }
        }
    }

    // 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("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginChangingConfigurationByNameAsync", 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 + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=config");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 changeConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ChangeConfiguration");
    requestDoc.appendChild(changeConfigurationElement);

    Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Configuration");
    configurationElement
            .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes())));
    changeConfigurationElement.appendChild(configurationElement);

    if (parameters.isTreatWarningsAsError() != null) {
        Element treatWarningsAsErrorElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "TreatWarningsAsError");
        treatWarningsAsErrorElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isTreatWarningsAsError()).toLowerCase()));
        changeConfigurationElement.appendChild(treatWarningsAsErrorElement);
    }

    if (parameters.getMode() != null) {
        Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode");
        modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString()));
        changeConfigurationElement.appendChild(modeElement);
    }

    if (parameters.getExtendedProperties() != null) {
        if (parameters.getExtendedProperties() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) {
            Element extendedPropertiesDictionaryElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties");
            for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) {
                String extendedPropertiesKey = entry.getKey();
                String extendedPropertiesValue = entry.getValue();
                Element extendedPropertiesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty");
                extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement);

                Element extendedPropertiesKeyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey));
                extendedPropertiesElement.appendChild(extendedPropertiesKeyElement);

                Element extendedPropertiesValueElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue));
                extendedPropertiesElement.appendChild(extendedPropertiesValueElement);
            }
            changeConfigurationElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getExtensionConfiguration() != null) {
        Element extensionConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration");
        changeConfigurationElement.appendChild(extensionConfigurationElement);

        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            if (parameters.getExtensionConfiguration().getAllRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getAllRoles())
                            .isInitialized()) {
                Element allRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles");
                for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration()
                        .getAllRoles()) {
                    Element extensionElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                    allRolesSequenceElement.appendChild(extensionElement);

                    Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                            "Id");
                    idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId()));
                    extensionElement.appendChild(idElement);
                }
                extensionConfigurationElement.appendChild(allRolesSequenceElement);
            }
        }

        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            if (parameters.getExtensionConfiguration().getNamedRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getNamedRoles())
                            .isInitialized()) {
                Element namedRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles");
                for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration()
                        .getNamedRoles()) {
                    Element roleElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Role");
                    namedRolesSequenceElement.appendChild(roleElement);

                    Element roleNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName");
                    roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName()));
                    roleElement.appendChild(roleNameElement);

                    if (namedRolesItem.getExtensions() instanceof LazyCollection == false
                            || ((LazyCollection) namedRolesItem.getExtensions()).isInitialized()) {
                        Element extensionsSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions");
                        for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) {
                            Element extensionElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                            extensionsSequenceElement.appendChild(extensionElement2);

                            Element idElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Id");
                            idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId()));
                            extensionElement2.appendChild(idElement2);
                        }
                        roleElement.appendChild(extensionsSequenceElement);
                    }
                }
                extensionConfigurationElement.appendChild(namedRolesSequenceElement);
            }
        }
    }

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Changing Deployment Configuration By Slot operation initiates a
* change to the deployment configuration. This operation is an
* asynchronous operation. To determine whether the Management service has
* finished processing the request, call Get Operation Status. For more
* information on asynchronous operations, see Tracking Asynchronous
* Service Management Requests at/*from   www .j a v  a2  s  .co  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460809.aspx
* for more information)
*
* @param serviceName Required. The cloud service to change deployment
* configuration for.
* @param deploymentSlot Required. The slot to change deployment
* configuration for.
* @param parameters Required. Parameters supplied to the Begin Changing
* Configuration Deployment By Slot 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 beginChangingConfigurationBySlot(String serviceName, DeploymentSlot deploymentSlot,
        DeploymentChangeConfigurationParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentSlot == null) {
        throw new NullPointerException("deploymentSlot");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getConfiguration() == null) {
        throw new NullPointerException("parameters.Configuration");
    }
    if (parameters.getExtensionConfiguration() != null) {
        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration()
                    .getAllRoles()) {
                if (allRolesParameterItem.getId() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id");
                }
            }
        }
        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters
                    .getExtensionConfiguration().getNamedRoles()) {
                if (namedRolesParameterItem.getExtensions() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions");
                }
                if (namedRolesParameterItem.getExtensions() != null) {
                    for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem
                            .getExtensions()) {
                        if (extensionsParameterItem.getId() == null) {
                            throw new NullPointerException(
                                    "parameters.ExtensionConfiguration.NamedRoles.Extensions.Id");
                        }
                    }
                }
                if (namedRolesParameterItem.getRoleName() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName");
                }
            }
        }
    }

    // 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("deploymentSlot", deploymentSlot);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginChangingConfigurationBySlotAsync", 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 + "/deploymentslots/";
    url = url + URLEncoder.encode(deploymentSlot.toString(), "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=config");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 changeConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ChangeConfiguration");
    requestDoc.appendChild(changeConfigurationElement);

    Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Configuration");
    configurationElement
            .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes())));
    changeConfigurationElement.appendChild(configurationElement);

    if (parameters.isTreatWarningsAsError() != null) {
        Element treatWarningsAsErrorElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "TreatWarningsAsError");
        treatWarningsAsErrorElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isTreatWarningsAsError()).toLowerCase()));
        changeConfigurationElement.appendChild(treatWarningsAsErrorElement);
    }

    if (parameters.getMode() != null) {
        Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode");
        modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString()));
        changeConfigurationElement.appendChild(modeElement);
    }

    if (parameters.getExtendedProperties() != null) {
        if (parameters.getExtendedProperties() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) {
            Element extendedPropertiesDictionaryElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties");
            for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) {
                String extendedPropertiesKey = entry.getKey();
                String extendedPropertiesValue = entry.getValue();
                Element extendedPropertiesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty");
                extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement);

                Element extendedPropertiesKeyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey));
                extendedPropertiesElement.appendChild(extendedPropertiesKeyElement);

                Element extendedPropertiesValueElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue));
                extendedPropertiesElement.appendChild(extendedPropertiesValueElement);
            }
            changeConfigurationElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getExtensionConfiguration() != null) {
        Element extensionConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration");
        changeConfigurationElement.appendChild(extensionConfigurationElement);

        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            if (parameters.getExtensionConfiguration().getAllRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getAllRoles())
                            .isInitialized()) {
                Element allRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles");
                for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration()
                        .getAllRoles()) {
                    Element extensionElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                    allRolesSequenceElement.appendChild(extensionElement);

                    Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                            "Id");
                    idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId()));
                    extensionElement.appendChild(idElement);
                }
                extensionConfigurationElement.appendChild(allRolesSequenceElement);
            }
        }

        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            if (parameters.getExtensionConfiguration().getNamedRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getNamedRoles())
                            .isInitialized()) {
                Element namedRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles");
                for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration()
                        .getNamedRoles()) {
                    Element roleElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Role");
                    namedRolesSequenceElement.appendChild(roleElement);

                    Element roleNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName");
                    roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName()));
                    roleElement.appendChild(roleNameElement);

                    if (namedRolesItem.getExtensions() instanceof LazyCollection == false
                            || ((LazyCollection) namedRolesItem.getExtensions()).isInitialized()) {
                        Element extensionsSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions");
                        for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) {
                            Element extensionElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                            extensionsSequenceElement.appendChild(extensionElement2);

                            Element idElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Id");
                            idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId()));
                            extensionElement2.appendChild(idElement2);
                        }
                        roleElement.appendChild(extensionsSequenceElement);
                    }
                }
                extensionConfigurationElement.appendChild(namedRolesSequenceElement);
            }
        }
    }

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Creating Deployment operation uploads a new service package and
* creates a new deployment in the staging or production environments. This
* operation is an asynchronous operation. To determine whether the
* management service has finished processing the request, call Get
* Operation Status. For more information on asynchronous operations, see
* Tracking Asynchronous Service Management Requests at
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/ee460813.aspx
* for more information)/*from w  w w . j  ava  2 s .c o  m*/
*
* @param serviceName Required. The cloud service to create a deployment for.
* @param deploymentSlot Required. The slot to create a deployment for.
* @param parameters Required. Parameters supplied to the Begin Creating
* Deployment 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, DeploymentSlot deploymentSlot,
        DeploymentCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentSlot == null) {
        throw new NullPointerException("deploymentSlot");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getConfiguration() == null) {
        throw new NullPointerException("parameters.Configuration");
    }
    if (parameters.getExtensionConfiguration() != null) {
        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration()
                    .getAllRoles()) {
                if (allRolesParameterItem.getId() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id");
                }
            }
        }
        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters
                    .getExtensionConfiguration().getNamedRoles()) {
                if (namedRolesParameterItem.getExtensions() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions");
                }
                if (namedRolesParameterItem.getExtensions() != null) {
                    for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem
                            .getExtensions()) {
                        if (extensionsParameterItem.getId() == null) {
                            throw new NullPointerException(
                                    "parameters.ExtensionConfiguration.NamedRoles.Extensions.Id");
                        }
                    }
                }
                if (namedRolesParameterItem.getRoleName() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName");
                }
            }
        }
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getPackageUri() == null) {
        throw new NullPointerException("parameters.PackageUri");
    }

    // 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("deploymentSlot", deploymentSlot);
        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 + "/deploymentslots/";
    url = url + URLEncoder.encode(deploymentSlot.toString(), "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
    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 createDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "CreateDeployment");
    requestDoc.appendChild(createDeploymentElement);

    Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
    nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
    createDeploymentElement.appendChild(nameElement);

    Element packageUrlElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PackageUrl");
    packageUrlElement.appendChild(requestDoc.createTextNode(parameters.getPackageUri().toString()));
    createDeploymentElement.appendChild(packageUrlElement);

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
    createDeploymentElement.appendChild(labelElement);

    Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Configuration");
    configurationElement
            .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes())));
    createDeploymentElement.appendChild(configurationElement);

    if (parameters.isStartDeployment() != null) {
        Element startDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "StartDeployment");
        startDeploymentElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isStartDeployment()).toLowerCase()));
        createDeploymentElement.appendChild(startDeploymentElement);
    }

    if (parameters.isTreatWarningsAsError() != null) {
        Element treatWarningsAsErrorElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "TreatWarningsAsError");
        treatWarningsAsErrorElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isTreatWarningsAsError()).toLowerCase()));
        createDeploymentElement.appendChild(treatWarningsAsErrorElement);
    }

    if (parameters.getExtendedProperties() != null) {
        if (parameters.getExtendedProperties() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) {
            Element extendedPropertiesDictionaryElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties");
            for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) {
                String extendedPropertiesKey = entry.getKey();
                String extendedPropertiesValue = entry.getValue();
                Element extendedPropertiesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty");
                extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement);

                Element extendedPropertiesKeyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey));
                extendedPropertiesElement.appendChild(extendedPropertiesKeyElement);

                Element extendedPropertiesValueElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue));
                extendedPropertiesElement.appendChild(extendedPropertiesValueElement);
            }
            createDeploymentElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getExtensionConfiguration() != null) {
        Element extensionConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration");
        createDeploymentElement.appendChild(extensionConfigurationElement);

        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            if (parameters.getExtensionConfiguration().getAllRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getAllRoles())
                            .isInitialized()) {
                Element allRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles");
                for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration()
                        .getAllRoles()) {
                    Element extensionElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                    allRolesSequenceElement.appendChild(extensionElement);

                    Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                            "Id");
                    idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId()));
                    extensionElement.appendChild(idElement);
                }
                extensionConfigurationElement.appendChild(allRolesSequenceElement);
            }
        }

        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            if (parameters.getExtensionConfiguration().getNamedRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getNamedRoles())
                            .isInitialized()) {
                Element namedRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles");
                for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration()
                        .getNamedRoles()) {
                    Element roleElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Role");
                    namedRolesSequenceElement.appendChild(roleElement);

                    Element roleNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName");
                    roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName()));
                    roleElement.appendChild(roleNameElement);

                    if (namedRolesItem.getExtensions() instanceof LazyCollection == false
                            || ((LazyCollection) namedRolesItem.getExtensions()).isInitialized()) {
                        Element extensionsSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions");
                        for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) {
                            Element extensionElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                            extensionsSequenceElement.appendChild(extensionElement2);

                            Element idElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Id");
                            idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId()));
                            extensionElement2.appendChild(idElement2);
                        }
                        roleElement.appendChild(extensionsSequenceElement);
                    }
                }
                extensionConfigurationElement.appendChild(namedRolesSequenceElement);
            }
        }
    }

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Upgrading Deployment By Name operation initiates an update of
* role instances in a deployment using the package and configuration that
* you specify. For more information about updating role instances, see
* Update an Azure Service at//  w w  w. j  a  v  a  2  s  .  co  m
* http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx. This
* operation is an asynchronous operation. To determine whether the request
* has been processed, call Get Operation Status. For more information on
* asynchronous operations, see Tracking Asynchronous Service Management
* Requests at
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To
* perform an automatic update of a deployment, call Upgrade Deployment or
* Change Deployment Configuration with the Mode element set to automatic.
* The update proceeds from that point without a need for further input.
* You can call Get Operation Status to determine when the update is
* complete. To perform a manual update, first call Upgrade Deployment with
* the Mode element set to manual. Next, call Walk Upgrade Domain to update
* each domain within the deployment. You should make sure that the
* operation is complete by calling Get Operation Status before updating
* the next domain. Important: An update that adds or removes role
* instances will result in a configuration update to all roles that are
* deployed in the cloud service. Existing role instances need to be
* notified of new role instances so that all role instances can
* communicate together in the cloud service. By default, a cloud service
* is deployed with five update domains, which are updated one at a time
* during an in-place update. For information on modifying the number of
* update domains in the service definition file, see the Azure Service
* Definition Schema (.csdef File). To determine the update domain in which
* a particular instance is running in Windows Azure, use the UpdateDomain
* property of the RoleInstance class. See the Azure Managed Library
* Reference at
* http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for
* more information.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for
* more information)
*
* @param serviceName Required. The cloud service to upgrade.
* @param deploymentName Required. The deployment to upgrade.
* @param parameters Required. Parameters supplied to the Begin Upgrading
* Deployment By Name 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 beginUpgradingByName(String serviceName, String deploymentName,
        DeploymentUpgradeParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getConfiguration() == null) {
        throw new NullPointerException("parameters.Configuration");
    }
    if (parameters.getExtensionConfiguration() != null) {
        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration()
                    .getAllRoles()) {
                if (allRolesParameterItem.getId() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id");
                }
            }
        }
        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters
                    .getExtensionConfiguration().getNamedRoles()) {
                if (namedRolesParameterItem.getExtensions() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions");
                }
                if (namedRolesParameterItem.getExtensions() != null) {
                    for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem
                            .getExtensions()) {
                        if (extensionsParameterItem.getId() == null) {
                            throw new NullPointerException(
                                    "parameters.ExtensionConfiguration.NamedRoles.Extensions.Id");
                        }
                    }
                }
                if (namedRolesParameterItem.getRoleName() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName");
                }
            }
        }
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }
    if (parameters.getMode() == null) {
        throw new NullPointerException("parameters.Mode");
    }
    if (parameters.getPackageUri() == null) {
        throw new NullPointerException("parameters.PackageUri");
    }

    // 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("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpgradingByNameAsync", 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 + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=upgrade");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 upgradeDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "UpgradeDeployment");
    requestDoc.appendChild(upgradeDeploymentElement);

    Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode");
    modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString()));
    upgradeDeploymentElement.appendChild(modeElement);

    Element packageUrlElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PackageUrl");
    packageUrlElement.appendChild(requestDoc.createTextNode(parameters.getPackageUri().toString()));
    upgradeDeploymentElement.appendChild(packageUrlElement);

    Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Configuration");
    configurationElement
            .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes())));
    upgradeDeploymentElement.appendChild(configurationElement);

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
    upgradeDeploymentElement.appendChild(labelElement);

    if (parameters.getRoleToUpgrade() != null) {
        Element roleToUpgradeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "RoleToUpgrade");
        roleToUpgradeElement.appendChild(requestDoc.createTextNode(parameters.getRoleToUpgrade()));
        upgradeDeploymentElement.appendChild(roleToUpgradeElement);
    }

    Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force");
    forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase()));
    upgradeDeploymentElement.appendChild(forceElement);

    if (parameters.getExtendedProperties() != null) {
        if (parameters.getExtendedProperties() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) {
            Element extendedPropertiesDictionaryElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties");
            for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) {
                String extendedPropertiesKey = entry.getKey();
                String extendedPropertiesValue = entry.getValue();
                Element extendedPropertiesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty");
                extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement);

                Element extendedPropertiesKeyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey));
                extendedPropertiesElement.appendChild(extendedPropertiesKeyElement);

                Element extendedPropertiesValueElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue));
                extendedPropertiesElement.appendChild(extendedPropertiesValueElement);
            }
            upgradeDeploymentElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getExtensionConfiguration() != null) {
        Element extensionConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration");
        upgradeDeploymentElement.appendChild(extensionConfigurationElement);

        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            if (parameters.getExtensionConfiguration().getAllRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getAllRoles())
                            .isInitialized()) {
                Element allRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles");
                for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration()
                        .getAllRoles()) {
                    Element extensionElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                    allRolesSequenceElement.appendChild(extensionElement);

                    Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                            "Id");
                    idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId()));
                    extensionElement.appendChild(idElement);
                }
                extensionConfigurationElement.appendChild(allRolesSequenceElement);
            }
        }

        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            if (parameters.getExtensionConfiguration().getNamedRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getNamedRoles())
                            .isInitialized()) {
                Element namedRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles");
                for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration()
                        .getNamedRoles()) {
                    Element roleElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Role");
                    namedRolesSequenceElement.appendChild(roleElement);

                    Element roleNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName");
                    roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName()));
                    roleElement.appendChild(roleNameElement);

                    if (namedRolesItem.getExtensions() instanceof LazyCollection == false
                            || ((LazyCollection) namedRolesItem.getExtensions()).isInitialized()) {
                        Element extensionsSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions");
                        for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) {
                            Element extensionElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                            extensionsSequenceElement.appendChild(extensionElement2);

                            Element idElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Id");
                            idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId()));
                            extensionElement2.appendChild(idElement2);
                        }
                        roleElement.appendChild(extensionsSequenceElement);
                    }
                }
                extensionConfigurationElement.appendChild(namedRolesSequenceElement);
            }
        }
    }

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

From source file:com.microsoft.windowsazure.management.compute.DeploymentOperationsImpl.java

/**
* The Begin Upgrading Deployment By Slot operation initiates an update of
* role instances in a deployment using the package and configuration that
* you specify. For more information about updating role instances, see
* Update an Azure Service at//from  www.j  a  va 2  s.c  o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx.This
* operation is an asynchronous operation. To determine whether the request
* has been processed, call Get Operation Status. For more information on
* asynchronous operations, see Tracking Asynchronous Service Management
* Requests at
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460791.aspx. To
* perform an automatic update of a deployment, call Upgrade Deployment or
* Change Deployment Configuration with the Mode element set to automatic.
* The update proceeds from that point without a need for further input.
* You can call Get Operation Status to determine when the update is
* complete. To perform a manual update, first call Upgrade Deployment with
* the Mode element set to manual. Next, call Walk Upgrade Domain to update
* each domain within the deployment. You should make sure that the
* operation is complete by calling Get Operation Status before updating
* the next domain. Important: An update that adds or removes role
* instances will result in a configuration update to all roles that are
* deployed in the cloud service. Existing role instances need to be
* notified of new role instances so that all role instances can
* communicate together in the cloud service. By default, a cloud service
* is deployed with five update domains, which are updated one at a time
* during an in-place update. For information on modifying the number of
* update domains in the service definition file, see the Azure Service
* Definition Schema (.csdef File). To determine the update domain in which
* a particular instance is running in Windows Azure, use the UpdateDomain
* property of the RoleInstance class. See the Azure Managed Library
* Reference at
* http://msdn.microsoft.com/en-us/library/windowsazure/dd179380.aspx for
* more information.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460793.aspx for
* more information)
*
* @param serviceName Required. The cloud service to upgrade.
* @param deploymentSlot Required. The slot to upgrade.
* @param parameters Required. Parameters supplied to the Begin Upgrading
* Deployment By Slot 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 beginUpgradingBySlot(String serviceName, DeploymentSlot deploymentSlot,
        DeploymentUpgradeParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    // TODO: Validate serviceName is a valid DNS name.
    if (deploymentSlot == null) {
        throw new NullPointerException("deploymentSlot");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getConfiguration() == null) {
        throw new NullPointerException("parameters.Configuration");
    }
    if (parameters.getExtensionConfiguration() != null) {
        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            for (ExtensionConfiguration.Extension allRolesParameterItem : parameters.getExtensionConfiguration()
                    .getAllRoles()) {
                if (allRolesParameterItem.getId() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.AllRoles.Id");
                }
            }
        }
        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            for (ExtensionConfiguration.NamedRole namedRolesParameterItem : parameters
                    .getExtensionConfiguration().getNamedRoles()) {
                if (namedRolesParameterItem.getExtensions() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.Extensions");
                }
                if (namedRolesParameterItem.getExtensions() != null) {
                    for (ExtensionConfiguration.Extension extensionsParameterItem : namedRolesParameterItem
                            .getExtensions()) {
                        if (extensionsParameterItem.getId() == null) {
                            throw new NullPointerException(
                                    "parameters.ExtensionConfiguration.NamedRoles.Extensions.Id");
                        }
                    }
                }
                if (namedRolesParameterItem.getRoleName() == null) {
                    throw new NullPointerException("parameters.ExtensionConfiguration.NamedRoles.RoleName");
                }
            }
        }
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }
    if (parameters.getMode() == null) {
        throw new NullPointerException("parameters.Mode");
    }
    if (parameters.getPackageUri() == null) {
        throw new NullPointerException("parameters.PackageUri");
    }

    // 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("deploymentSlot", deploymentSlot);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpgradingBySlotAsync", 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 + "/deploymentslots/";
    url = url + URLEncoder.encode(deploymentSlot.toString(), "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("comp=upgrade");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    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 upgradeDeploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "UpgradeDeployment");
    requestDoc.appendChild(upgradeDeploymentElement);

    Element modeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Mode");
    modeElement.appendChild(requestDoc.createTextNode(parameters.getMode().toString()));
    upgradeDeploymentElement.appendChild(modeElement);

    Element packageUrlElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PackageUrl");
    packageUrlElement.appendChild(requestDoc.createTextNode(parameters.getPackageUri().toString()));
    upgradeDeploymentElement.appendChild(packageUrlElement);

    Element configurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Configuration");
    configurationElement
            .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getConfiguration().getBytes())));
    upgradeDeploymentElement.appendChild(configurationElement);

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
    upgradeDeploymentElement.appendChild(labelElement);

    if (parameters.getRoleToUpgrade() != null) {
        Element roleToUpgradeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "RoleToUpgrade");
        roleToUpgradeElement.appendChild(requestDoc.createTextNode(parameters.getRoleToUpgrade()));
        upgradeDeploymentElement.appendChild(roleToUpgradeElement);
    }

    Element forceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Force");
    forceElement.appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isForce()).toLowerCase()));
    upgradeDeploymentElement.appendChild(forceElement);

    if (parameters.getExtendedProperties() != null) {
        if (parameters.getExtendedProperties() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) {
            Element extendedPropertiesDictionaryElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties");
            for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) {
                String extendedPropertiesKey = entry.getKey();
                String extendedPropertiesValue = entry.getValue();
                Element extendedPropertiesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty");
                extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement);

                Element extendedPropertiesKeyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey));
                extendedPropertiesElement.appendChild(extendedPropertiesKeyElement);

                Element extendedPropertiesValueElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue));
                extendedPropertiesElement.appendChild(extendedPropertiesValueElement);
            }
            upgradeDeploymentElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getExtensionConfiguration() != null) {
        Element extensionConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtensionConfiguration");
        upgradeDeploymentElement.appendChild(extensionConfigurationElement);

        if (parameters.getExtensionConfiguration().getAllRoles() != null) {
            if (parameters.getExtensionConfiguration().getAllRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getAllRoles())
                            .isInitialized()) {
                Element allRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AllRoles");
                for (ExtensionConfiguration.Extension allRolesItem : parameters.getExtensionConfiguration()
                        .getAllRoles()) {
                    Element extensionElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                    allRolesSequenceElement.appendChild(extensionElement);

                    Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                            "Id");
                    idElement.appendChild(requestDoc.createTextNode(allRolesItem.getId()));
                    extensionElement.appendChild(idElement);
                }
                extensionConfigurationElement.appendChild(allRolesSequenceElement);
            }
        }

        if (parameters.getExtensionConfiguration().getNamedRoles() != null) {
            if (parameters.getExtensionConfiguration().getNamedRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionConfiguration().getNamedRoles())
                            .isInitialized()) {
                Element namedRolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "NamedRoles");
                for (ExtensionConfiguration.NamedRole namedRolesItem : parameters.getExtensionConfiguration()
                        .getNamedRoles()) {
                    Element roleElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Role");
                    namedRolesSequenceElement.appendChild(roleElement);

                    Element roleNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName");
                    roleNameElement.appendChild(requestDoc.createTextNode(namedRolesItem.getRoleName()));
                    roleElement.appendChild(roleNameElement);

                    if (namedRolesItem.getExtensions() instanceof LazyCollection == false
                            || ((LazyCollection) namedRolesItem.getExtensions()).isInitialized()) {
                        Element extensionsSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Extensions");
                        for (ExtensionConfiguration.Extension extensionsItem : namedRolesItem.getExtensions()) {
                            Element extensionElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Extension");
                            extensionsSequenceElement.appendChild(extensionElement2);

                            Element idElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Id");
                            idElement2.appendChild(requestDoc.createTextNode(extensionsItem.getId()));
                            extensionElement2.appendChild(idElement2);
                        }
                        roleElement.appendChild(extensionsSequenceElement);
                    }
                }
                extensionConfigurationElement.appendChild(namedRolesSequenceElement);
            }
        }
    }

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