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.websites.WebSiteOperationsImpl.java

/**
* Updates a backup schedule for a site.//from   w ww  .  ja v a  2s . c  om
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param backupRequest Required. A backup schedule specification.
* @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 updateBackupConfiguration(String webSpaceName, String webSiteName,
        BackupRequest backupRequest)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (backupRequest == null) {
        throw new NullPointerException("backupRequest");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("webSiteName", webSiteName);
        tracingParameters.put("backupRequest", backupRequest);
        CloudTracing.enter(invocationId, this, "updateBackupConfigurationAsync", 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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    url = url + "/backup/config";
    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-04-01");

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

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

    if (backupRequest.getBackupSchedule() != null) {
        Element backupScheduleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "BackupSchedule");
        backupRequestElement.appendChild(backupScheduleElement);

        Element frequencyIntervalElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyInterval");
        frequencyIntervalElement.appendChild(requestDoc
                .createTextNode(Integer.toString(backupRequest.getBackupSchedule().getFrequencyInterval())));
        backupScheduleElement.appendChild(frequencyIntervalElement);

        if (backupRequest.getBackupSchedule().getFrequencyUnit() != null) {
            Element frequencyUnitElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyUnit");
            frequencyUnitElement.appendChild(
                    requestDoc.createTextNode(backupRequest.getBackupSchedule().getFrequencyUnit().toString()));
            backupScheduleElement.appendChild(frequencyUnitElement);
        }

        Element keepAtLeastOneBackupElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "KeepAtLeastOneBackup");
        keepAtLeastOneBackupElement.appendChild(requestDoc.createTextNode(
                Boolean.toString(backupRequest.getBackupSchedule().isKeepAtLeastOneBackup()).toLowerCase()));
        backupScheduleElement.appendChild(keepAtLeastOneBackupElement);

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

        Element retentionPeriodInDaysElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "RetentionPeriodInDays");
        retentionPeriodInDaysElement.appendChild(requestDoc.createTextNode(
                Integer.toString(backupRequest.getBackupSchedule().getRetentionPeriodInDays())));
        backupScheduleElement.appendChild(retentionPeriodInDaysElement);

        if (backupRequest.getBackupSchedule().getStartTime() != null) {
            Element startTimeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "StartTime");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
            simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
            startTimeElement.appendChild(requestDoc.createTextNode(
                    simpleDateFormat2.format(backupRequest.getBackupSchedule().getStartTime().getTime())));
            backupScheduleElement.appendChild(startTimeElement);
        }
    }

    if (backupRequest.getDatabases() != null) {
        if (backupRequest.getDatabases() instanceof LazyCollection == false
                || ((LazyCollection) backupRequest.getDatabases()).isInitialized()) {
            Element databasesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Databases");
            for (DatabaseBackupSetting databasesItem : backupRequest.getDatabases()) {
                Element databaseBackupSettingElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting");
                databasesSequenceElement.appendChild(databaseBackupSettingElement);

                if (databasesItem.getConnectionString() != null) {
                    Element connectionStringElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionString");
                    connectionStringElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionString()));
                    databaseBackupSettingElement.appendChild(connectionStringElement);
                }

                if (databasesItem.getConnectionStringName() != null) {
                    Element connectionStringNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "ConnectionStringName");
                    connectionStringNameElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionStringName()));
                    databaseBackupSettingElement.appendChild(connectionStringNameElement);
                }

                if (databasesItem.getDatabaseType() != null) {
                    Element databaseTypeElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseType");
                    databaseTypeElement.appendChild(requestDoc.createTextNode(databasesItem.getDatabaseType()));
                    databaseBackupSettingElement.appendChild(databaseTypeElement);
                }

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

    if (backupRequest.isEnabled() != null) {
        Element enabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Enabled");
        enabledElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(backupRequest.isEnabled()).toLowerCase()));
        backupRequestElement.appendChild(enabledElement);
    }

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

    if (backupRequest.getStorageAccountUrl() != null) {
        Element storageAccountUrlElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "StorageAccountUrl");
        storageAccountUrlElement.appendChild(requestDoc.createTextNode(backupRequest.getStorageAccountUrl()));
        backupRequestElement.appendChild(storageAccountUrlElement);
    }

    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.websites.WebSiteOperationsImpl.java

/**
* Creates an association to a hybrid connection for a web site.
*
* @param webSpaceName Required. The name of the web space.
* @param siteName Required. The name of the web site.
* @param parameters Required. Parameters supplied to the Create Hybrid
* Connection operation./*from w w w . jav a2  s .  c o m*/
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The Create Hybrid Connection operation response.
*/
@Override
public HybridConnectionCreateResponse createHybridConnection(String webSpaceName, String siteName,
        HybridConnectionCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (siteName == null) {
        throw new NullPointerException("siteName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getBiztalkUri() == null) {
        throw new NullPointerException("parameters.BiztalkUri");
    }
    if (parameters.getEntityConnectionString() == null) {
        throw new NullPointerException("parameters.EntityConnectionString");
    }
    if (parameters.getEntityName() == null) {
        throw new NullPointerException("parameters.EntityName");
    }
    if (parameters.getHostname() == null) {
        throw new NullPointerException("parameters.Hostname");
    }
    if (parameters.getResourceConnectionString() == null) {
        throw new NullPointerException("parameters.ResourceConnectionString");
    }
    if (parameters.getResourceType() == null) {
        throw new NullPointerException("parameters.ResourceType");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("siteName", siteName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createHybridConnectionAsync", 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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(siteName, "UTF-8");
    url = url + "/hybridconnection";
    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-04-01");

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

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

    Element biztalkUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "BiztalkUri");
    biztalkUriElement.appendChild(requestDoc.createTextNode(parameters.getBiztalkUri()));
    relayServiceConnectionEntityElement.appendChild(biztalkUriElement);

    Element entityConnectionStringElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "EntityConnectionString");
    entityConnectionStringElement
            .appendChild(requestDoc.createTextNode(parameters.getEntityConnectionString()));
    relayServiceConnectionEntityElement.appendChild(entityConnectionStringElement);

    Element entityNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EntityName");
    entityNameElement.appendChild(requestDoc.createTextNode(parameters.getEntityName()));
    relayServiceConnectionEntityElement.appendChild(entityNameElement);

    Element hostnameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Hostname");
    hostnameElement.appendChild(requestDoc.createTextNode(parameters.getHostname()));
    relayServiceConnectionEntityElement.appendChild(hostnameElement);

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

    Element resourceConnectionStringElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceConnectionString");
    resourceConnectionStringElement
            .appendChild(requestDoc.createTextNode(parameters.getResourceConnectionString()));
    relayServiceConnectionEntityElement.appendChild(resourceConnectionStringElement);

    Element resourceTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ResourceType");
    resourceTypeElement.appendChild(requestDoc.createTextNode(parameters.getResourceType()));
    relayServiceConnectionEntityElement.appendChild(resourceTypeElement);

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

            Element relayServiceConnectionEntityElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "RelayServiceConnectionEntity");
            if (relayServiceConnectionEntityElement2 != null) {
                HybridConnection hybridConnectionInstance = new HybridConnection();
                result.setHybridConnection(hybridConnectionInstance);

                Element entityNameElement2 = XmlUtility.getElementByTagNameNS(
                        relayServiceConnectionEntityElement2, "http://schemas.microsoft.com/windowsazure",
                        "EntityName");
                if (entityNameElement2 != null) {
                    String entityNameInstance;
                    entityNameInstance = entityNameElement2.getTextContent();
                    hybridConnectionInstance.setEntityName(entityNameInstance);
                }

                Element entityConnectionStringElement2 = XmlUtility.getElementByTagNameNS(
                        relayServiceConnectionEntityElement2, "http://schemas.microsoft.com/windowsazure",
                        "EntityConnectionString");
                if (entityConnectionStringElement2 != null) {
                    String entityConnectionStringInstance;
                    entityConnectionStringInstance = entityConnectionStringElement2.getTextContent();
                    hybridConnectionInstance.setEntityConnectionString(entityConnectionStringInstance);
                }

                Element resourceTypeElement2 = XmlUtility.getElementByTagNameNS(
                        relayServiceConnectionEntityElement2, "http://schemas.microsoft.com/windowsazure",
                        "ResourceType");
                if (resourceTypeElement2 != null) {
                    String resourceTypeInstance;
                    resourceTypeInstance = resourceTypeElement2.getTextContent();
                    hybridConnectionInstance.setResourceType(resourceTypeInstance);
                }

                Element resourceConnectionStringElement2 = XmlUtility.getElementByTagNameNS(
                        relayServiceConnectionEntityElement2, "http://schemas.microsoft.com/windowsazure",
                        "ResourceConnectionString");
                if (resourceConnectionStringElement2 != null) {
                    String resourceConnectionStringInstance;
                    resourceConnectionStringInstance = resourceConnectionStringElement2.getTextContent();
                    hybridConnectionInstance.setResourceConnectionString(resourceConnectionStringInstance);
                }

                Element hostnameElement2 = XmlUtility.getElementByTagNameNS(
                        relayServiceConnectionEntityElement2, "http://schemas.microsoft.com/windowsazure",
                        "Hostname");
                if (hostnameElement2 != null) {
                    String hostnameInstance;
                    hostnameInstance = hostnameElement2.getTextContent();
                    hybridConnectionInstance.setHostname(hostnameInstance);
                }

                Element portElement2 = XmlUtility.getElementByTagNameNS(relayServiceConnectionEntityElement2,
                        "http://schemas.microsoft.com/windowsazure", "Port");
                if (portElement2 != null) {
                    int portInstance;
                    portInstance = DatatypeConverter.parseInt(portElement2.getTextContent());
                    hybridConnectionInstance.setPort(portInstance);
                }

                Element biztalkUriElement2 = XmlUtility.getElementByTagNameNS(
                        relayServiceConnectionEntityElement2, "http://schemas.microsoft.com/windowsazure",
                        "BiztalkUri");
                if (biztalkUriElement2 != null) {
                    String biztalkUriInstance;
                    biztalkUriInstance = biztalkUriElement2.getTextContent();
                    hybridConnectionInstance.setBiztalkUri(biztalkUriInstance);
                }
            }

        }
        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.websites.WebSiteOperationsImpl.java

/**
* Scans a backup in a storage account and returns database information etc.
* Should be called before calling Restore to discover what parameters are
* needed for the restore operation.//from   w  w w. j  a v a  2  s  .  c o m
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param restoreRequest Required. A restore request.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The information gathered about a backup storaged in a storage
* account.
*/
@Override
public WebSiteRestoreDiscoverResponse discover(String webSpaceName, String webSiteName,
        RestoreRequest restoreRequest)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (restoreRequest == null) {
        throw new NullPointerException("restoreRequest");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("webSiteName", webSiteName);
        tracingParameters.put("restoreRequest", restoreRequest);
        CloudTracing.enter(invocationId, this, "discoverAsync", 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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    url = url + "/restore/discover";
    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-04-01");

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

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

    Element adjustConnectionStringsElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "AdjustConnectionStrings");
    adjustConnectionStringsElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(restoreRequest.isAdjustConnectionStrings()).toLowerCase()));
    restoreRequestElement.appendChild(adjustConnectionStringsElement);

    if (restoreRequest.getBlobName() != null) {
        Element blobNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "BlobName");
        blobNameElement.appendChild(requestDoc.createTextNode(restoreRequest.getBlobName()));
        restoreRequestElement.appendChild(blobNameElement);
    }

    if (restoreRequest.getDatabases() != null) {
        if (restoreRequest.getDatabases() instanceof LazyCollection == false
                || ((LazyCollection) restoreRequest.getDatabases()).isInitialized()) {
            Element databasesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Databases");
            for (DatabaseBackupSetting databasesItem : restoreRequest.getDatabases()) {
                Element databaseBackupSettingElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting");
                databasesSequenceElement.appendChild(databaseBackupSettingElement);

                if (databasesItem.getConnectionString() != null) {
                    Element connectionStringElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionString");
                    connectionStringElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionString()));
                    databaseBackupSettingElement.appendChild(connectionStringElement);
                }

                if (databasesItem.getConnectionStringName() != null) {
                    Element connectionStringNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "ConnectionStringName");
                    connectionStringNameElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionStringName()));
                    databaseBackupSettingElement.appendChild(connectionStringNameElement);
                }

                if (databasesItem.getDatabaseType() != null) {
                    Element databaseTypeElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseType");
                    databaseTypeElement.appendChild(requestDoc.createTextNode(databasesItem.getDatabaseType()));
                    databaseBackupSettingElement.appendChild(databaseTypeElement);
                }

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

    Element ignoreConflictingHostNamesElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "IgnoreConflictingHostNames");
    ignoreConflictingHostNamesElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(restoreRequest.isIgnoreConflictingHostNames()).toLowerCase()));
    restoreRequestElement.appendChild(ignoreConflictingHostNamesElement);

    Element overwriteElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Overwrite");
    overwriteElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(restoreRequest.isOverwrite()).toLowerCase()));
    restoreRequestElement.appendChild(overwriteElement);

    if (restoreRequest.getStorageAccountUrl() != null) {
        Element storageAccountUrlElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "StorageAccountUrl");
        storageAccountUrlElement.appendChild(requestDoc.createTextNode(restoreRequest.getStorageAccountUrl()));
        restoreRequestElement.appendChild(storageAccountUrlElement);
    }

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

            Element restoreRequestElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "RestoreRequest");
            if (restoreRequestElement2 != null) {
                Element storageAccountUrlElement2 = XmlUtility.getElementByTagNameNS(restoreRequestElement2,
                        "http://schemas.microsoft.com/windowsazure", "StorageAccountUrl");
                if (storageAccountUrlElement2 != null) {
                    String storageAccountUrlInstance;
                    storageAccountUrlInstance = storageAccountUrlElement2.getTextContent();
                    result.setStorageAccountUrl(storageAccountUrlInstance);
                }

                Element blobNameElement2 = XmlUtility.getElementByTagNameNS(restoreRequestElement2,
                        "http://schemas.microsoft.com/windowsazure", "BlobName");
                if (blobNameElement2 != null) {
                    String blobNameInstance;
                    blobNameInstance = blobNameElement2.getTextContent();
                    result.setBlobName(blobNameInstance);
                }

                Element overwriteElement2 = XmlUtility.getElementByTagNameNS(restoreRequestElement2,
                        "http://schemas.microsoft.com/windowsazure", "Overwrite");
                if (overwriteElement2 != null) {
                    boolean overwriteInstance;
                    overwriteInstance = DatatypeConverter
                            .parseBoolean(overwriteElement2.getTextContent().toLowerCase());
                    result.setOverwrite(overwriteInstance);
                }

                Element databasesSequenceElement2 = XmlUtility.getElementByTagNameNS(restoreRequestElement2,
                        "http://schemas.microsoft.com/windowsazure", "Databases");
                if (databasesSequenceElement2 != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(databasesSequenceElement2,
                                    "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element databasesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(databasesSequenceElement2,
                                        "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting")
                                .get(i1));
                        DatabaseBackupSetting databaseBackupSettingInstance = new DatabaseBackupSetting();
                        result.getDatabases().add(databaseBackupSettingInstance);

                        Element connectionStringElement2 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "ConnectionString");
                        if (connectionStringElement2 != null) {
                            String connectionStringInstance;
                            connectionStringInstance = connectionStringElement2.getTextContent();
                            databaseBackupSettingInstance.setConnectionString(connectionStringInstance);
                        }

                        Element connectionStringNameElement2 = XmlUtility.getElementByTagNameNS(
                                databasesElement, "http://schemas.microsoft.com/windowsazure",
                                "ConnectionStringName");
                        if (connectionStringNameElement2 != null) {
                            String connectionStringNameInstance;
                            connectionStringNameInstance = connectionStringNameElement2.getTextContent();
                            databaseBackupSettingInstance.setConnectionStringName(connectionStringNameInstance);
                        }

                        Element databaseTypeElement2 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "DatabaseType");
                        if (databaseTypeElement2 != null) {
                            String databaseTypeInstance;
                            databaseTypeInstance = databaseTypeElement2.getTextContent();
                            databaseBackupSettingInstance.setDatabaseType(databaseTypeInstance);
                        }

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

                Element ignoreConflictingHostNamesElement2 = XmlUtility.getElementByTagNameNS(
                        restoreRequestElement2, "http://schemas.microsoft.com/windowsazure",
                        "IgnoreConflictingHostNames");
                if (ignoreConflictingHostNamesElement2 != null) {
                    boolean ignoreConflictingHostNamesInstance;
                    ignoreConflictingHostNamesInstance = DatatypeConverter
                            .parseBoolean(ignoreConflictingHostNamesElement2.getTextContent().toLowerCase());
                    result.setIgnoreConflictingHostNames(ignoreConflictingHostNamesInstance);
                }

                Element adjustConnectionStringsElement2 = XmlUtility.getElementByTagNameNS(
                        restoreRequestElement2, "http://schemas.microsoft.com/windowsazure",
                        "AdjustConnectionStrings");
                if (adjustConnectionStringsElement2 != null) {
                    boolean adjustConnectionStringsInstance;
                    adjustConnectionStringsInstance = DatatypeConverter
                            .parseBoolean(adjustConnectionStringsElement2.getTextContent().toLowerCase());
                    result.setAdjustConnectionStrings(adjustConnectionStringsInstance);
                }
            }

        }
        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.websites.WebSiteOperationsImpl.java

/**
* Backups a site on-demand./* w  w  w .  j a  v  a 2 s  . c o  m*/
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param backupRequest Required. A backup specification.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The backup record created based on the backup request.
*/
@Override
public WebSiteBackupResponse backup(String webSpaceName, String webSiteName, BackupRequest backupRequest)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (backupRequest == null) {
        throw new NullPointerException("backupRequest");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("webSiteName", webSiteName);
        tracingParameters.put("backupRequest", backupRequest);
        CloudTracing.enter(invocationId, this, "backupAsync", 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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    url = url + "/backup";
    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-04-01");

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

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

    if (backupRequest.getBackupSchedule() != null) {
        Element backupScheduleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "BackupSchedule");
        backupRequestElement.appendChild(backupScheduleElement);

        Element frequencyIntervalElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyInterval");
        frequencyIntervalElement.appendChild(requestDoc
                .createTextNode(Integer.toString(backupRequest.getBackupSchedule().getFrequencyInterval())));
        backupScheduleElement.appendChild(frequencyIntervalElement);

        if (backupRequest.getBackupSchedule().getFrequencyUnit() != null) {
            Element frequencyUnitElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyUnit");
            frequencyUnitElement.appendChild(
                    requestDoc.createTextNode(backupRequest.getBackupSchedule().getFrequencyUnit().toString()));
            backupScheduleElement.appendChild(frequencyUnitElement);
        }

        Element keepAtLeastOneBackupElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "KeepAtLeastOneBackup");
        keepAtLeastOneBackupElement.appendChild(requestDoc.createTextNode(
                Boolean.toString(backupRequest.getBackupSchedule().isKeepAtLeastOneBackup()).toLowerCase()));
        backupScheduleElement.appendChild(keepAtLeastOneBackupElement);

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

        Element retentionPeriodInDaysElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "RetentionPeriodInDays");
        retentionPeriodInDaysElement.appendChild(requestDoc.createTextNode(
                Integer.toString(backupRequest.getBackupSchedule().getRetentionPeriodInDays())));
        backupScheduleElement.appendChild(retentionPeriodInDaysElement);

        if (backupRequest.getBackupSchedule().getStartTime() != null) {
            Element startTimeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "StartTime");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
            simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
            startTimeElement.appendChild(requestDoc.createTextNode(
                    simpleDateFormat2.format(backupRequest.getBackupSchedule().getStartTime().getTime())));
            backupScheduleElement.appendChild(startTimeElement);
        }
    }

    if (backupRequest.getDatabases() != null) {
        if (backupRequest.getDatabases() instanceof LazyCollection == false
                || ((LazyCollection) backupRequest.getDatabases()).isInitialized()) {
            Element databasesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Databases");
            for (DatabaseBackupSetting databasesItem : backupRequest.getDatabases()) {
                Element databaseBackupSettingElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting");
                databasesSequenceElement.appendChild(databaseBackupSettingElement);

                if (databasesItem.getConnectionString() != null) {
                    Element connectionStringElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionString");
                    connectionStringElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionString()));
                    databaseBackupSettingElement.appendChild(connectionStringElement);
                }

                if (databasesItem.getConnectionStringName() != null) {
                    Element connectionStringNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "ConnectionStringName");
                    connectionStringNameElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionStringName()));
                    databaseBackupSettingElement.appendChild(connectionStringNameElement);
                }

                if (databasesItem.getDatabaseType() != null) {
                    Element databaseTypeElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseType");
                    databaseTypeElement.appendChild(requestDoc.createTextNode(databasesItem.getDatabaseType()));
                    databaseBackupSettingElement.appendChild(databaseTypeElement);
                }

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

    if (backupRequest.isEnabled() != null) {
        Element enabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Enabled");
        enabledElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(backupRequest.isEnabled()).toLowerCase()));
        backupRequestElement.appendChild(enabledElement);
    }

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

    if (backupRequest.getStorageAccountUrl() != null) {
        Element storageAccountUrlElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "StorageAccountUrl");
        storageAccountUrlElement.appendChild(requestDoc.createTextNode(backupRequest.getStorageAccountUrl()));
        backupRequestElement.appendChild(storageAccountUrlElement);
    }

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

            Element backupItemElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "BackupItem");
            if (backupItemElement != null) {
                BackupItem backupItemInstance = new BackupItem();
                result.setBackupItem(backupItemInstance);

                Element storageAccountUrlElement2 = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "StorageAccountUrl");
                if (storageAccountUrlElement2 != null) {
                    String storageAccountUrlInstance;
                    storageAccountUrlInstance = storageAccountUrlElement2.getTextContent();
                    backupItemInstance.setStorageAccountUrl(storageAccountUrlInstance);
                }

                Element blobNameElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "BlobName");
                if (blobNameElement != null) {
                    String blobNameInstance;
                    blobNameInstance = blobNameElement.getTextContent();
                    backupItemInstance.setBlobName(blobNameInstance);
                }

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

                Element statusElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null && statusElement.getTextContent() != null
                        && !statusElement.getTextContent().isEmpty()) {
                    BackupItemStatus statusInstance;
                    statusInstance = BackupItemStatus.valueOf(statusElement.getTextContent());
                    backupItemInstance.setStatus(statusInstance);
                }

                Element sizeInBytesElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "SizeInBytes");
                if (sizeInBytesElement != null) {
                    long sizeInBytesInstance;
                    sizeInBytesInstance = DatatypeConverter.parseLong(sizeInBytesElement.getTextContent());
                    backupItemInstance.setSizeInBytes(sizeInBytesInstance);
                }

                Element createdElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Created");
                if (createdElement != null && createdElement.getTextContent() != null
                        && !createdElement.getTextContent().isEmpty()) {
                    Calendar createdInstance;
                    createdInstance = DatatypeConverter.parseDateTime(createdElement.getTextContent());
                    backupItemInstance.setCreated(createdInstance);
                }

                Element logElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Log");
                if (logElement != null) {
                    String logInstance;
                    logInstance = logElement.getTextContent();
                    backupItemInstance.setLog(logInstance);
                }

                Element databasesSequenceElement2 = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Databases");
                if (databasesSequenceElement2 != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(databasesSequenceElement2,
                                    "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element databasesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(databasesSequenceElement2,
                                        "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting")
                                .get(i1));
                        DatabaseBackupSetting databaseBackupSettingInstance = new DatabaseBackupSetting();
                        backupItemInstance.getDatabases().add(databaseBackupSettingInstance);

                        Element connectionStringElement2 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "ConnectionString");
                        if (connectionStringElement2 != null) {
                            String connectionStringInstance;
                            connectionStringInstance = connectionStringElement2.getTextContent();
                            databaseBackupSettingInstance.setConnectionString(connectionStringInstance);
                        }

                        Element connectionStringNameElement2 = XmlUtility.getElementByTagNameNS(
                                databasesElement, "http://schemas.microsoft.com/windowsazure",
                                "ConnectionStringName");
                        if (connectionStringNameElement2 != null) {
                            String connectionStringNameInstance;
                            connectionStringNameInstance = connectionStringNameElement2.getTextContent();
                            databaseBackupSettingInstance.setConnectionStringName(connectionStringNameInstance);
                        }

                        Element databaseTypeElement2 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "DatabaseType");
                        if (databaseTypeElement2 != null) {
                            String databaseTypeInstance;
                            databaseTypeInstance = databaseTypeElement2.getTextContent();
                            databaseBackupSettingInstance.setDatabaseType(databaseTypeInstance);
                        }

                        Element nameElement4 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "Name");
                        if (nameElement4 != null) {
                            String nameInstance2;
                            nameInstance2 = nameElement4.getTextContent();
                            databaseBackupSettingInstance.setName(nameInstance2);
                        }
                    }
                }

                Element scheduledElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Scheduled");
                if (scheduledElement != null) {
                    boolean scheduledInstance;
                    scheduledInstance = DatatypeConverter
                            .parseBoolean(scheduledElement.getTextContent().toLowerCase());
                    backupItemInstance.setScheduled(scheduledInstance);
                }

                Element lastRestoreTimeStampElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "LastRestoreTimeStamp");
                if (lastRestoreTimeStampElement != null && lastRestoreTimeStampElement.getTextContent() != null
                        && !lastRestoreTimeStampElement.getTextContent().isEmpty()) {
                    Calendar lastRestoreTimeStampInstance;
                    lastRestoreTimeStampInstance = DatatypeConverter
                            .parseDateTime(lastRestoreTimeStampElement.getTextContent());
                    backupItemInstance.setLastRestoreTimeStamp(lastRestoreTimeStampInstance);
                }

                Element finishedTimeStampElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "FinishedTimeStamp");
                if (finishedTimeStampElement != null && finishedTimeStampElement.getTextContent() != null
                        && !finishedTimeStampElement.getTextContent().isEmpty()) {
                    Calendar finishedTimeStampInstance;
                    finishedTimeStampInstance = DatatypeConverter
                            .parseDateTime(finishedTimeStampElement.getTextContent());
                    backupItemInstance.setFinishedTimeStamp(finishedTimeStampInstance);
                }

                Element correlationIdElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "CorrelationId");
                if (correlationIdElement != null) {
                    String correlationIdInstance;
                    correlationIdInstance = correlationIdElement.getTextContent();
                    backupItemInstance.setCorrelationId(correlationIdInstance);
                }
            }

        }
        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.websites.WebSiteOperationsImpl.java

/**
* You can create a web site by using a POST request that includes the name
* of the web site and other information in the request body.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166986.aspx for
* more information)/*  w  w  w  . j a v a2 s.c om*/
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Parameters supplied to the Create Web Site
* 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create Web Site operation response.
*/
@Override
public WebSiteCreateResponse create(String webSpaceName, WebSiteCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getServerFarm() == null) {
        throw new NullPointerException("parameters.ServerFarm");
    }
    if (parameters.getWebSpace() != null) {
        if (parameters.getWebSpace().getGeoRegion() == null) {
            throw new NullPointerException("parameters.WebSpace.GeoRegion");
        }
        if (parameters.getWebSpace().getName() == null) {
            throw new NullPointerException("parameters.WebSpace.Name");
        }
        if (parameters.getWebSpace().getPlan() == null) {
            throw new NullPointerException("parameters.WebSpace.Plan");
        }
    }

    // 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("webSpaceName", webSpaceName);
        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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites";
    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-04-01");

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

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

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

    Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServerFarm");
    serverFarmElement.appendChild(requestDoc.createTextNode(parameters.getServerFarm()));
    siteElement.appendChild(serverFarmElement);

    if (parameters.getWebSpace() != null) {
        Element webSpaceToCreateElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "WebSpaceToCreate");
        siteElement.appendChild(webSpaceToCreateElement);

        Element geoRegionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "GeoRegion");
        geoRegionElement.appendChild(requestDoc.createTextNode(parameters.getWebSpace().getGeoRegion()));
        webSpaceToCreateElement.appendChild(geoRegionElement);

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

        Element planElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Plan");
        planElement.appendChild(requestDoc.createTextNode(parameters.getWebSpace().getPlan()));
        webSpaceToCreateElement.appendChild(planElement);
    }

    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 && statusCode != HttpStatus.SC_CREATED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element siteElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Site");
            if (siteElement2 != null) {
                WebSite webSiteInstance = new WebSite();
                result.setWebSite(webSiteInstance);

                Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "AdminEnabled");
                if (adminEnabledElement != null && adminEnabledElement.getTextContent() != null
                        && !adminEnabledElement.getTextContent().isEmpty()) {
                    boolean adminEnabledInstance;
                    adminEnabledInstance = DatatypeConverter
                            .parseBoolean(adminEnabledElement.getTextContent().toLowerCase());
                    webSiteInstance.setAdminEnabled(adminEnabledInstance);
                }

                Element availabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "AvailabilityState");
                if (availabilityStateElement != null && availabilityStateElement.getTextContent() != null
                        && !availabilityStateElement.getTextContent().isEmpty()) {
                    WebSpaceAvailabilityState availabilityStateInstance;
                    availabilityStateInstance = WebSpaceAvailabilityState
                            .valueOf(availabilityStateElement.getTextContent());
                    webSiteInstance.setAvailabilityState(availabilityStateInstance);
                }

                Element sKUElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "SKU");
                if (sKUElement != null && sKUElement.getTextContent() != null
                        && !sKUElement.getTextContent().isEmpty()) {
                    SkuOptions sKUInstance;
                    sKUInstance = SkuOptions.valueOf(sKUElement.getTextContent());
                    webSiteInstance.setSku(sKUInstance);
                }

                Element enabledElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "Enabled");
                if (enabledElement != null && enabledElement.getTextContent() != null
                        && !enabledElement.getTextContent().isEmpty()) {
                    boolean enabledInstance;
                    enabledInstance = DatatypeConverter
                            .parseBoolean(enabledElement.getTextContent().toLowerCase());
                    webSiteInstance.setEnabled(enabledInstance);
                }

                Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "EnabledHostNames");
                if (enabledHostNamesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i1));
                        webSiteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent());
                    }
                }

                Element hostNameSslStatesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "HostNameSslStates");
                if (hostNameSslStatesSequenceElement != null) {
                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNameSslStatesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                            .size(); i2 = i2 + 1) {
                        org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNameSslStatesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                                .get(i2));
                        WebSite.WebSiteHostNameSslState hostNameSslStateInstance = new WebSite.WebSiteHostNameSslState();
                        webSiteInstance.getHostNameSslStates().add(hostNameSslStateInstance);

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

                        Element sslStateElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "SslState");
                        if (sslStateElement != null && sslStateElement.getTextContent() != null
                                && !sslStateElement.getTextContent().isEmpty()) {
                            WebSiteSslState sslStateInstance;
                            sslStateInstance = WebSiteSslState.valueOf(sslStateElement.getTextContent());
                            hostNameSslStateInstance.setSslState(sslStateInstance);
                        }

                        Element thumbprintElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                        if (thumbprintElement != null) {
                            boolean isNil = false;
                            Attr nilAttribute = thumbprintElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute != null) {
                                isNil = "true".equals(nilAttribute.getValue());
                            }
                            if (isNil == false) {
                                String thumbprintInstance;
                                thumbprintInstance = thumbprintElement.getTextContent();
                                hostNameSslStateInstance.setThumbprint(thumbprintInstance);
                            }
                        }

                        Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "VirtualIP");
                        if (virtualIPElement != null) {
                            boolean isNil2 = false;
                            Attr nilAttribute2 = virtualIPElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute2 != null) {
                                isNil2 = "true".equals(nilAttribute2.getValue());
                            }
                            if (isNil2 == false) {
                                InetAddress virtualIPInstance;
                                virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent());
                                hostNameSslStateInstance.setVirtualIP(virtualIPInstance);
                            }
                        }
                    }
                }

                Element hostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "HostNames");
                if (hostNamesSequenceElement != null) {
                    for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNamesSequenceElement,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i3 = i3 + 1) {
                        org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i3));
                        webSiteInstance.getHostNames().add(hostNamesElement.getTextContent());
                    }
                }

                Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc");
                if (lastModifiedTimeUtcElement != null && lastModifiedTimeUtcElement.getTextContent() != null
                        && !lastModifiedTimeUtcElement.getTextContent().isEmpty()) {
                    Calendar lastModifiedTimeUtcInstance;
                    lastModifiedTimeUtcInstance = DatatypeConverter
                            .parseDateTime(lastModifiedTimeUtcElement.getTextContent());
                    webSiteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance);
                }

                Element nameElement4 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement4 != null) {
                    String nameInstance2;
                    nameInstance2 = nameElement4.getTextContent();
                    webSiteInstance.setName(nameInstance2);
                }

                Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "RepositorySiteName");
                if (repositorySiteNameElement != null) {
                    String repositorySiteNameInstance;
                    repositorySiteNameInstance = repositorySiteNameElement.getTextContent();
                    webSiteInstance.setRepositorySiteName(repositorySiteNameInstance);
                }

                Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState");
                if (runtimeAvailabilityStateElement != null
                        && runtimeAvailabilityStateElement.getTextContent() != null
                        && !runtimeAvailabilityStateElement.getTextContent().isEmpty()) {
                    WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance;
                    runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState
                            .valueOf(runtimeAvailabilityStateElement.getTextContent());
                    webSiteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance);
                }

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

                Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                if (serverFarmElement2 != null) {
                    String serverFarmInstance;
                    serverFarmInstance = serverFarmElement2.getTextContent();
                    webSiteInstance.setServerFarm(serverFarmInstance);
                }

                Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "SiteProperties");
                if (sitePropertiesElement != null) {
                    WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties();
                    webSiteInstance.setSiteProperties(sitePropertiesInstance);

                    Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "AppSettings");
                    if (appSettingsSequenceElement != null) {
                        for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(appSettingsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i4 = i4 + 1) {
                            org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(appSettingsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i4));
                            String appSettingsKey = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String appSettingsValue = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue);
                        }
                    }

                    Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Metadata");
                    if (metadataSequenceElement != null) {
                        for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metadataSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i5 = i5 + 1) {
                            org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(metadataSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i5));
                            String metadataKey = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String metadataValue = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue);
                        }
                    }

                    Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Properties");
                    if (propertiesSequenceElement != null) {
                        for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(propertiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i6 = i6 + 1) {
                            org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(propertiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i6));
                            String propertiesKey = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String propertiesValue = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue);
                        }
                    }
                }

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

                Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "UsageState");
                if (usageStateElement != null && usageStateElement.getTextContent() != null
                        && !usageStateElement.getTextContent().isEmpty()) {
                    WebSiteUsageState usageStateInstance;
                    usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent());
                    webSiteInstance.setUsageState(usageStateInstance);
                }

                Element webSpaceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "WebSpace");
                if (webSpaceElement != null) {
                    String webSpaceInstance;
                    webSpaceInstance = webSpaceElement.getTextContent();
                    webSiteInstance.setWebSpace(webSpaceInstance);
                }
            }

        }
        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.websites.WebSiteOperationsImpl.java

/**
* You can update the settings for a web site by using the HTTP PUT method
* and by specifying the settings in the request body.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn167005.aspx for
* more information)//from   w w  w .  j  a  v a 2s  .  c  o  m
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param parameters Required. Parameters supplied to the Update Web Site
* 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Update Web Site operation response.
*/
@Override
public WebSiteUpdateResponse update(String webSpaceName, String webSiteName, WebSiteUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getHostNameSslStates() != null) {
        for (WebSiteUpdateParameters.WebSiteHostNameSslState hostNameSslStatesParameterItem : parameters
                .getHostNameSslStates()) {
            if (hostNameSslStatesParameterItem.getName() == null) {
                throw new NullPointerException("parameters.HostNameSslStates.Name");
            }
            if (hostNameSslStatesParameterItem.getSslState() == null) {
                throw new NullPointerException("parameters.HostNameSslStates.SslState");
            }
        }
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("webSiteName", webSiteName);
        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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "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-04-01");

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

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

    if (parameters.getHostNameSslStates() != null) {
        if (parameters.getHostNameSslStates() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getHostNameSslStates()).isInitialized()) {
            Element hostNameSslStatesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "HostNameSslStates");
            for (WebSiteUpdateParameters.WebSiteHostNameSslState hostNameSslStatesItem : parameters
                    .getHostNameSslStates()) {
                Element webSiteHostNameSslStateElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState");
                hostNameSslStatesSequenceElement.appendChild(webSiteHostNameSslStateElement);

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

                Element sslStateElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SslState");
                sslStateElement
                        .appendChild(requestDoc.createTextNode(hostNameSslStatesItem.getSslState().toString()));
                webSiteHostNameSslStateElement.appendChild(sslStateElement);

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

                Element toUpdateElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ToUpdate");
                toUpdateElement.appendChild(requestDoc.createTextNode("true"));
                webSiteHostNameSslStateElement.appendChild(toUpdateElement);
            }
            siteElement.appendChild(hostNameSslStatesSequenceElement);
        }
    }

    if (parameters.getHostNames() != null) {
        if (parameters.getHostNames() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getHostNames()).isInitialized()) {
            Element hostNamesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "HostNames");
            for (String hostNamesItem : parameters.getHostNames()) {
                Element hostNamesItemElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string");
                hostNamesItemElement.appendChild(requestDoc.createTextNode(hostNamesItem));
                hostNamesSequenceElement.appendChild(hostNamesItemElement);
            }
            siteElement.appendChild(hostNamesSequenceElement);
        }
    }

    if (parameters.getServerFarm() != null) {
        Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServerFarm");
        serverFarmElement.appendChild(requestDoc.createTextNode(parameters.getServerFarm()));
        siteElement.appendChild(serverFarmElement);
    }

    if (parameters.getState() != null) {
        Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State");
        stateElement.appendChild(requestDoc.createTextNode(parameters.getState()));
        siteElement.appendChild(stateElement);
    }

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

            Element siteElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Site");
            if (siteElement2 != null) {
                WebSite webSiteInstance = new WebSite();
                result.setWebSite(webSiteInstance);

                Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "AdminEnabled");
                if (adminEnabledElement != null && adminEnabledElement.getTextContent() != null
                        && !adminEnabledElement.getTextContent().isEmpty()) {
                    boolean adminEnabledInstance;
                    adminEnabledInstance = DatatypeConverter
                            .parseBoolean(adminEnabledElement.getTextContent().toLowerCase());
                    webSiteInstance.setAdminEnabled(adminEnabledInstance);
                }

                Element availabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "AvailabilityState");
                if (availabilityStateElement != null && availabilityStateElement.getTextContent() != null
                        && !availabilityStateElement.getTextContent().isEmpty()) {
                    WebSpaceAvailabilityState availabilityStateInstance;
                    availabilityStateInstance = WebSpaceAvailabilityState
                            .valueOf(availabilityStateElement.getTextContent());
                    webSiteInstance.setAvailabilityState(availabilityStateInstance);
                }

                Element sKUElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "SKU");
                if (sKUElement != null && sKUElement.getTextContent() != null
                        && !sKUElement.getTextContent().isEmpty()) {
                    SkuOptions sKUInstance;
                    sKUInstance = SkuOptions.valueOf(sKUElement.getTextContent());
                    webSiteInstance.setSku(sKUInstance);
                }

                Element enabledElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "Enabled");
                if (enabledElement != null && enabledElement.getTextContent() != null
                        && !enabledElement.getTextContent().isEmpty()) {
                    boolean enabledInstance;
                    enabledInstance = DatatypeConverter
                            .parseBoolean(enabledElement.getTextContent().toLowerCase());
                    webSiteInstance.setEnabled(enabledInstance);
                }

                Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "EnabledHostNames");
                if (enabledHostNamesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i1));
                        webSiteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent());
                    }
                }

                Element hostNameSslStatesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "HostNameSslStates");
                if (hostNameSslStatesSequenceElement2 != null) {
                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNameSslStatesSequenceElement2,
                                    "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                            .size(); i2 = i2 + 1) {
                        org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNameSslStatesSequenceElement2,
                                        "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                                .get(i2));
                        WebSite.WebSiteHostNameSslState hostNameSslStateInstance = new WebSite.WebSiteHostNameSslState();
                        webSiteInstance.getHostNameSslStates().add(hostNameSslStateInstance);

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

                        Element sslStateElement2 = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "SslState");
                        if (sslStateElement2 != null && sslStateElement2.getTextContent() != null
                                && !sslStateElement2.getTextContent().isEmpty()) {
                            WebSiteSslState sslStateInstance;
                            sslStateInstance = WebSiteSslState.valueOf(sslStateElement2.getTextContent());
                            hostNameSslStateInstance.setSslState(sslStateInstance);
                        }

                        Element thumbprintElement2 = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                        if (thumbprintElement2 != null) {
                            boolean isNil = false;
                            Attr nilAttribute2 = thumbprintElement2
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute2 != null) {
                                isNil = "true".equals(nilAttribute2.getValue());
                            }
                            if (isNil == false) {
                                String thumbprintInstance;
                                thumbprintInstance = thumbprintElement2.getTextContent();
                                hostNameSslStateInstance.setThumbprint(thumbprintInstance);
                            }
                        }

                        Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "VirtualIP");
                        if (virtualIPElement != null) {
                            boolean isNil2 = false;
                            Attr nilAttribute3 = virtualIPElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute3 != null) {
                                isNil2 = "true".equals(nilAttribute3.getValue());
                            }
                            if (isNil2 == false) {
                                InetAddress virtualIPInstance;
                                virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent());
                                hostNameSslStateInstance.setVirtualIP(virtualIPInstance);
                            }
                        }
                    }
                }

                Element hostNamesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "HostNames");
                if (hostNamesSequenceElement2 != null) {
                    for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNamesSequenceElement2,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i3 = i3 + 1) {
                        org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNamesSequenceElement2,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i3));
                        webSiteInstance.getHostNames().add(hostNamesElement.getTextContent());
                    }
                }

                Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc");
                if (lastModifiedTimeUtcElement != null && lastModifiedTimeUtcElement.getTextContent() != null
                        && !lastModifiedTimeUtcElement.getTextContent().isEmpty()) {
                    Calendar lastModifiedTimeUtcInstance;
                    lastModifiedTimeUtcInstance = DatatypeConverter
                            .parseDateTime(lastModifiedTimeUtcElement.getTextContent());
                    webSiteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance);
                }

                Element nameElement3 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement3 != null) {
                    String nameInstance2;
                    nameInstance2 = nameElement3.getTextContent();
                    webSiteInstance.setName(nameInstance2);
                }

                Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "RepositorySiteName");
                if (repositorySiteNameElement != null) {
                    String repositorySiteNameInstance;
                    repositorySiteNameInstance = repositorySiteNameElement.getTextContent();
                    webSiteInstance.setRepositorySiteName(repositorySiteNameInstance);
                }

                Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState");
                if (runtimeAvailabilityStateElement != null
                        && runtimeAvailabilityStateElement.getTextContent() != null
                        && !runtimeAvailabilityStateElement.getTextContent().isEmpty()) {
                    WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance;
                    runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState
                            .valueOf(runtimeAvailabilityStateElement.getTextContent());
                    webSiteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance);
                }

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

                Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                if (serverFarmElement2 != null) {
                    String serverFarmInstance;
                    serverFarmInstance = serverFarmElement2.getTextContent();
                    webSiteInstance.setServerFarm(serverFarmInstance);
                }

                Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "SiteProperties");
                if (sitePropertiesElement != null) {
                    WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties();
                    webSiteInstance.setSiteProperties(sitePropertiesInstance);

                    Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "AppSettings");
                    if (appSettingsSequenceElement != null) {
                        for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(appSettingsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i4 = i4 + 1) {
                            org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(appSettingsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i4));
                            String appSettingsKey = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String appSettingsValue = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue);
                        }
                    }

                    Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Metadata");
                    if (metadataSequenceElement != null) {
                        for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metadataSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i5 = i5 + 1) {
                            org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(metadataSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i5));
                            String metadataKey = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String metadataValue = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue);
                        }
                    }

                    Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Properties");
                    if (propertiesSequenceElement != null) {
                        for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(propertiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i6 = i6 + 1) {
                            org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(propertiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i6));
                            String propertiesKey = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String propertiesValue = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue);
                        }
                    }
                }

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

                Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "UsageState");
                if (usageStateElement != null && usageStateElement.getTextContent() != null
                        && !usageStateElement.getTextContent().isEmpty()) {
                    WebSiteUsageState usageStateInstance;
                    usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent());
                    webSiteInstance.setUsageState(usageStateInstance);
                }

                Element webSpaceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "WebSpace");
                if (webSpaceElement != null) {
                    String webSpaceInstance;
                    webSpaceInstance = webSpaceElement.getTextContent();
                    webSiteInstance.setWebSpace(webSpaceInstance);
                }
            }

        }
        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.VirtualMachineOperationsImpl.java

/**
* The Begin Starting Roles operation starts the specified set of virtual
* machines.  (see/*from  www . j a va  2s .  c  o  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Begin Starting
* Roles 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 beginStartingRoles(String serviceName, String deploymentName,
        VirtualMachineStartRolesParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/Roles/Operations";
    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 startRolesOperationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartRolesOperation");
    requestDoc.appendChild(startRolesOperationElement);

    Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "OperationType");
    operationTypeElement.appendChild(requestDoc.createTextNode("StartRolesOperation"));
    startRolesOperationElement.appendChild(operationTypeElement);

    if (parameters.getRoles() != null) {
        if (parameters.getRoles() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getRoles()).isInitialized()) {
            Element rolesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Roles");
            for (String rolesItem : parameters.getRoles()) {
                Element rolesItemElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                rolesItemElement.appendChild(requestDoc.createTextNode(rolesItem));
                rolesSequenceElement.appendChild(rolesItemElement);
            }
            startRolesOperationElement.appendChild(rolesSequenceElement);
        }
    }

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

/**
* The Shutdown Role operation shuts down the specified virtual machine.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
* for more information)/*from ww  w  .j a  va2 s .co  m*/
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* shutdown.
* @param parameters Required. The parameters for the shutdown vm 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 beginShutdown(String serviceName, String deploymentName, String virtualMachineName,
        VirtualMachineShutdownParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (virtualMachineName == null) {
        throw new NullPointerException("virtualMachineName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roleinstances/";
    url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
    url = url + "/Operations";
    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 shutdownRoleOperationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ShutdownRoleOperation");
    requestDoc.appendChild(shutdownRoleOperationElement);

    Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "OperationType");
    operationTypeElement.appendChild(requestDoc.createTextNode("ShutdownRoleOperation"));
    shutdownRoleOperationElement.appendChild(operationTypeElement);

    if (parameters.getPostShutdownAction() != null) {
        Element postShutdownActionElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PostShutdownAction");
        postShutdownActionElement
                .appendChild(requestDoc.createTextNode(parameters.getPostShutdownAction().toString()));
        shutdownRoleOperationElement.appendChild(postShutdownActionElement);
    }

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

/**
* The Begin Shutting Down Roles operation stops the specified set of
* virtual machines.  (see//from   w  w  w .j  a va2  s . c o m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for
* more information)
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param parameters Required. Parameters to pass to the Begin Shutting Down
* Roles 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 beginShuttingDownRoles(String serviceName, String deploymentName,
        VirtualMachineShutdownRolesParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/Roles/Operations";
    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 shutdownRolesOperationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ShutdownRolesOperation");
    requestDoc.appendChild(shutdownRolesOperationElement);

    Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "OperationType");
    operationTypeElement.appendChild(requestDoc.createTextNode("ShutdownRolesOperation"));
    shutdownRolesOperationElement.appendChild(operationTypeElement);

    if (parameters.getRoles() != null) {
        if (parameters.getRoles() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getRoles()).isInitialized()) {
            Element rolesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Roles");
            for (String rolesItem : parameters.getRoles()) {
                Element rolesItemElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                rolesItemElement.appendChild(requestDoc.createTextNode(rolesItem));
                rolesSequenceElement.appendChild(rolesItemElement);
            }
            shutdownRolesOperationElement.appendChild(rolesSequenceElement);
        }
    }

    if (parameters.getPostShutdownAction() != null) {
        Element postShutdownActionElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PostShutdownAction");
        postShutdownActionElement
                .appendChild(requestDoc.createTextNode(parameters.getPostShutdownAction().toString()));
        shutdownRolesOperationElement.appendChild(postShutdownActionElement);
    }

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

/**
* Begin capturing role as VM template.//w  ww .  ja  v  a 2  s . c  o m
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of your deployment.
* @param virtualMachineName Required. The name of the virtual machine to
* restart.
* @param parameters Required. Parameters supplied to the Capture Virtual
* Machine 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 beginCapturingVMImage(String serviceName, String deploymentName,
        String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (virtualMachineName == null) {
        throw new NullPointerException("virtualMachineName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roleinstances/";
    url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
    url = url + "/Operations";
    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 captureRoleAsVMImageOperationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "CaptureRoleAsVMImageOperation");
    requestDoc.appendChild(captureRoleAsVMImageOperationElement);

    Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "OperationType");
    operationTypeElement.appendChild(requestDoc.createTextNode("CaptureRoleAsVMImageOperation"));
    captureRoleAsVMImageOperationElement.appendChild(operationTypeElement);

    if (parameters.getOSState() != null) {
        Element oSStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "OSState");
        oSStateElement.appendChild(requestDoc.createTextNode(parameters.getOSState()));
        captureRoleAsVMImageOperationElement.appendChild(oSStateElement);
    }

    if (parameters.getVMImageName() != null) {
        Element vMImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "VMImageName");
        vMImageNameElement.appendChild(requestDoc.createTextNode(parameters.getVMImageName()));
        captureRoleAsVMImageOperationElement.appendChild(vMImageNameElement);
    }

    if (parameters.getVMImageLabel() != null) {
        Element vMImageLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "VMImageLabel");
        vMImageLabelElement.appendChild(requestDoc.createTextNode(parameters.getVMImageLabel()));
        captureRoleAsVMImageOperationElement.appendChild(vMImageLabelElement);
    }

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