Example usage for org.w3c.dom Element getAttributeNodeNS

List of usage examples for org.w3c.dom Element getAttributeNodeNS

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttributeNodeNS.

Prototype

public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Retrieves an Attr node by local name and namespace URI.

Usage

From source file:com.microsoft.windowsazure.management.websites.WebSiteOperationsImpl.java

/**
* You can retrieve the publish settings information for a web site by
* issuing an HTTP GET request.  (see//from w  ww . j  a  v  a 2  s .c  om
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166996.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Publish Profile Web Site operation response.
*/
@Override
public WebSiteGetPublishProfileResponse getPublishProfile(String webSpaceName, String webSiteName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }

    // 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);
        CloudTracing.enter(invocationId, this, "getPublishProfileAsync", 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 + "/publishxml";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

            Element publishDataElement = XmlUtility.getElementByTagNameNS(responseDoc, "", "publishData");
            if (publishDataElement != null) {
                if (publishDataElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(publishDataElement, "", "publishProfile")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element publishProfilesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(publishDataElement, "", "publishProfile").get(i1));
                        WebSiteGetPublishProfileResponse.PublishProfile publishProfileInstance = new WebSiteGetPublishProfileResponse.PublishProfile();
                        result.getPublishProfiles().add(publishProfileInstance);

                        Attr profileNameAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "profileName");
                        if (profileNameAttribute != null) {
                            publishProfileInstance.setProfileName(profileNameAttribute.getValue());
                        }

                        Attr publishMethodAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "publishMethod");
                        if (publishMethodAttribute != null) {
                            publishProfileInstance.setPublishMethod(publishMethodAttribute.getValue());
                        }

                        Attr publishUrlAttribute = publishProfilesElement.getAttributeNodeNS("", "publishUrl");
                        if (publishUrlAttribute != null) {
                            publishProfileInstance.setPublishUrl(publishUrlAttribute.getValue());
                        }

                        Attr msdeploySiteAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "msdeploySite");
                        if (msdeploySiteAttribute != null) {
                            publishProfileInstance.setMSDeploySite(msdeploySiteAttribute.getValue());
                        }

                        Attr ftpPassiveModeAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "ftpPassiveMode");
                        if (ftpPassiveModeAttribute != null) {
                            publishProfileInstance.setFtpPassiveMode(DatatypeConverter
                                    .parseBoolean(ftpPassiveModeAttribute.getValue().toLowerCase()));
                        }

                        Attr userNameAttribute = publishProfilesElement.getAttributeNodeNS("", "userName");
                        if (userNameAttribute != null) {
                            publishProfileInstance.setUserName(userNameAttribute.getValue());
                        }

                        Attr userPWDAttribute = publishProfilesElement.getAttributeNodeNS("", "userPWD");
                        if (userPWDAttribute != null) {
                            publishProfileInstance.setUserPassword(userPWDAttribute.getValue());
                        }

                        Attr destinationAppUrlAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "destinationAppUrl");
                        if (destinationAppUrlAttribute != null) {
                            publishProfileInstance
                                    .setDestinationAppUri(new URI(destinationAppUrlAttribute.getValue()));
                        }

                        Attr sQLServerDBConnectionStringAttribute = publishProfilesElement
                                .getAttributeNodeNS("", "SQLServerDBConnectionString");
                        if (sQLServerDBConnectionStringAttribute != null) {
                            publishProfileInstance.setSqlServerConnectionString(
                                    sQLServerDBConnectionStringAttribute.getValue());
                        }

                        Attr mySQLDBConnectionStringAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "mySQLDBConnectionString");
                        if (mySQLDBConnectionStringAttribute != null) {
                            publishProfileInstance
                                    .setMySqlConnectionString(mySQLDBConnectionStringAttribute.getValue());
                        }

                        Attr hostingProviderForumLinkAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "hostingProviderForumLink");
                        if (hostingProviderForumLinkAttribute != null) {
                            publishProfileInstance.setHostingProviderForumUri(
                                    new URI(hostingProviderForumLinkAttribute.getValue()));
                        }

                        Attr controlPanelLinkAttribute = publishProfilesElement.getAttributeNodeNS("",
                                "controlPanelLink");
                        if (controlPanelLinkAttribute != null) {
                            publishProfileInstance
                                    .setControlPanelUri(new URI(controlPanelLinkAttribute.getValue()));
                        }

                        Element databasesSequenceElement = XmlUtility
                                .getElementByTagNameNS(publishProfilesElement, "", "databases");
                        if (databasesSequenceElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(databasesSequenceElement, "", "add")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element databasesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(databasesSequenceElement, "", "add").get(i2));
                                WebSiteGetPublishProfileResponse.Database addInstance = new WebSiteGetPublishProfileResponse.Database();
                                publishProfileInstance.getDatabases().add(addInstance);

                                Attr nameAttribute = databasesElement.getAttributeNodeNS("", "name");
                                if (nameAttribute != null) {
                                    addInstance.setName(nameAttribute.getValue());
                                }

                                Attr connectionStringAttribute = databasesElement.getAttributeNodeNS("",
                                        "connectionString");
                                if (connectionStringAttribute != null) {
                                    addInstance.setConnectionString(connectionStringAttribute.getValue());
                                }

                                Attr providerNameAttribute = databasesElement.getAttributeNodeNS("",
                                        "providerName");
                                if (providerNameAttribute != null) {
                                    addInstance.setProviderName(providerNameAttribute.getValue());
                                }

                                Attr typeAttribute = databasesElement.getAttributeNodeNS("", "type");
                                if (typeAttribute != null) {
                                    addInstance.setType(typeAttribute.getValue());
                                }
                            }
                        }
                    }
                }
            }

        }
        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 retrieve details for a web site by issuing an HTTP GET request.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/dn167007.aspx
* for more information)//from   ww  w.j av 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 Optional. Parameters supplied to the Get Web Site
* Operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Web Site operation response.
*/
@Override
public WebSiteGetResponse get(String webSpaceName, String webSiteName, WebSiteGetParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    if (parameters != null && parameters.getPropertiesToInclude() != null
            && parameters.getPropertiesToInclude().size() > 0) {
        queryParameters.add("propertiesToInclude=" + URLEncoder
                .encode(CollectionStringBuilder.join(parameters.getPropertiesToInclude(), ","), "UTF-8"));
    }
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

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

                Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "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(siteElement,
                        "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(siteElement,
                        "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(siteElement,
                        "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(siteElement,
                        "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(siteElement,
                        "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 nameElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "Name");
                        if (nameElement != null) {
                            String nameInstance;
                            nameInstance = nameElement.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(siteElement,
                        "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(siteElement,
                        "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 nameElement2 = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement2 != null) {
                    String nameInstance2;
                    nameInstance2 = nameElement2.getTextContent();
                    webSiteInstance.setName(nameInstance2);
                }

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

                Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "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(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "SelfLink");
                if (selfLinkElement != null) {
                    URI selfLinkInstance;
                    selfLinkInstance = new URI(selfLinkElement.getTextContent());
                    webSiteInstance.setUri(selfLinkInstance);
                }

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

                Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "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(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    webSiteInstance.setState(stateInstance);
                }

                Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "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(siteElement,
                        "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 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)/*from w  ww . ja va 2s  .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  va 2  s. co 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.azure.management.websites.WebSiteOperationsImpl.java

/**
* Retrieve the publish settings information for a web site.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166996.aspx for
* more information)//from   ww w  .ja  va  2s.  c om
*
* @param resourceGroupName Required. The name of the resource group.
* @param webSiteName Required. The name of the web site.
* @param slotName Optional. The name of the slot.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Web Site Publish Profile operation response.
*/
@Override
public WebSiteGetPublishProfileResponse getPublishProfile(String resourceGroupName, String webSiteName,
        String slotName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }

    // 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("resourceGroupName", resourceGroupName);
        tracingParameters.put("webSiteName", webSiteName);
        tracingParameters.put("slotName", slotName);
        CloudTracing.enter(invocationId, this, "getPublishProfileAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Web";
    url = url + "/";
    url = url + "sites";
    url = url + "/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    if (slotName != null) {
        url = url + "/slots/" + URLEncoder.encode(slotName, "UTF-8");
    }
    url = url + "/publishxml";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-06-01");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");

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

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

            Element publishDataSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "",
                    "publishData");
            if (publishDataSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(publishDataSequenceElement, "", "publishProfile")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element publishDataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(publishDataSequenceElement, "", "publishProfile").get(i1));
                    WebSiteGetPublishProfileResponse.PublishProfile publishProfileInstance = new WebSiteGetPublishProfileResponse.PublishProfile();
                    result.getPublishProfiles().add(publishProfileInstance);

                    Attr profileNameAttribute = publishDataElement.getAttributeNodeNS("", "profileName");
                    if (profileNameAttribute != null) {
                        publishProfileInstance.setProfileName(profileNameAttribute.getValue());
                    }

                    Attr publishMethodAttribute = publishDataElement.getAttributeNodeNS("", "publishMethod");
                    if (publishMethodAttribute != null) {
                        publishProfileInstance.setPublishMethod(publishMethodAttribute.getValue());
                    }

                    Attr publishUrlAttribute = publishDataElement.getAttributeNodeNS("", "publishUrl");
                    if (publishUrlAttribute != null) {
                        publishProfileInstance.setPublishUrl(publishUrlAttribute.getValue());
                    }

                    Attr msdeploySiteAttribute = publishDataElement.getAttributeNodeNS("", "msdeploySite");
                    if (msdeploySiteAttribute != null) {
                        publishProfileInstance.setMSDeploySite(msdeploySiteAttribute.getValue());
                    }

                    Attr ftpPassiveModeAttribute = publishDataElement.getAttributeNodeNS("", "ftpPassiveMode");
                    if (ftpPassiveModeAttribute != null) {
                        publishProfileInstance.setFtpPassiveMode(DatatypeConverter
                                .parseBoolean(ftpPassiveModeAttribute.getValue().toLowerCase()));
                    }

                    Attr userNameAttribute = publishDataElement.getAttributeNodeNS("", "userName");
                    if (userNameAttribute != null) {
                        publishProfileInstance.setUserName(userNameAttribute.getValue());
                    }

                    Attr userPWDAttribute = publishDataElement.getAttributeNodeNS("", "userPWD");
                    if (userPWDAttribute != null) {
                        publishProfileInstance.setUserPassword(userPWDAttribute.getValue());
                    }

                    Attr destinationAppUrlAttribute = publishDataElement.getAttributeNodeNS("",
                            "destinationAppUrl");
                    if (destinationAppUrlAttribute != null) {
                        publishProfileInstance
                                .setDestinationAppUri(new URI(destinationAppUrlAttribute.getValue()));
                    }

                    Attr sQLServerDBConnectionStringAttribute = publishDataElement.getAttributeNodeNS("",
                            "SQLServerDBConnectionString");
                    if (sQLServerDBConnectionStringAttribute != null) {
                        publishProfileInstance
                                .setSqlServerConnectionString(sQLServerDBConnectionStringAttribute.getValue());
                    }

                    Attr mySQLDBConnectionStringAttribute = publishDataElement.getAttributeNodeNS("",
                            "mySQLDBConnectionString");
                    if (mySQLDBConnectionStringAttribute != null) {
                        publishProfileInstance
                                .setMySqlConnectionString(mySQLDBConnectionStringAttribute.getValue());
                    }

                    Attr hostingProviderForumLinkAttribute = publishDataElement.getAttributeNodeNS("",
                            "hostingProviderForumLink");
                    if (hostingProviderForumLinkAttribute != null) {
                        publishProfileInstance.setHostingProviderForumUri(
                                new URI(hostingProviderForumLinkAttribute.getValue()));
                    }

                    Attr controlPanelLinkAttribute = publishDataElement.getAttributeNodeNS("",
                            "controlPanelLink");
                    if (controlPanelLinkAttribute != null) {
                        publishProfileInstance
                                .setControlPanelUri(new URI(controlPanelLinkAttribute.getValue()));
                    }

                    Element databasesSequenceElement = XmlUtility.getElementByTagNameNS(publishDataElement, "",
                            "databases");
                    if (databasesSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(databasesSequenceElement, "", "add")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element databasesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(databasesSequenceElement, "", "add").get(i2));
                            WebSiteGetPublishProfileResponse.Database addInstance = new WebSiteGetPublishProfileResponse.Database();
                            publishProfileInstance.getDatabases().add(addInstance);

                            Attr nameAttribute = databasesElement.getAttributeNodeNS("", "name");
                            if (nameAttribute != null) {
                                addInstance.setName(nameAttribute.getValue());
                            }

                            Attr connectionStringAttribute = databasesElement.getAttributeNodeNS("",
                                    "connectionString");
                            if (connectionStringAttribute != null) {
                                addInstance.setConnectionString(connectionStringAttribute.getValue());
                            }

                            Attr providerNameAttribute = databasesElement.getAttributeNodeNS("",
                                    "providerName");
                            if (providerNameAttribute != null) {
                                addInstance.setProviderName(providerNameAttribute.getValue());
                            }

                            Attr typeAttribute = databasesElement.getAttributeNodeNS("", "type");
                            if (typeAttribute != null) {
                                addInstance.setType(typeAttribute.getValue());
                            }
                        }
                    }
                }
            }

        }
        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.network.GatewayOperationsImpl.java

/**
* The List Virtual Network Gateway Supported Devices operation lists the
* supported, on-premise network devices that can connect to the gateway.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj154102.aspx
* for more information)/*from   w ww .j av  a2s .  c  om*/
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The response to the list supported devices request.
*/
@Override
public GatewayListSupportedDevicesResponse listSupportedDevices()
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate

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

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

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

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

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

            Element vpnDeviceListElement = XmlUtility.getElementByTagNameNS(responseDoc, "", "VpnDeviceList");
            if (vpnDeviceListElement != null) {
                Attr versionAttribute = vpnDeviceListElement.getAttributeNodeNS("", "version");
                if (versionAttribute != null) {
                    result.setVersion(versionAttribute.getValue());
                }

                if (vpnDeviceListElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(vpnDeviceListElement, "", "Vendor").size(); i1 = i1 + 1) {
                        org.w3c.dom.Element vendorsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(vpnDeviceListElement, "", "Vendor").get(i1));
                        GatewayListSupportedDevicesResponse.Vendor vendorInstance = new GatewayListSupportedDevicesResponse.Vendor();
                        result.getVendors().add(vendorInstance);

                        Attr nameAttribute = vendorsElement.getAttributeNodeNS("", "name");
                        if (nameAttribute != null) {
                            vendorInstance.setName(nameAttribute.getValue());
                        }

                        if (vendorsElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(vendorsElement, "", "Platform")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element platformsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(vendorsElement, "", "Platform").get(i2));
                                GatewayListSupportedDevicesResponse.Platform platformInstance = new GatewayListSupportedDevicesResponse.Platform();
                                vendorInstance.getPlatforms().add(platformInstance);

                                Attr nameAttribute2 = platformsElement.getAttributeNodeNS("", "name");
                                if (nameAttribute2 != null) {
                                    platformInstance.setName(nameAttribute2.getValue());
                                }

                                if (platformsElement != null) {
                                    for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(platformsElement, "", "OSFamily")
                                            .size(); i3 = i3 + 1) {
                                        org.w3c.dom.Element oSFamiliesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(platformsElement, "", "OSFamily")
                                                .get(i3));
                                        GatewayListSupportedDevicesResponse.OSFamily oSFamilyInstance = new GatewayListSupportedDevicesResponse.OSFamily();
                                        platformInstance.getOSFamilies().add(oSFamilyInstance);

                                        Attr nameAttribute3 = oSFamiliesElement.getAttributeNodeNS("", "name");
                                        if (nameAttribute3 != null) {
                                            oSFamilyInstance.setName(nameAttribute3.getValue());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
        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:org.alfresco.web.forms.xforms.Schema2XForms.java

@SuppressWarnings("unchecked")
public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode,
        final Node newInstanceNode,

        final HashMap<String, String> schemaNamespaces) {
    final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode);
    prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);
    final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode);
    instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);

    for (final String prefix : schemaNamespaces.keySet()) {
        prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
        instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
    }/*from  w  w  w .  j  a v  a 2  s .  co  m*/

    // Evaluate non-recursive XPaths for all prototype elements at this level
    final Iterator<Pointer> it = prototypeContext.iteratePointers("*");
    while (it.hasNext()) {
        final Pointer p = it.next();
        Element proto = (Element) p.getNode();
        String path = p.asPath();
        // check if this is a prototype element with the attribute set
        boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")
                && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true");

        // We shouldn't locate a repeatable child with a fixed path
        if (isPrototype) {
            path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path);
            }
        }

        Document newInstanceDocument = newInstanceNode.getOwnerDocument();

        // Locate the corresponding nodes in the instance document
        List<Node> l = (List<Node>) instanceContext.selectNodes(path);

        // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node
        if (l.isEmpty()) {
            if (!isPrototype) {
                LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));

                // Clone the prototype node and all its children
                Element clone = (Element) proto.cloneNode(true);
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }
            }
        } else {
            // Otherwise, append the matches from the old instance document in order
            for (Node old : l) {
                Element oldEl = (Element) old;

                // Copy the old instance element rather than cloning it, so we don't copy over attributes
                Element clone = null;
                String nSUri = oldEl.getNamespaceURI();
                if (nSUri == null) {
                    clone = newInstanceDocument.createElement(oldEl.getTagName());
                } else {
                    clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName());
                }
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }

                // Copy over child text if this is not a complex type
                boolean isEmpty = true;
                for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) {
                    if (n instanceof Text) {
                        clone.appendChild(newInstanceDocument.importNode(n, false));
                        isEmpty = false;
                    } else if (n instanceof Element) {
                        break;
                    }
                }

                // Populate the nil attribute. It may be true or false
                if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) {
                    clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty));
                }

                // Copy over attributes present in the prototype
                NamedNodeMap attributes = proto.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attribute = (Attr) attributes.item(i);
                    String localName = attribute.getLocalName();
                    if (localName == null) {
                        String name = attribute.getName();
                        if (oldEl.hasAttribute(name)) {
                            clone.setAttributeNode(
                                    (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false));
                        } else {
                            LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                    + attribute.getNodeName() + " to "
                                    + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                            clone.setAttributeNode((Attr) attribute.cloneNode(false));
                        }
                    } else {
                        String namespace = attribute.getNamespaceURI();
                        if (!((!isEmpty
                                && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS)
                                        && localName.equals("nil"))
                                || (namespace.equals(NamespaceService.ALFRESCO_URI)
                                        && localName.equals("prototype"))))) {
                            if (oldEl.hasAttributeNS(namespace, localName)) {
                                clone.setAttributeNodeNS((Attr) newInstanceDocument
                                        .importNode(oldEl.getAttributeNodeNS(namespace, localName), false));
                            } else {
                                LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                        + attribute.getNodeName() + " to "
                                        + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                                clone.setAttributeNodeNS((Attr) attribute.cloneNode(false));
                            }
                        }
                    }
                }

                // recurse on children
                rebuildInstance(proto, oldEl, clone, schemaNamespaces);
            }
        }

        // Now add in a new copy of the prototype
        if (isPrototype) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));
            }
            newInstanceNode.appendChild(proto.cloneNode(true));
        }
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

private Element addElementWithMultipleCompatibleTypes(final Document xformsDocument, Element modelSection,
        final Element defaultInstanceElement, final Element formSection, final XSModel schema,
        final XSElementDeclaration elementDecl, final TreeSet<XSTypeDefinition> compatibleTypes,
        final String pathToRoot, final ResourceBundle resourceBundle, final SchemaUtil.Occurrence occurs)
        throws FormBuilderException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[addElementWithMultipleCompatibleTypes] adding element " + elementDecl + " at path "
                + pathToRoot);//from  w w w . jav  a2  s. co m

    // look for compatible types
    final XSTypeDefinition controlType = elementDecl.getTypeDefinition();

    //get possible values
    final List<XSTypeDefinition> enumValues = new LinkedList<XSTypeDefinition>();
    //add the type (if not abstract)
    if (!((XSComplexTypeDefinition) controlType).getAbstract()) {
        enumValues.add(controlType);
    }

    //add compatible types
    enumValues.addAll(compatibleTypes);

    // multiple compatible types for this element exist
    // in the schema - allow the user to choose from
    // between compatible non-abstract types
    boolean isRepeated = isRepeated(occurs, controlType);
    Element bindElement = this.createBind(xformsDocument, pathToRoot + "/@xsi:type");
    String bindId = bindElement.getAttributeNS(null, "id");
    modelSection.appendChild(bindElement);
    this.startBindElement(bindElement, schema, controlType, null, occurs);

    //add the "element" bind, in addition
    final Element bindElement2 = this.createBind(xformsDocument,
            pathToRoot + (isRepeated ? "[position() != last()]" : ""));
    modelSection.appendChild(bindElement2);
    this.startBindElement(bindElement2, schema, controlType, null, occurs);

    // add content to select1
    final Map<String, Element> caseTypes = this.addChoicesForSelectSwitchControl(xformsDocument, formSection,
            enumValues, bindId);

    //add switch
    final Element switchElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":switch");
    switchElement.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":bind",
            bindId);
    switchElement.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":appearance",
            "full");

    formSection.appendChild(switchElement);

    if (!((XSComplexTypeDefinition) controlType).getAbstract()) {
        final Element firstCaseElement = caseTypes.get(controlType.getName());
        switchElement.appendChild(firstCaseElement);
        final Element firstGroupElement = this.addComplexType(xformsDocument, modelSection,
                defaultInstanceElement, firstCaseElement, schema, (XSComplexTypeDefinition) controlType,
                elementDecl, pathToRoot, SchemaUtil.getOccurrence(elementDecl), true, false, resourceBundle);
        firstGroupElement.setAttributeNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":appearance", "");
    }

    defaultInstanceElement.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":type",
            (((XSComplexTypeDefinition) controlType).getAbstract() ? compatibleTypes.first().getName()
                    : controlType.getName()));
    defaultInstanceElement.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", "true");

    /////////////// add sub types //////////////
    // add each compatible type within
    // a case statement
    for (final XSTypeDefinition type : compatibleTypes) {
        final String compatibleTypeName = type.getName();

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(type == null
                    ? ("[addElementWithMultipleCompatibleTypes] compatible type is null!! type = "
                            + compatibleTypeName + ", targetNamespace = " + this.targetNamespace)
                    : ("[addElementWithMultipleCompatibleTypes] adding compatible type " + type.getName()));
        }

        if (type == null || type.getTypeCategory() != XSTypeDefinition.COMPLEX_TYPE) {
            continue;
        }

        final Element caseElement = caseTypes.get(type.getName());
        switchElement.appendChild(caseElement);

        // ALF-9524 fix, add an extra element to the instance for each type that extends the abstract parent
        Element newDefaultInstanceElement = xformsDocument.createElement(getElementName(type, xformsDocument));

        Attr nodesetAttr = modelSection.getAttributeNodeNS(NamespaceConstants.XFORMS_NS, "nodeset");
        // construct the nodeset that is used in bind for abstract type
        String desiredBindNodeset = getElementName(elementDecl, xformsDocument)
                + (isRepeated ? "[position() != last()]" : "");

        // check the current bind
        if (nodesetAttr == null || !nodesetAttr.getValue().equals(desiredBindNodeset)) {
            // look for desired bind in children
            Element newModelSection = DOMUtil.getElementByAttributeValueNS(modelSection,
                    NamespaceConstants.XFORMS_NS, "bind", NamespaceConstants.XFORMS_NS, "nodeset",
                    desiredBindNodeset);

            if (newModelSection == null) {
                // look for absolute path
                desiredBindNodeset = "/" + desiredBindNodeset;
                newModelSection = DOMUtil.getElementByAttributeValueNS(modelSection,
                        NamespaceConstants.XFORMS_NS, "bind", NamespaceConstants.XFORMS_NS, "nodeset",
                        desiredBindNodeset);
            }

            modelSection = newModelSection;
        }

        // create the extra bind for each child of abstract type
        Element bindElement3 = this.createBind(xformsDocument, getElementName(type, xformsDocument));
        modelSection.appendChild(bindElement3);
        bindElement3 = this.startBindElement(bindElement3, schema, controlType, elementDecl, occurs);

        // add the relevant attribute that checks the value of parent' @xsi:type
        bindElement3.setAttributeNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":relevant", "../@xsi:type='" + type.getName() + "'");

        final Element groupElement = this.addComplexType(xformsDocument, modelSection,
                newDefaultInstanceElement, caseElement, schema, (XSComplexTypeDefinition) type, elementDecl,
                pathToRoot, SchemaUtil.getOccurrence(elementDecl), true, true, resourceBundle);
        groupElement.setAttributeNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":appearance", "");

        defaultInstanceElement.appendChild(newDefaultInstanceElement.cloneNode(true));

        // modify bind to add a "relevant" attribute that checks the value of @xsi:type
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addElementWithMultipleCompatibleTypes] Model section =\n"
                    + XMLUtil.toString(bindElement3));
        }

        final NodeList binds = bindElement3.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "bind");
        for (int i = 0; i < binds.getLength(); i++) {
            final Element subBind = (Element) binds.item(i);
            String name = subBind.getAttributeNS(NamespaceConstants.XFORMS_NS, "nodeset");

            // ETHREEOH-3308 fix
            name = repeatableNamePattern.matcher(name).replaceAll("");

            if (!subBind.getParentNode().getAttributes().getNamedItem("id").getNodeValue()
                    .equals(bindElement3.getAttribute("id"))) {
                continue;
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[addElementWithMultipleCompatibleTypes] Testing sub-bind with nodeset " + name);
            }

            Pair<String, String> parsed = parseName(name, xformsDocument);

            if (!SchemaUtil.isElementDeclaredIn(parsed.getFirst(), parsed.getSecond(),
                    (XSComplexTypeDefinition) type, false)
                    && !SchemaUtil.isAttributeDeclaredIn(parsed.getFirst(), parsed.getSecond(),
                            (XSComplexTypeDefinition) type, false)) {
                continue;
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[addElementWithMultipleCompatibleTypes] Element/Attribute " + name
                        + " declared in type " + type.getName() + ": adding relevant attribute");
            }

            //test sub types of this type
            //TreeSet subCompatibleTypes = (TreeSet) typeTree.get(type);

            String newRelevant = "../../@xsi:type='" + type.getName() + "'";
            if (this.typeTree.containsKey(type.getName())) {
                for (XSTypeDefinition otherType : this.typeTree.get(type.getName())) {
                    newRelevant = newRelevant + " or ../../@xsi:type='" + otherType.getName() + "'";
                }
            }

            //change relevant attribute
            final String relevant = subBind.getAttributeNS(NamespaceConstants.XFORMS_NS, "relevant");
            if (relevant != null && relevant.length() != 0) {
                newRelevant = ("(" + relevant + ") and " + newRelevant);
            }
            subBind.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":relevant",
                    newRelevant);
        }
    }
    return switchElement;
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java

/**
 * Creates a <code>DOMReference</code> from an element.
 *
 * @param refElem a Reference element/*from   w w w  .j  a  v a 2s  .  c  o m*/
 */
public DOMReference(Element refElem, XMLCryptoContext context, Provider provider) throws MarshalException {
    Boolean secureValidation = (Boolean) context.getProperty("org.apache.jcp.xml.dsig.secureValidation");
    boolean secVal = false;
    if (secureValidation != null && secureValidation.booleanValue()) {
        secVal = true;
    }

    // unmarshal Transforms, if specified
    Element nextSibling = DOMUtils.getFirstChildElement(refElem);
    List<Transform> transforms = new ArrayList<Transform>(5);
    if (nextSibling.getLocalName().equals("Transforms")) {
        Element transformElem = DOMUtils.getFirstChildElement(nextSibling);

        int transformCount = 0;
        while (transformElem != null) {
            transforms.add(new DOMTransform(transformElem, context, provider));
            transformElem = DOMUtils.getNextSiblingElement(transformElem);

            transformCount++;
            if (secVal && (transformCount > MAXIMUM_TRANSFORM_COUNT)) {
                String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " "
                        + "transforms per Reference are allowed with secure validation";
                throw new MarshalException(error);
            }
        }
        nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
    }

    // unmarshal DigestMethod
    Element dmElem = nextSibling;
    this.digestMethod = DOMDigestMethod.unmarshal(dmElem);
    String digestMethodAlgorithm = this.digestMethod.getAlgorithm();
    if (secVal && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) {
        throw new MarshalException(
                "It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled");
    }

    // unmarshal DigestValue
    try {
        Element dvElem = DOMUtils.getNextSiblingElement(dmElem);
        this.digestValue = Base64.decode(dvElem);
    } catch (Base64DecodingException bde) {
        throw new MarshalException(bde);
    }

    // unmarshal attributes
    this.uri = DOMUtils.getAttributeValue(refElem, "URI");

    Attr attr = refElem.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        this.id = attr.getValue();
        refElem.setIdAttributeNode(attr, true);
    } else {
        this.id = null;
    }

    this.type = DOMUtils.getAttributeValue(refElem, "Type");
    this.here = refElem.getAttributeNodeNS(null, "URI");
    this.refElem = refElem;
    this.transforms = transforms;
    this.allTransforms = transforms;
    this.appliedTransformData = null;
    this.provider = provider;
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Returns the value of an attribute of an element. Returns null if the
 * attribute is not found (whereas Element.getAttributeNS returns "" if an
 * attrib is not found).//from w w w  . j av a 2s  .com
 *
 * @param el Element whose attrib is looked for
 * @param namespaceURI namespace URI of attribute to look for
 * @param localPart local part of attribute to look for
 *
 * @return the attribute value
 */
static public String getAttributeNS(Element el, String namespaceURI, String localPart) {
    String sRet = null;
    Attr attr = el.getAttributeNodeNS(namespaceURI, localPart);
    if (attr != null) {
        sRet = attr.getValue();
    }
    return sRet;
}