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.storage.StorageAccountOperationsImpl.java

/**
* The Update Storage Account operation updates the label and the
* description, and enables or disables the geo-replication status for a
* storage account in Azure.  (see//ww  w . j  a  v  a 2 s  .c  o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx for
* more information)
*
* @param accountName Required. Name of the storage account to update.
* @param parameters Required. Parameters supplied to the Update Storage
* Account operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse update(String accountName, StorageAccountUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (accountName == null) {
        throw new NullPointerException("accountName");
    }
    if (accountName.length() < 3) {
        throw new IllegalArgumentException("accountName");
    }
    if (accountName.length() > 24) {
        throw new IllegalArgumentException("accountName");
    }
    for (char accountNameChar : accountName.toCharArray()) {
        if (Character.isLowerCase(accountNameChar) == false && Character.isDigit(accountNameChar) == false) {
            throw new IllegalArgumentException("accountName");
        }
    }
    // TODO: Validate accountName is a valid DNS name.
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("accountName", accountName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", 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/storageservices/";
    url = url + URLEncoder.encode(accountName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        updateStorageServiceInputElement.appendChild(descriptionElement);
    } else {
        Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
        nilAttribute.setValue("true");
        emptyElement.setAttributeNode(nilAttribute);
        updateStorageServiceInputElement.appendChild(emptyElement);
    }

    if (parameters.getLabel() != null) {
        Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
        labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
        updateStorageServiceInputElement.appendChild(labelElement);
    }

    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);
            }
            updateStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getAccountType() != null) {
        Element accountTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AccountType");
        accountTypeElement.appendChild(requestDoc.createTextNode(parameters.getAccountType()));
        updateStorageServiceInputElement.appendChild(accountTypeElement);
    }

    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.storage.StorageAccountOperationsImpl.java

/**
* The Begin Creating Storage Account operation creates a new storage
* account in Azure.  (see/*  w w  w .  j  ava  2  s  . co  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Begin Creating
* Storage Account operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreating(StorageAccountCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    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.getName().length() < 3) {
        throw new IllegalArgumentException("parameters.Name");
    }
    if (parameters.getName().length() > 24) {
        throw new IllegalArgumentException("parameters.Name");
    }
    for (char nameChar : parameters.getName().toCharArray()) {
        if (Character.isLowerCase(nameChar) == false && Character.isDigit(nameChar) == false) {
            throw new IllegalArgumentException("parameters.Name");
        }
    }
    // TODO: Validate parameters.Name is a valid DNS name.

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("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/storageservices";
    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", "2014-10-01");

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

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

    Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceName");
    serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
    createStorageServiceInputElement.appendChild(serviceNameElement);

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        createStorageServiceInputElement.appendChild(descriptionElement);
    } else {
        Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
        nilAttribute.setValue("true");
        emptyElement.setAttributeNode(nilAttribute);
        createStorageServiceInputElement.appendChild(emptyElement);
    }

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

    if (parameters.getAffinityGroup() != null) {
        Element affinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AffinityGroup");
        affinityGroupElement.appendChild(requestDoc.createTextNode(parameters.getAffinityGroup()));
        createStorageServiceInputElement.appendChild(affinityGroupElement);
    }

    if (parameters.getLocation() != null) {
        Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Location");
        locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
        createStorageServiceInputElement.appendChild(locationElement);
    }

    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);
            }
            createStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getAccountType() != null) {
        Element accountTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AccountType");
        accountTypeElement.appendChild(requestDoc.createTextNode(parameters.getAccountType()));
        createStorageServiceInputElement.appendChild(accountTypeElement);
    }

    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.ExtensionImageOperationsImpl.java

/**
* Register a new extension. An extension is identified by the combination
* of its ProviderNamespace and Type (case-sensitive string). It is not
* allowed to register an extension with the same identity (i.e.
* combination of ProviderNamespace and Type) of an already-registered
* extension. To register new version of an existing extension, the Update
* Extension API should be used./*  w  ww .j  a v a  2  s . c o  m*/
*
* @param parameters Required. Parameters supplied to the Register Virtual
* Machine Extension Image 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 beginRegistering(ExtensionImageRegisterParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getCertificate() != null) {
        if (parameters.getCertificate().getStoreLocation() == null) {
            throw new NullPointerException("parameters.Certificate.StoreLocation");
        }
    }
    if (parameters.getExtensionEndpoints() != null) {
        if (parameters.getExtensionEndpoints().getInputEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInputEndpoints()) {
                if (inputEndpointsParameterItem.getLocalPort() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.LocalPort");
                }
                if (inputEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.Name");
                }
                if (inputEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.Protocol");
                }
            }
        }
        if (parameters.getExtensionEndpoints().getInstanceInputEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInstanceInputEndpoints()) {
                if (instanceInputEndpointsParameterItem.getLocalPort() == null) {
                    throw new NullPointerException(
                            "parameters.ExtensionEndpoints.InstanceInputEndpoints.LocalPort");
                }
                if (instanceInputEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Name");
                }
                if (instanceInputEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException(
                            "parameters.ExtensionEndpoints.InstanceInputEndpoints.Protocol");
                }
            }
        }
        if (parameters.getExtensionEndpoints().getInternalEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInternalEndpoints()) {
                if (internalEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InternalEndpoints.Name");
                }
                if (internalEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InternalEndpoints.Protocol");
                }
            }
        }
    }
    if (parameters.getLocalResources() != null) {
        for (ExtensionLocalResourceConfiguration localResourcesParameterItem : parameters.getLocalResources()) {
            if (localResourcesParameterItem.getName() == null) {
                throw new NullPointerException("parameters.LocalResources.Name");
            }
        }
    }
    if (parameters.getProviderNameSpace() == null) {
        throw new NullPointerException("parameters.ProviderNameSpace");
    }
    if (parameters.getType() == null) {
        throw new NullPointerException("parameters.Type");
    }
    if (parameters.getVersion() == null) {
        throw new NullPointerException("parameters.Version");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginRegisteringAsync", 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/extensions";
    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 extensionImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ExtensionImage");
    requestDoc.appendChild(extensionImageElement);

    Element providerNameSpaceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ProviderNameSpace");
    providerNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getProviderNameSpace()));
    extensionImageElement.appendChild(providerNameSpaceElement);

    Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type");
    typeElement.appendChild(requestDoc.createTextNode(parameters.getType()));
    extensionImageElement.appendChild(typeElement);

    Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version");
    versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion()));
    extensionImageElement.appendChild(versionElement);

    if (parameters.getLabel() != null) {
        Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
        labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
        extensionImageElement.appendChild(labelElement);
    }

    if (parameters.getHostingResources() != null) {
        Element hostingResourcesElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostingResources");
        hostingResourcesElement.appendChild(requestDoc.createTextNode(parameters.getHostingResources()));
        extensionImageElement.appendChild(hostingResourcesElement);
    }

    if (parameters.getMediaLink() != null) {
        Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MediaLink");
        mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLink().toString()));
        extensionImageElement.appendChild(mediaLinkElement);
    }

    if (parameters.getCertificate() != null) {
        Element certificateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Certificate");
        extensionImageElement.appendChild(certificateElement);

        Element storeLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "StoreLocation");
        storeLocationElement
                .appendChild(requestDoc.createTextNode(parameters.getCertificate().getStoreLocation()));
        certificateElement.appendChild(storeLocationElement);

        if (parameters.getCertificate().getStoreName() != null) {
            Element storeNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "StoreName");
            storeNameElement.appendChild(requestDoc.createTextNode(parameters.getCertificate().getStoreName()));
            certificateElement.appendChild(storeNameElement);
        }

        if (parameters.getCertificate().isThumbprintRequired() != null) {
            Element thumbprintRequiredElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintRequired");
            thumbprintRequiredElement.appendChild(requestDoc.createTextNode(
                    Boolean.toString(parameters.getCertificate().isThumbprintRequired()).toLowerCase()));
            certificateElement.appendChild(thumbprintRequiredElement);
        }

        if (parameters.getCertificate().getThumbprintAlgorithm() != null) {
            Element thumbprintAlgorithmElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm");
            thumbprintAlgorithmElement.appendChild(
                    requestDoc.createTextNode(parameters.getCertificate().getThumbprintAlgorithm()));
            certificateElement.appendChild(thumbprintAlgorithmElement);
        }
    }

    if (parameters.getExtensionEndpoints() != null) {
        Element endpointsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Endpoints");
        extensionImageElement.appendChild(endpointsElement);

        if (parameters.getExtensionEndpoints().getInputEndpoints() != null) {
            if (parameters.getExtensionEndpoints().getInputEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInputEndpoints())
                            .isInitialized()) {
                Element inputEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints");
                for (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsItem : parameters
                        .getExtensionEndpoints().getInputEndpoints()) {
                    Element inputEndpointElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                    inputEndpointsSequenceElement.appendChild(inputEndpointElement);

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

                    Element protocolElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getProtocol()));
                    inputEndpointElement.appendChild(protocolElement);

                    Element portElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                    portElement.appendChild(
                            requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort())));
                    inputEndpointElement.appendChild(portElement);

                    Element localPortElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                    localPortElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLocalPort()));
                    inputEndpointElement.appendChild(localPortElement);
                }
                endpointsElement.appendChild(inputEndpointsSequenceElement);
            }
        }

        if (parameters.getExtensionEndpoints().getInternalEndpoints() != null) {
            if (parameters.getExtensionEndpoints().getInternalEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInternalEndpoints())
                            .isInitialized()) {
                Element internalEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InternalEndpoints");
                for (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsItem : parameters
                        .getExtensionEndpoints().getInternalEndpoints()) {
                    Element internalEndpointElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InternalEndpoint");
                    internalEndpointsSequenceElement.appendChild(internalEndpointElement);

                    Element nameElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    nameElement2.appendChild(requestDoc.createTextNode(internalEndpointsItem.getName()));
                    internalEndpointElement.appendChild(nameElement2);

                    Element protocolElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement2
                            .appendChild(requestDoc.createTextNode(internalEndpointsItem.getProtocol()));
                    internalEndpointElement.appendChild(protocolElement2);

                    Element portElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                    portElement2.appendChild(
                            requestDoc.createTextNode(Integer.toString(internalEndpointsItem.getPort())));
                    internalEndpointElement.appendChild(portElement2);
                }
                endpointsElement.appendChild(internalEndpointsSequenceElement);
            }
        }

        if (parameters.getExtensionEndpoints().getInstanceInputEndpoints() != null) {
            if (parameters.getExtensionEndpoints()
                    .getInstanceInputEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInstanceInputEndpoints())
                            .isInitialized()) {
                Element instanceInputEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InstanceInputEndpoints");
                for (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsItem : parameters
                        .getExtensionEndpoints().getInstanceInputEndpoints()) {
                    Element instanceInputEndpointElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "InstanceInputEndpoint");
                    instanceInputEndpointsSequenceElement.appendChild(instanceInputEndpointElement);

                    Element nameElement3 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    nameElement3.appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getName()));
                    instanceInputEndpointElement.appendChild(nameElement3);

                    Element protocolElement3 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement3
                            .appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getProtocol()));
                    instanceInputEndpointElement.appendChild(protocolElement3);

                    Element localPortElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                    localPortElement2
                            .appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getLocalPort()));
                    instanceInputEndpointElement.appendChild(localPortElement2);

                    Element fixedPortMinElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "FixedPortMin");
                    fixedPortMinElement.appendChild(requestDoc
                            .createTextNode(Integer.toString(instanceInputEndpointsItem.getFixedPortMin())));
                    instanceInputEndpointElement.appendChild(fixedPortMinElement);

                    Element fixedPortMaxElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "FixedPortMax");
                    fixedPortMaxElement.appendChild(requestDoc
                            .createTextNode(Integer.toString(instanceInputEndpointsItem.getFixedPortMax())));
                    instanceInputEndpointElement.appendChild(fixedPortMaxElement);
                }
                endpointsElement.appendChild(instanceInputEndpointsSequenceElement);
            }
        }
    }

    if (parameters.getPublicConfigurationSchema() != null) {
        Element publicConfigurationSchemaElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicConfigurationSchema");
        publicConfigurationSchemaElement.appendChild(
                requestDoc.createTextNode(Base64.encode(parameters.getPublicConfigurationSchema().getBytes())));
        extensionImageElement.appendChild(publicConfigurationSchemaElement);
    }

    if (parameters.getPrivateConfigurationSchema() != null) {
        Element privateConfigurationSchemaElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PrivateConfigurationSchema");
        privateConfigurationSchemaElement.appendChild(requestDoc
                .createTextNode(Base64.encode(parameters.getPrivateConfigurationSchema().getBytes())));
        extensionImageElement.appendChild(privateConfigurationSchemaElement);
    }

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        extensionImageElement.appendChild(descriptionElement);
    }

    if (parameters.getPublisherName() != null) {
        Element publisherNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublisherName");
        publisherNameElement.appendChild(requestDoc.createTextNode(parameters.getPublisherName()));
        extensionImageElement.appendChild(publisherNameElement);
    }

    if (parameters.getPublishedDate() != null) {
        Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublishedDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        publishedDateElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
        extensionImageElement.appendChild(publishedDateElement);
    }

    if (parameters.getLocalResources() != null) {
        Element localResourcesSequenceElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalResources");
        for (ExtensionLocalResourceConfiguration localResourcesItem : parameters.getLocalResources()) {
            Element localResourceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalResource");
            localResourcesSequenceElement.appendChild(localResourceElement);

            Element nameElement4 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Name");
            nameElement4.appendChild(requestDoc.createTextNode(localResourcesItem.getName()));
            localResourceElement.appendChild(nameElement4);

            if (localResourcesItem.getSizeInMB() != null) {
                Element sizeInMBElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SizeInMB");
                sizeInMBElement.appendChild(
                        requestDoc.createTextNode(Integer.toString(localResourcesItem.getSizeInMB())));
                localResourceElement.appendChild(sizeInMBElement);
            }
        }
        extensionImageElement.appendChild(localResourcesSequenceElement);
    }

    if (parameters.isBlockRoleUponFailure() != null) {
        Element blockRoleUponFailureElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "BlockRoleUponFailure");
        blockRoleUponFailureElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isBlockRoleUponFailure()).toLowerCase()));
        extensionImageElement.appendChild(blockRoleUponFailureElement);
    }

    if (parameters.isInternalExtension() != null) {
        Element isInternalExtensionElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "IsInternalExtension");
        isInternalExtensionElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isInternalExtension()).toLowerCase()));
        extensionImageElement.appendChild(isInternalExtensionElement);
    }

    if (parameters.getSampleConfig() != null) {
        Element sampleConfigElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SampleConfig");
        sampleConfigElement
                .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getSampleConfig().getBytes())));
        extensionImageElement.appendChild(sampleConfigElement);
    }

    if (parameters.isReplicationCompleted() != null) {
        Element replicationCompletedElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ReplicationCompleted");
        replicationCompletedElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isReplicationCompleted()).toLowerCase()));
        extensionImageElement.appendChild(replicationCompletedElement);
    }

    if (parameters.getEula() != null) {
        Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
        eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula().toString()));
        extensionImageElement.appendChild(eulaElement);
    }

    if (parameters.getPrivacyUri() != null) {
        Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PrivacyUri");
        privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
        extensionImageElement.appendChild(privacyUriElement);
    }

    if (parameters.getHomepageUri() != null) {
        Element homepageUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "HomepageUri");
        homepageUriElement.appendChild(requestDoc.createTextNode(parameters.getHomepageUri().toString()));
        extensionImageElement.appendChild(homepageUriElement);
    }

    if (parameters.isJsonExtension() != null) {
        Element isJsonExtensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IsJsonExtension");
        isJsonExtensionElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isJsonExtension()).toLowerCase()));
        extensionImageElement.appendChild(isJsonExtensionElement);
    }

    if (parameters.isDisallowMajorVersionUpgrade() != null) {
        Element disallowMajorVersionUpgradeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "DisallowMajorVersionUpgrade");
        disallowMajorVersionUpgradeElement.appendChild(requestDoc
                .createTextNode(Boolean.toString(parameters.isDisallowMajorVersionUpgrade()).toLowerCase()));
        extensionImageElement.appendChild(disallowMajorVersionUpgradeElement);
    }

    if (parameters.getSupportedOS() != null) {
        Element supportedOSElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SupportedOS");
        supportedOSElement.appendChild(requestDoc.createTextNode(parameters.getSupportedOS()));
        extensionImageElement.appendChild(supportedOSElement);
    }

    if (parameters.getCompanyName() != null) {
        Element companyNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "CompanyName");
        companyNameElement.appendChild(requestDoc.createTextNode(parameters.getCompanyName()));
        extensionImageElement.appendChild(companyNameElement);
    }

    if (parameters.getRegions() != null) {
        Element regionsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Regions");
        regionsElement.appendChild(requestDoc.createTextNode(parameters.getRegions()));
        extensionImageElement.appendChild(regionsElement);
    }

    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.ExtensionImageOperationsImpl.java

/**
* Update a new extension. It is allowed to update an extension which had
* already been registered with the same identity (i.e. combination of
* ProviderNamespace and Type) but with different version. It will fail if
* the extension to update has an identity that has not been registered
* before, or there is already an extension with the same identity and same
* version.// w w  w  .  j  a  va 2  s  . c o m
*
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine Extension Image 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 beginUpdating(ExtensionImageUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getCertificate() != null) {
        if (parameters.getCertificate().getStoreLocation() == null) {
            throw new NullPointerException("parameters.Certificate.StoreLocation");
        }
    }
    if (parameters.getExtensionEndpoints() != null) {
        if (parameters.getExtensionEndpoints().getInputEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInputEndpoints()) {
                if (inputEndpointsParameterItem.getLocalPort() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.LocalPort");
                }
                if (inputEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.Name");
                }
                if (inputEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.Protocol");
                }
            }
        }
        if (parameters.getExtensionEndpoints().getInstanceInputEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInstanceInputEndpoints()) {
                if (instanceInputEndpointsParameterItem.getLocalPort() == null) {
                    throw new NullPointerException(
                            "parameters.ExtensionEndpoints.InstanceInputEndpoints.LocalPort");
                }
                if (instanceInputEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Name");
                }
                if (instanceInputEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException(
                            "parameters.ExtensionEndpoints.InstanceInputEndpoints.Protocol");
                }
            }
        }
        if (parameters.getExtensionEndpoints().getInternalEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInternalEndpoints()) {
                if (internalEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InternalEndpoints.Name");
                }
                if (internalEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InternalEndpoints.Protocol");
                }
            }
        }
    }
    if (parameters.getLocalResources() != null) {
        for (ExtensionLocalResourceConfiguration localResourcesParameterItem : parameters.getLocalResources()) {
            if (localResourcesParameterItem.getName() == null) {
                throw new NullPointerException("parameters.LocalResources.Name");
            }
        }
    }
    if (parameters.getProviderNameSpace() == null) {
        throw new NullPointerException("parameters.ProviderNameSpace");
    }
    if (parameters.getType() == null) {
        throw new NullPointerException("parameters.Type");
    }
    if (parameters.getVersion() == null) {
        throw new NullPointerException("parameters.Version");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingAsync", 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/extensions";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("action=update");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/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 extensionImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ExtensionImage");
    requestDoc.appendChild(extensionImageElement);

    Element providerNameSpaceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ProviderNameSpace");
    providerNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getProviderNameSpace()));
    extensionImageElement.appendChild(providerNameSpaceElement);

    Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type");
    typeElement.appendChild(requestDoc.createTextNode(parameters.getType()));
    extensionImageElement.appendChild(typeElement);

    Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version");
    versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion()));
    extensionImageElement.appendChild(versionElement);

    if (parameters.getLabel() != null) {
        Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
        labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
        extensionImageElement.appendChild(labelElement);
    }

    if (parameters.getHostingResources() != null) {
        Element hostingResourcesElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostingResources");
        hostingResourcesElement.appendChild(requestDoc.createTextNode(parameters.getHostingResources()));
        extensionImageElement.appendChild(hostingResourcesElement);
    }

    if (parameters.getMediaLink() != null) {
        Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MediaLink");
        mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLink().toString()));
        extensionImageElement.appendChild(mediaLinkElement);
    }

    if (parameters.getCertificate() != null) {
        Element certificateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Certificate");
        extensionImageElement.appendChild(certificateElement);

        Element storeLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "StoreLocation");
        storeLocationElement
                .appendChild(requestDoc.createTextNode(parameters.getCertificate().getStoreLocation()));
        certificateElement.appendChild(storeLocationElement);

        if (parameters.getCertificate().getStoreName() != null) {
            Element storeNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "StoreName");
            storeNameElement.appendChild(requestDoc.createTextNode(parameters.getCertificate().getStoreName()));
            certificateElement.appendChild(storeNameElement);
        }

        if (parameters.getCertificate().isThumbprintRequired() != null) {
            Element thumbprintRequiredElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintRequired");
            thumbprintRequiredElement.appendChild(requestDoc.createTextNode(
                    Boolean.toString(parameters.getCertificate().isThumbprintRequired()).toLowerCase()));
            certificateElement.appendChild(thumbprintRequiredElement);
        }

        if (parameters.getCertificate().getThumbprintAlgorithm() != null) {
            Element thumbprintAlgorithmElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm");
            thumbprintAlgorithmElement.appendChild(
                    requestDoc.createTextNode(parameters.getCertificate().getThumbprintAlgorithm()));
            certificateElement.appendChild(thumbprintAlgorithmElement);
        }
    }

    if (parameters.getExtensionEndpoints() != null) {
        Element endpointsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Endpoints");
        extensionImageElement.appendChild(endpointsElement);

        if (parameters.getExtensionEndpoints().getInputEndpoints() != null) {
            if (parameters.getExtensionEndpoints().getInputEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInputEndpoints())
                            .isInitialized()) {
                Element inputEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints");
                for (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsItem : parameters
                        .getExtensionEndpoints().getInputEndpoints()) {
                    Element inputEndpointElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                    inputEndpointsSequenceElement.appendChild(inputEndpointElement);

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

                    Element protocolElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getProtocol()));
                    inputEndpointElement.appendChild(protocolElement);

                    Element portElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                    portElement.appendChild(
                            requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort())));
                    inputEndpointElement.appendChild(portElement);

                    Element localPortElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                    localPortElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLocalPort()));
                    inputEndpointElement.appendChild(localPortElement);
                }
                endpointsElement.appendChild(inputEndpointsSequenceElement);
            }
        }

        if (parameters.getExtensionEndpoints().getInternalEndpoints() != null) {
            if (parameters.getExtensionEndpoints().getInternalEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInternalEndpoints())
                            .isInitialized()) {
                Element internalEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InternalEndpoints");
                for (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsItem : parameters
                        .getExtensionEndpoints().getInternalEndpoints()) {
                    Element internalEndpointElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InternalEndpoint");
                    internalEndpointsSequenceElement.appendChild(internalEndpointElement);

                    Element nameElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    nameElement2.appendChild(requestDoc.createTextNode(internalEndpointsItem.getName()));
                    internalEndpointElement.appendChild(nameElement2);

                    Element protocolElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement2
                            .appendChild(requestDoc.createTextNode(internalEndpointsItem.getProtocol()));
                    internalEndpointElement.appendChild(protocolElement2);

                    Element portElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                    portElement2.appendChild(
                            requestDoc.createTextNode(Integer.toString(internalEndpointsItem.getPort())));
                    internalEndpointElement.appendChild(portElement2);
                }
                endpointsElement.appendChild(internalEndpointsSequenceElement);
            }
        }

        if (parameters.getExtensionEndpoints().getInstanceInputEndpoints() != null) {
            if (parameters.getExtensionEndpoints()
                    .getInstanceInputEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInstanceInputEndpoints())
                            .isInitialized()) {
                Element instanceInputEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InstanceInputEndpoints");
                for (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsItem : parameters
                        .getExtensionEndpoints().getInstanceInputEndpoints()) {
                    Element instanceInputEndpointElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "InstanceInputEndpoint");
                    instanceInputEndpointsSequenceElement.appendChild(instanceInputEndpointElement);

                    Element nameElement3 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    nameElement3.appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getName()));
                    instanceInputEndpointElement.appendChild(nameElement3);

                    Element protocolElement3 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement3
                            .appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getProtocol()));
                    instanceInputEndpointElement.appendChild(protocolElement3);

                    Element localPortElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                    localPortElement2
                            .appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getLocalPort()));
                    instanceInputEndpointElement.appendChild(localPortElement2);

                    Element fixedPortMinElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "FixedPortMin");
                    fixedPortMinElement.appendChild(requestDoc
                            .createTextNode(Integer.toString(instanceInputEndpointsItem.getFixedPortMin())));
                    instanceInputEndpointElement.appendChild(fixedPortMinElement);

                    Element fixedPortMaxElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "FixedPortMax");
                    fixedPortMaxElement.appendChild(requestDoc
                            .createTextNode(Integer.toString(instanceInputEndpointsItem.getFixedPortMax())));
                    instanceInputEndpointElement.appendChild(fixedPortMaxElement);
                }
                endpointsElement.appendChild(instanceInputEndpointsSequenceElement);
            }
        }
    }

    if (parameters.getPublicConfigurationSchema() != null) {
        Element publicConfigurationSchemaElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicConfigurationSchema");
        publicConfigurationSchemaElement.appendChild(
                requestDoc.createTextNode(Base64.encode(parameters.getPublicConfigurationSchema().getBytes())));
        extensionImageElement.appendChild(publicConfigurationSchemaElement);
    }

    if (parameters.getPrivateConfigurationSchema() != null) {
        Element privateConfigurationSchemaElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PrivateConfigurationSchema");
        privateConfigurationSchemaElement.appendChild(requestDoc
                .createTextNode(Base64.encode(parameters.getPrivateConfigurationSchema().getBytes())));
        extensionImageElement.appendChild(privateConfigurationSchemaElement);
    }

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        extensionImageElement.appendChild(descriptionElement);
    }

    if (parameters.getPublisherName() != null) {
        Element publisherNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublisherName");
        publisherNameElement.appendChild(requestDoc.createTextNode(parameters.getPublisherName()));
        extensionImageElement.appendChild(publisherNameElement);
    }

    if (parameters.getPublishedDate() != null) {
        Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublishedDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        publishedDateElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
        extensionImageElement.appendChild(publishedDateElement);
    }

    if (parameters.getLocalResources() != null) {
        Element localResourcesSequenceElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalResources");
        for (ExtensionLocalResourceConfiguration localResourcesItem : parameters.getLocalResources()) {
            Element localResourceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalResource");
            localResourcesSequenceElement.appendChild(localResourceElement);

            Element nameElement4 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Name");
            nameElement4.appendChild(requestDoc.createTextNode(localResourcesItem.getName()));
            localResourceElement.appendChild(nameElement4);

            if (localResourcesItem.getSizeInMB() != null) {
                Element sizeInMBElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SizeInMB");
                sizeInMBElement.appendChild(
                        requestDoc.createTextNode(Integer.toString(localResourcesItem.getSizeInMB())));
                localResourceElement.appendChild(sizeInMBElement);
            }
        }
        extensionImageElement.appendChild(localResourcesSequenceElement);
    }

    if (parameters.isBlockRoleUponFailure() != null) {
        Element blockRoleUponFailureElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "BlockRoleUponFailure");
        blockRoleUponFailureElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isBlockRoleUponFailure()).toLowerCase()));
        extensionImageElement.appendChild(blockRoleUponFailureElement);
    }

    if (parameters.isInternalExtension() != null) {
        Element isInternalExtensionElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "IsInternalExtension");
        isInternalExtensionElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isInternalExtension()).toLowerCase()));
        extensionImageElement.appendChild(isInternalExtensionElement);
    }

    if (parameters.getSampleConfig() != null) {
        Element sampleConfigElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SampleConfig");
        sampleConfigElement
                .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getSampleConfig().getBytes())));
        extensionImageElement.appendChild(sampleConfigElement);
    }

    if (parameters.isReplicationCompleted() != null) {
        Element replicationCompletedElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ReplicationCompleted");
        replicationCompletedElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isReplicationCompleted()).toLowerCase()));
        extensionImageElement.appendChild(replicationCompletedElement);
    }

    if (parameters.getEula() != null) {
        Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
        eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula().toString()));
        extensionImageElement.appendChild(eulaElement);
    }

    if (parameters.getPrivacyUri() != null) {
        Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PrivacyUri");
        privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
        extensionImageElement.appendChild(privacyUriElement);
    }

    if (parameters.getHomepageUri() != null) {
        Element homepageUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "HomepageUri");
        homepageUriElement.appendChild(requestDoc.createTextNode(parameters.getHomepageUri().toString()));
        extensionImageElement.appendChild(homepageUriElement);
    }

    if (parameters.isJsonExtension() != null) {
        Element isJsonExtensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IsJsonExtension");
        isJsonExtensionElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isJsonExtension()).toLowerCase()));
        extensionImageElement.appendChild(isJsonExtensionElement);
    }

    if (parameters.isDisallowMajorVersionUpgrade() != null) {
        Element disallowMajorVersionUpgradeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "DisallowMajorVersionUpgrade");
        disallowMajorVersionUpgradeElement.appendChild(requestDoc
                .createTextNode(Boolean.toString(parameters.isDisallowMajorVersionUpgrade()).toLowerCase()));
        extensionImageElement.appendChild(disallowMajorVersionUpgradeElement);
    }

    if (parameters.getSupportedOS() != null) {
        Element supportedOSElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SupportedOS");
        supportedOSElement.appendChild(requestDoc.createTextNode(parameters.getSupportedOS()));
        extensionImageElement.appendChild(supportedOSElement);
    }

    if (parameters.getCompanyName() != null) {
        Element companyNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "CompanyName");
        companyNameElement.appendChild(requestDoc.createTextNode(parameters.getCompanyName()));
        extensionImageElement.appendChild(companyNameElement);
    }

    if (parameters.getRegions() != null) {
        Element regionsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Regions");
        regionsElement.appendChild(requestDoc.createTextNode(parameters.getRegions()));
        extensionImageElement.appendChild(regionsElement);
    }

    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.sql.DatabaseOperationsImpl.java

/**
* Updates the properties of an Azure SQL Database.
*
* @param serverName Required. The name of the Azure SQL Database Server
* where the database is hosted.//from w w  w.j  a  v  a 2 s  . co  m
* @param databaseName Required. The name of the Azure SQL Database to be
* updated.
* @param parameters Required. The parameters for the Update Database
* 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 Contains the response from a request to Update Database.
*/
@Override
public DatabaseUpdateResponse update(String serverName, String databaseName,
        DatabaseUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEdition() == null) {
        throw new NullPointerException("parameters.Edition");
    }

    // 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("serverName", serverName);
        tracingParameters.put("databaseName", databaseName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", 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/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "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
    HttpPut httpRequest = new HttpPut(url);

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

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

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

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        serviceResourceElement.appendChild(nameElement);
    }

    Element editionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Edition");
    editionElement.appendChild(requestDoc.createTextNode(parameters.getEdition()));
    serviceResourceElement.appendChild(editionElement);

    if (parameters.getMaximumDatabaseSizeInGB() != null) {
        Element maxSizeGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeGB");
        maxSizeGBElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getMaximumDatabaseSizeInGB())));
        serviceResourceElement.appendChild(maxSizeGBElement);
    }

    if (parameters.getMaximumDatabaseSizeInBytes() != null) {
        Element maxSizeBytesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeBytes");
        maxSizeBytesElement.appendChild(
                requestDoc.createTextNode(Long.toString(parameters.getMaximumDatabaseSizeInBytes())));
        serviceResourceElement.appendChild(maxSizeBytesElement);
    }

    if (parameters.getServiceObjectiveId() != null) {
        Element serviceObjectiveIdElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
        serviceObjectiveIdElement.appendChild(requestDoc.createTextNode(parameters.getServiceObjectiveId()));
        serviceResourceElement.appendChild(serviceObjectiveIdElement);
    }

    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
        DatabaseUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseUpdateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                Database serviceResourceInstance = new Database();
                result.setDatabase(serviceResourceInstance);

                Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Id");
                if (idElement != null) {
                    int idInstance;
                    idInstance = DatatypeConverter.parseInt(idElement.getTextContent());
                    serviceResourceInstance.setId(idInstance);
                }

                Element editionElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Edition");
                if (editionElement2 != null) {
                    String editionInstance;
                    editionInstance = editionElement2.getTextContent();
                    serviceResourceInstance.setEdition(editionInstance);
                }

                Element maxSizeGBElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeGB");
                if (maxSizeGBElement2 != null) {
                    int maxSizeGBInstance;
                    maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance);
                }

                Element maxSizeBytesElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes");
                if (maxSizeBytesElement2 != null) {
                    long maxSizeBytesInstance;
                    maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance);
                }

                Element collationNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CollationName");
                if (collationNameElement != null) {
                    String collationNameInstance;
                    collationNameInstance = collationNameElement.getTextContent();
                    serviceResourceInstance.setCollationName(collationNameInstance);
                }

                Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CreationDate");
                if (creationDateElement != null) {
                    Calendar creationDateInstance;
                    creationDateInstance = DatatypeConverter
                            .parseDateTime(creationDateElement.getTextContent());
                    serviceResourceInstance.setCreationDate(creationDateInstance);
                }

                Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsFederationRoot");
                if (isFederationRootElement != null) {
                    boolean isFederationRootInstance;
                    isFederationRootInstance = DatatypeConverter
                            .parseBoolean(isFederationRootElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsFederationRoot(isFederationRootInstance);
                }

                Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsSystemObject");
                if (isSystemObjectElement != null) {
                    boolean isSystemObjectInstance;
                    isSystemObjectInstance = DatatypeConverter
                            .parseBoolean(isSystemObjectElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsSystemObject(isSystemObjectInstance);
                }

                Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SizeMB");
                if (sizeMBElement != null) {
                    String sizeMBInstance;
                    sizeMBInstance = sizeMBElement.getTextContent();
                    serviceResourceInstance.setSizeMB(sizeMBInstance);
                }

                Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorCode");
                if (serviceObjectiveAssignmentErrorCodeElement != null) {
                    String serviceObjectiveAssignmentErrorCodeInstance;
                    serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(
                            serviceObjectiveAssignmentErrorCodeInstance);
                }

                Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorDescription");
                if (serviceObjectiveAssignmentErrorDescriptionElement != null) {
                    String serviceObjectiveAssignmentErrorDescriptionInstance;
                    serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(
                            serviceObjectiveAssignmentErrorDescriptionInstance);
                }

                Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentState");
                if (serviceObjectiveAssignmentStateElement != null) {
                    String serviceObjectiveAssignmentStateInstance;
                    serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement
                            .getTextContent();
                    serviceResourceInstance
                            .setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance);
                }

                Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentStateDescription");
                if (serviceObjectiveAssignmentStateDescriptionElement != null) {
                    String serviceObjectiveAssignmentStateDescriptionInstance;
                    serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(
                            serviceObjectiveAssignmentStateDescriptionInstance);
                }

                Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentSuccessDate");
                if (serviceObjectiveAssignmentSuccessDateElement != null) {
                    String serviceObjectiveAssignmentSuccessDateInstance;
                    serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(
                            serviceObjectiveAssignmentSuccessDateInstance);
                }

                Element serviceObjectiveIdElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
                if (serviceObjectiveIdElement2 != null) {
                    String serviceObjectiveIdInstance;
                    serviceObjectiveIdInstance = serviceObjectiveIdElement2.getTextContent();
                    serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance);
                }

                Element assignedServiceObjectiveIdElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "AssignedServiceObjectiveId");
                if (assignedServiceObjectiveIdElement != null) {
                    String assignedServiceObjectiveIdInstance;
                    assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.getTextContent();
                    serviceResourceInstance.setAssignedServiceObjectiveId(assignedServiceObjectiveIdInstance);
                }

                Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "RecoveryPeriodStartDate");
                if (recoveryPeriodStartDateElement != null
                        && recoveryPeriodStartDateElement.getTextContent() != null
                        && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) {
                    Calendar recoveryPeriodStartDateInstance;
                    recoveryPeriodStartDateInstance = DatatypeConverter
                            .parseDateTime(recoveryPeriodStartDateElement.getTextContent());
                    serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance);
                }

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

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

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

        }
        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.sql.DatabaseOperationsImpl.java

/**
* Creates a database in an Azure SQL Database Server.
*
* @param serverName Required. The name of the Azure SQL Database Server
* where the database will be created./*from  w  ww.j a  v a2  s .  c  o  m*/
* @param parameters Required. The parameters for the create database
* 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 Represents the response to a create database request from the
* service.
*/
@Override
public DatabaseCreateResponse create(String serverName, DatabaseCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases";
    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", "2012-03-01");

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

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

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

    if (parameters.getEdition() != null) {
        Element editionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Edition");
        editionElement.appendChild(requestDoc.createTextNode(parameters.getEdition()));
        serviceResourceElement.appendChild(editionElement);
    }

    if (parameters.getMaximumDatabaseSizeInGB() != null) {
        Element maxSizeGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeGB");
        maxSizeGBElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getMaximumDatabaseSizeInGB())));
        serviceResourceElement.appendChild(maxSizeGBElement);
    }

    if (parameters.getCollationName() != null) {
        Element collationNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "CollationName");
        collationNameElement.appendChild(requestDoc.createTextNode(parameters.getCollationName()));
        serviceResourceElement.appendChild(collationNameElement);
    }

    if (parameters.getMaximumDatabaseSizeInBytes() != null) {
        Element maxSizeBytesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeBytes");
        maxSizeBytesElement.appendChild(
                requestDoc.createTextNode(Long.toString(parameters.getMaximumDatabaseSizeInBytes())));
        serviceResourceElement.appendChild(maxSizeBytesElement);
    }

    if (parameters.getServiceObjectiveId() != null) {
        Element serviceObjectiveIdElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
        serviceObjectiveIdElement.appendChild(requestDoc.createTextNode(parameters.getServiceObjectiveId()));
        serviceResourceElement.appendChild(serviceObjectiveIdElement);
    }

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

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

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

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                Database serviceResourceInstance = new Database();
                result.setDatabase(serviceResourceInstance);

                Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Id");
                if (idElement != null) {
                    int idInstance;
                    idInstance = DatatypeConverter.parseInt(idElement.getTextContent());
                    serviceResourceInstance.setId(idInstance);
                }

                Element editionElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Edition");
                if (editionElement2 != null) {
                    String editionInstance;
                    editionInstance = editionElement2.getTextContent();
                    serviceResourceInstance.setEdition(editionInstance);
                }

                Element maxSizeGBElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeGB");
                if (maxSizeGBElement2 != null) {
                    int maxSizeGBInstance;
                    maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance);
                }

                Element maxSizeBytesElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes");
                if (maxSizeBytesElement2 != null) {
                    long maxSizeBytesInstance;
                    maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance);
                }

                Element collationNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CollationName");
                if (collationNameElement2 != null) {
                    String collationNameInstance;
                    collationNameInstance = collationNameElement2.getTextContent();
                    serviceResourceInstance.setCollationName(collationNameInstance);
                }

                Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CreationDate");
                if (creationDateElement != null) {
                    Calendar creationDateInstance;
                    creationDateInstance = DatatypeConverter
                            .parseDateTime(creationDateElement.getTextContent());
                    serviceResourceInstance.setCreationDate(creationDateInstance);
                }

                Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsFederationRoot");
                if (isFederationRootElement != null) {
                    boolean isFederationRootInstance;
                    isFederationRootInstance = DatatypeConverter
                            .parseBoolean(isFederationRootElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsFederationRoot(isFederationRootInstance);
                }

                Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsSystemObject");
                if (isSystemObjectElement != null) {
                    boolean isSystemObjectInstance;
                    isSystemObjectInstance = DatatypeConverter
                            .parseBoolean(isSystemObjectElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsSystemObject(isSystemObjectInstance);
                }

                Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SizeMB");
                if (sizeMBElement != null) {
                    String sizeMBInstance;
                    sizeMBInstance = sizeMBElement.getTextContent();
                    serviceResourceInstance.setSizeMB(sizeMBInstance);
                }

                Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorCode");
                if (serviceObjectiveAssignmentErrorCodeElement != null) {
                    String serviceObjectiveAssignmentErrorCodeInstance;
                    serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(
                            serviceObjectiveAssignmentErrorCodeInstance);
                }

                Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorDescription");
                if (serviceObjectiveAssignmentErrorDescriptionElement != null) {
                    String serviceObjectiveAssignmentErrorDescriptionInstance;
                    serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(
                            serviceObjectiveAssignmentErrorDescriptionInstance);
                }

                Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentState");
                if (serviceObjectiveAssignmentStateElement != null) {
                    String serviceObjectiveAssignmentStateInstance;
                    serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement
                            .getTextContent();
                    serviceResourceInstance
                            .setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance);
                }

                Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentStateDescription");
                if (serviceObjectiveAssignmentStateDescriptionElement != null) {
                    String serviceObjectiveAssignmentStateDescriptionInstance;
                    serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(
                            serviceObjectiveAssignmentStateDescriptionInstance);
                }

                Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentSuccessDate");
                if (serviceObjectiveAssignmentSuccessDateElement != null) {
                    String serviceObjectiveAssignmentSuccessDateInstance;
                    serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(
                            serviceObjectiveAssignmentSuccessDateInstance);
                }

                Element serviceObjectiveIdElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
                if (serviceObjectiveIdElement2 != null) {
                    String serviceObjectiveIdInstance;
                    serviceObjectiveIdInstance = serviceObjectiveIdElement2.getTextContent();
                    serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance);
                }

                Element assignedServiceObjectiveIdElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "AssignedServiceObjectiveId");
                if (assignedServiceObjectiveIdElement != null) {
                    String assignedServiceObjectiveIdInstance;
                    assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.getTextContent();
                    serviceResourceInstance.setAssignedServiceObjectiveId(assignedServiceObjectiveIdInstance);
                }

                Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "RecoveryPeriodStartDate");
                if (recoveryPeriodStartDateElement != null
                        && recoveryPeriodStartDateElement.getTextContent() != null
                        && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) {
                    Calendar recoveryPeriodStartDateInstance;
                    recoveryPeriodStartDateInstance = DatatypeConverter
                            .parseDateTime(recoveryPeriodStartDateElement.getTextContent());
                    serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance);
                }

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

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

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

        }
        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.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/* w  w  w  .  ja va2s .  c o m*/
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

From source file:org.gvnix.web.exception.handler.roo.addon.addon.WebExceptionHandlerOperationsImpl.java

/**
 * Update the webmvc-config.xml with the new Exception.
 * /*  w w w  . j a va2  s  .  c o  m*/
 * @param exceptionName Exception Name to Handle.
 * @return {@link String} The exceptionViewName to create the .jspx view.
 */
protected String updateWebMvcConfig(String exceptionName) {

    String webXmlPath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            WEB_MVC_CONFIG);
    Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND);

    MutableFile webXmlMutableFile = null;
    Document webXml;

    try {
        webXmlMutableFile = fileManager.updateFile(webXmlPath);
        webXml = XmlUtils.getDocumentBuilder().parse(webXmlMutableFile.getInputStream());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Element root = webXml.getDocumentElement();

    Element simpleMappingException = XmlUtils
            .findFirstElement(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root);

    Element exceptionResolver = XmlUtils.findFirstElement(RESOLVER_BEAN_MESSAGE
            + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root);

    boolean updateMappings = false;
    boolean updateController = false;

    // View name for this Exception.
    String exceptionViewName;

    if (exceptionResolver != null) {
        exceptionViewName = exceptionResolver.getTextContent();
    } else {
        updateMappings = true;
        exceptionViewName = getExceptionViewName(exceptionName);
    }

    Element newExceptionMapping;

    // Exception Mapping
    newExceptionMapping = webXml.createElement("prop");
    newExceptionMapping.setAttribute("key", exceptionName);

    Validate.isTrue(exceptionViewName != null,
            "Can't create the view for the:\t" + exceptionName + " Exception.");

    newExceptionMapping.setTextContent(exceptionViewName);

    if (updateMappings) {
        simpleMappingException.appendChild(newExceptionMapping);
    }

    // Exception Controller
    Element newExceptionView = XmlUtils
            .findFirstElement("/beans/view-controller[@path='/" + exceptionViewName + "']", root);

    if (newExceptionView == null) {
        updateController = true;
    }

    newExceptionView = webXml.createElementNS("http://www.springframework.org/schema/mvc", "view-controller");
    newExceptionView.setPrefix("mvc");

    newExceptionView.setAttribute("path", "/" + exceptionViewName);

    if (updateController) {
        root.appendChild(newExceptionView);
    }

    if (updateMappings || updateController) {
        XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml);
    }

    return exceptionViewName;
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method takes the SOAP request that come from the WSP and removes
 * the elements that need to be removed per the SAML Profiles spec.
 * /* w w w . j a  va 2  s  .  co  m*/
 * @param samlSession
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPRequest(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 3 of 5: Process SOAP Request");
    try {
        String expression = "/S:Envelope/S:Header/paos:Request";
        Document dom = authnState.getSoapRequestDom();
        Node node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

        if (node != null) {
            // Save the response consumer URL to samlSession
            String responseConsumerURL = node.getAttributes().getNamedItem("responseConsumerURL")
                    .getTextContent();
            logger.debug("Loaded response consumer URL {}", responseConsumerURL);
            authnState.setResponseConsumerURL(responseConsumerURL);
            // Save the PAOS MessageID, if present
            Node paosMessageID = node.getAttributes().getNamedItem("messageID");

            if (paosMessageID != null)
                authnState.setPaosMessageID(paosMessageID.getTextContent());
            else
                authnState.setPaosMessageID(null);

            // This removes the paos:Request node
            node.getParentNode().removeChild(node);

            // Retrieve the RelayState cookie for sending it back to the WSP with the SOAP Response
            expression = "/S:Envelope/S:Header/ecp:RelayState";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            if (node != null) {
                Element relayStateElement = (Element) node;
                authnState.setRelayStateElement(relayStateElement);
                node.getParentNode().removeChild(node);
            }

            // On to the ecp:Request for removal
            expression = "/S:Envelope/S:Header/ecp:Request";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            node.getParentNode().removeChild(node);

            // Now add some namespace bindings to the SOAP Header
            expression = "/S:Envelope/S:Header";
            Element soapHeader = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

            // Add new elements to S:Header
            Element newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sbf"), "sbf:Framework");
            newElement.setAttribute("version", "2.0");
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sb"), "sb:Sender");
            newElement.setAttribute("providerID", samlSession.getPortalEntityID());
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:MessageID");
            String messageID = generateMessageID();
            newElement.setTextContent(messageID);
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:Action");
            newElement.setTextContent("urn:liberty:ssos:2006-08:AuthnRequest");
            soapHeader.appendChild(newElement);

            // This is the wsse:Security element 
            Element securityElement = dom.createElementNS(
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "wsse:Security");
            securityElement.setAttribute(soapHeader.getPrefix() + ":mustUnderstand", "1");
            Element createdElement = dom.createElement("wsu:Created");
            // The examples use Zulu time zone, not local
            TimeZone zuluTimeZone = TimeZone.getTimeZone("Zulu");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
            sdf.setTimeZone(zuluTimeZone);
            createdElement.setTextContent(sdf.format(new Date()));
            newElement = dom.createElementNS(
                    "http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
                    "wsu:Timestamp");
            newElement.appendChild(createdElement);
            securityElement.appendChild(newElement);
            // Finally, insert the original SAML assertion
            Node samlAssertionNode = dom.importNode(samlSession.getSamlAssertionDom().getDocumentElement(),
                    true);
            securityElement.appendChild(samlAssertionNode);
            soapHeader.appendChild(securityElement);

            // Store the modified SOAP Request in the SAML Session
            String modifiedSOAPRequest = writeDomToString(dom);
            authnState.setModifiedSOAPRequest(modifiedSOAPRequest);
            logger.debug("Completed processing of SOAP request");
            return true;
        }
        logger.debug("Failed to process SOAP request using expression {}", expression);
    } catch (XPathExpressionException ex) {
        logger.error("Programming error.  Invalid XPath expression.", ex);
        throw new DelegatedAuthenticationRuntimeException("Programming error.  Invalid XPath expression.", ex);
    }
    return false;
}

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

/**
* The Add Disk operation adds a disk to the user image repository. The disk
* can be an operating system disk or a data disk.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for
* more information)/*from ww  w. jav  a2  s .co  m*/
*
* @param name Required. The name of the disk being updated.
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine Disk 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 beginUpdatingDisk(String name, VirtualMachineDiskUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (name == null) {
        throw new NullPointerException("name");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("name", name);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingDiskAsync", 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/disks/";
    url = url + URLEncoder.encode(name, "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
    HttpPut httpRequest = new HttpPut(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 diskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Disk");
    requestDoc.appendChild(diskElement);

    if (parameters.isHasOperatingSystem() != null) {
        Element hasOperatingSystemElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "HasOperatingSystem");
        hasOperatingSystemElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isHasOperatingSystem()).toLowerCase()));
        diskElement.appendChild(hasOperatingSystemElement);
    }

    if (parameters.getOperatingSystemType() != null) {
        Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS");
        osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType()));
        diskElement.appendChild(osElement);
    }

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

    if (parameters.getMediaLinkUri() != null) {
        Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MediaLink");
        mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString()));
        diskElement.appendChild(mediaLinkElement);
    }

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

    if (parameters.getResizedSizeInGB() != null) {
        Element resizedSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ResizedSizeInGB");
        resizedSizeInGBElement
                .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getResizedSizeInGB())));
        diskElement.appendChild(resizedSizeInGBElement);
    }

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