Example usage for javax.xml.bind DatatypeConverter parseBoolean

List of usage examples for javax.xml.bind DatatypeConverter parseBoolean

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseBoolean.

Prototype

public static boolean parseBoolean(String lexicalXSDBoolean) 

Source Link

Document

Converts the string argument into a boolean value.

Usage

From source file:net.sf.taverna.t2.uiexts.bioswr.model.HTTPBindingTemplateService.java

private void putUrlEncodedInputs(BindingOperation operation, String method, ArrayNode headersNode,
        StringBuilder url) {/*ww  w  .  jav  a 2 s.  c o  m*/
    Set<String> cited = null;

    String ignoreUncited = operation
            .getExtensionAttribute(HTTPBindingOperationExtensions.HTTP_IGNORE_UNCITED_ATTR);
    if (ignoreUncited == null || !DatatypeConverter.parseBoolean(ignoreUncited)) {
        String location = operation.getExtensionAttribute(HTTPBindingOperationExtensions.HTTP_LOCATION_ATTR);
        if (location != null) {
            cited = new TreeSet<String>();
            Pattern pattern = Pattern.compile("\\{(\\w+\\d*)\\}");
            Matcher m = pattern.matcher(location);
            while (m.find()) {
                cited.add(m.group(1));
            }
        }
    }
    List<BindingMessageReference> inputs = operation.getBindingInputs();
    for (BindingMessageReference input : inputs) {
        writeHeaders(input, headersNode);

        if (cited != null) {
            if ("GET".equals(method) || "DELETE".equals(method)) {
                addUrlEncodedParams(input, cited, url);
            } else {
                headersNode.addObject().put("header", "Content-Type").put("value",
                        "application/x-www-form-urlencoded");
                addUrlEncodedParams(input, cited, url);
            }
        }
    }
}

From source file:com.microsoft.windowsazure.management.network.StaticIPOperationsImpl.java

/**
* The Check Static IP operation retrieves the details for the availability
* of static IP addresses for the given virtual network.
*
* @param networkName Required. The name of the virtual network.
* @param ipAddress Required. The address of the static IP.
* @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./*  w ww . j a v  a2 s  .  com*/
* @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 A response that indicates the availability of a static IP
* address, and if not, provides a list of suggestions.
*/
@Override
public NetworkStaticIPAvailabilityResponse check(String networkName, InetAddress ipAddress)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (networkName == null) {
        throw new NullPointerException("networkName");
    }
    if (ipAddress == null) {
        throw new NullPointerException("ipAddress");
    }

    // 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("networkName", networkName);
        tracingParameters.put("ipAddress", ipAddress);
        CloudTracing.enter(invocationId, this, "checkAsync", 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/";
    url = url + URLEncoder.encode(networkName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("op=checkavailability");
    queryParameters.add("address=" + URLEncoder.encode(ipAddress.getHostAddress(), "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", "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
        NetworkStaticIPAvailabilityResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new NetworkStaticIPAvailabilityResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element addressAvailabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "AddressAvailabilityResponse");
            if (addressAvailabilityResponseElement != null) {
                Element isAvailableElement = XmlUtility.getElementByTagNameNS(
                        addressAvailabilityResponseElement, "http://schemas.microsoft.com/windowsazure",
                        "IsAvailable");
                if (isAvailableElement != null) {
                    boolean isAvailableInstance;
                    isAvailableInstance = DatatypeConverter
                            .parseBoolean(isAvailableElement.getTextContent().toLowerCase());
                    result.setIsAvailable(isAvailableInstance);
                }

                Element availableAddressesSequenceElement = XmlUtility.getElementByTagNameNS(
                        addressAvailabilityResponseElement, "http://schemas.microsoft.com/windowsazure",
                        "AvailableAddresses");
                if (availableAddressesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(availableAddressesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "AvailableAddress")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element availableAddressesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(availableAddressesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "AvailableAddress")
                                .get(i1));
                        result.getAvailableAddresses()
                                .add(InetAddress.getByName(availableAddressesElement.getTextContent()));
                    }
                }
            }

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

@Override
public WebSiteGetPublishProfileResponse getPublishProfile(String webSpaceName, String webSiteName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate/* w  w w  . j a v  a 2s  .c  o  m*/
    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 = "/"
            + (this.getClient().getCredentials().getSubscriptionId() != null
                    ? this.getClient().getCredentials().getSubscriptionId().trim()
                    : "")
            + "/services/WebSpaces/" + webSpaceName.trim() + "/sites/" + webSiteName.trim() + "/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
        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(null, "profileName");
                    if (profileNameAttribute != null) {
                        publishProfileInstance.setProfileName(profileNameAttribute.getValue());
                    }

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

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

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

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

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

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

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

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

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

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

                    Attr controlPanelLinkAttribute = publishProfilesElement.getAttributeNodeNS(null,
                            "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(null, "name");
                            if (nameAttribute != null) {
                                addInstance.setName(nameAttribute.getValue());
                            }

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

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

                            Attr typeAttribute = databasesElement.getAttributeNodeNS(null, "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.sql.ServiceObjectiveOperationsImpl.java

/**
* Returns information about a certain Service Objective with a specific Id.
*
* @param serverName Required. The name of the Azure SQL Database Server to
* be queried.//from  w w w . ja v  a  2 s.c  o  m
* @param serviceObjectiveId Required. The Id of the Service Objective to be
* obtained.
* @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 Response containing the service objective for a given Azure SQL
* Database Server with matching service objective Id.
*/
@Override
public ServiceObjectiveGetResponse get(String serverName, String serviceObjectiveId)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (serviceObjectiveId == null) {
        throw new NullPointerException("serviceObjectiveId");
    }

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

    // Construct URL
    String url = "";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/serviceobjectives/";
    url = url + URLEncoder.encode(serviceObjectiveId, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2012-03-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
        ServiceObjectiveGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceObjectiveGetResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

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

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

                Element isDefaultElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "IsDefault");
                if (isDefaultElement != null) {
                    boolean isDefaultInstance;
                    isDefaultInstance = DatatypeConverter
                            .parseBoolean(isDefaultElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsDefault(isDefaultInstance);
                }

                Element isSystemElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "IsSystem");
                if (isSystemElement != null) {
                    boolean isSystemInstance;
                    isSystemInstance = DatatypeConverter
                            .parseBoolean(isSystemElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsSystem(isSystemInstance);
                }

                Element descriptionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "Description");
                if (descriptionElement != null) {
                    String descriptionInstance;
                    descriptionInstance = descriptionElement.getTextContent();
                    serviceResourceInstance.setDescription(descriptionInstance);
                }

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

                Element dimensionSettingsSequenceElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "DimensionSettings");
                if (dimensionSettingsSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(dimensionSettingsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element dimensionSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(dimensionSettingsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                                .get(i1));
                        ServiceObjective.DimensionSettingResponse serviceResourceInstance2 = new ServiceObjective.DimensionSettingResponse();
                        serviceResourceInstance.getDimensionSettings().add(serviceResourceInstance2);

                        Element idElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                "http://schemas.microsoft.com/windowsazure", "Id");
                        if (idElement2 != null) {
                            String idInstance2;
                            idInstance2 = idElement2.getTextContent();
                            serviceResourceInstance2.setId(idInstance2);
                        }

                        Element descriptionElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                "http://schemas.microsoft.com/windowsazure", "Description");
                        if (descriptionElement2 != null) {
                            String descriptionInstance2;
                            descriptionInstance2 = descriptionElement2.getTextContent();
                            serviceResourceInstance2.setDescription(descriptionInstance2);
                        }

                        Element ordinalElement = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                "http://schemas.microsoft.com/windowsazure", "Ordinal");
                        if (ordinalElement != null) {
                            byte ordinalInstance;
                            ordinalInstance = DatatypeConverter.parseByte(ordinalElement.getTextContent());
                            serviceResourceInstance2.setOrdinal(ordinalInstance);
                        }

                        Element isDefaultElement2 = XmlUtility.getElementByTagNameNS(dimensionSettingsElement,
                                "http://schemas.microsoft.com/windowsazure", "IsDefault");
                        if (isDefaultElement2 != null) {
                            boolean isDefaultInstance2;
                            isDefaultInstance2 = DatatypeConverter
                                    .parseBoolean(isDefaultElement2.getTextContent().toLowerCase());
                            serviceResourceInstance2.setIsDefault(isDefaultInstance2);
                        }

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

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

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

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

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

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

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

/**
* The List Role Sizes operation lists all of the role sizes that are valid
* for your subscription.//from   ww w .  ja v  a  2 s .c o  m
*
* @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 List Role Sizes operation response.
*/
@Override
public RoleSizeListResponse list()
        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, "listAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/rolesizes";
    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-10-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
        RoleSizeListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new RoleSizeListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element roleSizesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "RoleSizes");
            if (roleSizesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(roleSizesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element roleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(roleSizesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "RoleSize")
                            .get(i1));
                    RoleSizeListResponse.RoleSize roleSizeInstance = new RoleSizeListResponse.RoleSize();
                    result.getRoleSizes().add(roleSizeInstance);

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

                    Element labelElement = XmlUtility.getElementByTagNameNS(roleSizesElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent();
                        roleSizeInstance.setLabel(labelInstance);
                    }

                    Element coresElement = XmlUtility.getElementByTagNameNS(roleSizesElement,
                            "http://schemas.microsoft.com/windowsazure", "Cores");
                    if (coresElement != null) {
                        int coresInstance;
                        coresInstance = DatatypeConverter.parseInt(coresElement.getTextContent());
                        roleSizeInstance.setCores(coresInstance);
                    }

                    Element memoryInMbElement = XmlUtility.getElementByTagNameNS(roleSizesElement,
                            "http://schemas.microsoft.com/windowsazure", "MemoryInMb");
                    if (memoryInMbElement != null) {
                        int memoryInMbInstance;
                        memoryInMbInstance = DatatypeConverter.parseInt(memoryInMbElement.getTextContent());
                        roleSizeInstance.setMemoryInMb(memoryInMbInstance);
                    }

                    Element supportedByWebWorkerRolesElement = XmlUtility.getElementByTagNameNS(
                            roleSizesElement, "http://schemas.microsoft.com/windowsazure",
                            "SupportedByWebWorkerRoles");
                    if (supportedByWebWorkerRolesElement != null) {
                        boolean supportedByWebWorkerRolesInstance;
                        supportedByWebWorkerRolesInstance = DatatypeConverter
                                .parseBoolean(supportedByWebWorkerRolesElement.getTextContent().toLowerCase());
                        roleSizeInstance.setSupportedByWebWorkerRoles(supportedByWebWorkerRolesInstance);
                    }

                    Element supportedByVirtualMachinesElement = XmlUtility.getElementByTagNameNS(
                            roleSizesElement, "http://schemas.microsoft.com/windowsazure",
                            "SupportedByVirtualMachines");
                    if (supportedByVirtualMachinesElement != null) {
                        boolean supportedByVirtualMachinesInstance;
                        supportedByVirtualMachinesInstance = DatatypeConverter
                                .parseBoolean(supportedByVirtualMachinesElement.getTextContent().toLowerCase());
                        roleSizeInstance.setSupportedByVirtualMachines(supportedByVirtualMachinesInstance);
                    }

                    Element maxDataDiskCountElement = XmlUtility.getElementByTagNameNS(roleSizesElement,
                            "http://schemas.microsoft.com/windowsazure", "MaxDataDiskCount");
                    if (maxDataDiskCountElement != null) {
                        int maxDataDiskCountInstance;
                        maxDataDiskCountInstance = DatatypeConverter
                                .parseInt(maxDataDiskCountElement.getTextContent());
                        roleSizeInstance.setMaxDataDiskCount(maxDataDiskCountInstance);
                    }

                    Element webWorkerResourceDiskSizeInMbElement = XmlUtility.getElementByTagNameNS(
                            roleSizesElement, "http://schemas.microsoft.com/windowsazure",
                            "WebWorkerResourceDiskSizeInMb");
                    if (webWorkerResourceDiskSizeInMbElement != null) {
                        int webWorkerResourceDiskSizeInMbInstance;
                        webWorkerResourceDiskSizeInMbInstance = DatatypeConverter
                                .parseInt(webWorkerResourceDiskSizeInMbElement.getTextContent());
                        roleSizeInstance
                                .setWebWorkerResourceDiskSizeInMb(webWorkerResourceDiskSizeInMbInstance);
                    }

                    Element virtualMachineResourceDiskSizeInMbElement = XmlUtility.getElementByTagNameNS(
                            roleSizesElement, "http://schemas.microsoft.com/windowsazure",
                            "VirtualMachineResourceDiskSizeInMb");
                    if (virtualMachineResourceDiskSizeInMbElement != null) {
                        int virtualMachineResourceDiskSizeInMbInstance;
                        virtualMachineResourceDiskSizeInMbInstance = DatatypeConverter
                                .parseInt(virtualMachineResourceDiskSizeInMbElement.getTextContent());
                        roleSizeInstance.setVirtualMachineResourceDiskSizeInMb(
                                virtualMachineResourceDiskSizeInMbInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

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

/**
* The List Operating Systems operation lists the versions of the guest
* operating system that are currently available in Windows Azure. The
* 2010-10-28 version of List Operating Systems also indicates what family
* an operating system version belongs to. Currently Azure supports two
* operating system families: the Azure guest operating system that is
* substantially compatible with Windows Server 2008 SP2, and the Azure
* guest operating system that is substantially compatible with Windows
* Server 2008 R2.  (see//from  ww w  .  ja va  2 s  .  c om
* http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx for
* more information)
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The List Operating Systems operation response.
*/
@Override
public OperatingSystemListResponse list()
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // 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, "listAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operatingsystems";
    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
        OperatingSystemListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new OperatingSystemListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element operatingSystemsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OperatingSystems");
            if (operatingSystemsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element operatingSystemsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                            .get(i1));
                    OperatingSystemListResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListResponse.OperatingSystem();
                    result.getOperatingSystems().add(operatingSystemInstance);

                    Element versionElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                            "http://schemas.microsoft.com/windowsazure", "Version");
                    if (versionElement != null) {
                        String versionInstance;
                        versionInstance = versionElement.getTextContent();
                        operatingSystemInstance.setVersion(versionInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent() != null
                                ? new String(Base64.decode(labelElement.getTextContent()))
                                : null;
                        operatingSystemInstance.setLabel(labelInstance);
                    }

                    Element isDefaultElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsDefault");
                    if (isDefaultElement != null) {
                        boolean isDefaultInstance;
                        isDefaultInstance = DatatypeConverter
                                .parseBoolean(isDefaultElement.getTextContent().toLowerCase());
                        operatingSystemInstance.setIsDefault(isDefaultInstance);
                    }

                    Element isActiveElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsActive");
                    if (isActiveElement != null) {
                        boolean isActiveInstance;
                        isActiveInstance = DatatypeConverter
                                .parseBoolean(isActiveElement.getTextContent().toLowerCase());
                        operatingSystemInstance.setIsActive(isActiveInstance);
                    }

                    Element familyElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                            "http://schemas.microsoft.com/windowsazure", "Family");
                    if (familyElement != null) {
                        int familyInstance;
                        familyInstance = DatatypeConverter.parseInt(familyElement.getTextContent());
                        operatingSystemInstance.setFamily(familyInstance);
                    }

                    Element familyLabelElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                            "http://schemas.microsoft.com/windowsazure", "FamilyLabel");
                    if (familyLabelElement != null) {
                        String familyLabelInstance;
                        familyLabelInstance = familyLabelElement.getTextContent() != null
                                ? new String(Base64.decode(familyLabelElement.getTextContent()))
                                : null;
                        operatingSystemInstance.setFamilyLabel(familyLabelInstance);
                    }
                }
            }

        }
        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.servicebus.NamespaceOperationsImpl.java

/**
* Checks the availability of the given service namespace across all Windows
* Azure subscriptions. This is useful because the domain name is created
* based on the service namespace name.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx for
* more information)//w  w  w .java 2 s .co  m
*
* @param namespaceName Required. The namespace name.
* @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 a query for the availability status of a
* namespace name.
*/
@Override
public CheckNamespaceAvailabilityResponse checkAvailability(String namespaceName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }

    // 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("namespaceName", namespaceName);
        CloudTracing.enter(invocationId, this, "checkAvailabilityAsync", 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/ServiceBus/CheckNamespaceAvailability";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("namespace=" + URLEncoder.encode(namespaceName, "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("Accept", "application/atom+xml");
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("x-ms-version", "2013-06-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
        CheckNamespaceAvailabilityResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new CheckNamespaceAvailabilityResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element entryElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement != null) {
                Element contentElement = XmlUtility.getElementByTagNameNS(entryElement,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement != null) {
                    Element namespaceAvailabilityElement = XmlUtility.getElementByTagNameNS(contentElement,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "NamespaceAvailability");
                    if (namespaceAvailabilityElement != null) {
                        Element resultElement = XmlUtility.getElementByTagNameNS(namespaceAvailabilityElement,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Result");
                        if (resultElement != null) {
                            boolean resultInstance;
                            resultInstance = DatatypeConverter
                                    .parseBoolean(resultElement.getTextContent().toLowerCase());
                            result.setIsAvailable(resultInstance);
                        }

                        Element reasonDetailElement = XmlUtility.getElementByTagNameNS(
                                namespaceAvailabilityElement,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ReasonDetail");
                        if (reasonDetailElement != null) {
                            String reasonDetailInstance;
                            reasonDetailInstance = reasonDetailElement.getTextContent();
                            result.setReasonDetails(reasonDetailInstance);
                        }
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

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

/**
* The List Resource Extensions operation lists the resource extensions that
* are available to add to a Virtual Machine. In Azure, a process can run
* as a resource extension of a Virtual Machine. For example, Remote
* Desktop Access or the Azure Diagnostics Agent can run as resource
* extensions to the Virtual Machine.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx for
* more information)//from ww  w.  j a  va2s .c o  m
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The List Resource Extensions operation response.
*/
@Override
public VirtualMachineExtensionListResponse list()
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // 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, "listAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/resourceextensions";
    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
        VirtualMachineExtensionListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualMachineExtensionListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element resourceExtensionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ResourceExtensions");
            if (resourceExtensionsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element resourceExtensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                            .get(i1));
                    VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension();
                    result.getResourceExtensions().add(resourceExtensionInstance);

                    Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Publisher");
                    if (publisherElement != null) {
                        String publisherInstance;
                        publisherInstance = publisherElement.getTextContent();
                        resourceExtensionInstance.setPublisher(publisherInstance);
                    }

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

                    Element versionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Version");
                    if (versionElement != null) {
                        String versionInstance;
                        versionInstance = versionElement.getTextContent();
                        resourceExtensionInstance.setVersion(versionInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent();
                        resourceExtensionInstance.setLabel(labelInstance);
                    }

                    Element descriptionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Description");
                    if (descriptionElement != null) {
                        String descriptionInstance;
                        descriptionInstance = descriptionElement.getTextContent();
                        resourceExtensionInstance.setDescription(descriptionInstance);
                    }

                    Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PublicConfigurationSchema");
                    if (publicConfigurationSchemaElement != null) {
                        String publicConfigurationSchemaInstance;
                        publicConfigurationSchemaInstance = publicConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(publicConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPublicConfigurationSchema(publicConfigurationSchemaInstance);
                    }

                    Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PrivateConfigurationSchema");
                    if (privateConfigurationSchemaElement != null) {
                        String privateConfigurationSchemaInstance;
                        privateConfigurationSchemaInstance = privateConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(privateConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPrivateConfigurationSchema(privateConfigurationSchemaInstance);
                    }

                    Element sampleConfigElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SampleConfig");
                    if (sampleConfigElement != null) {
                        String sampleConfigInstance;
                        sampleConfigInstance = sampleConfigElement.getTextContent() != null
                                ? new String(Base64.decode(sampleConfigElement.getTextContent()))
                                : null;
                        resourceExtensionInstance.setSampleConfig(sampleConfigInstance);
                    }

                    Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "ReplicationCompleted");
                    if (replicationCompletedElement != null
                            && replicationCompletedElement.getTextContent() != null
                            && !replicationCompletedElement.getTextContent().isEmpty()) {
                        boolean replicationCompletedInstance;
                        replicationCompletedInstance = DatatypeConverter
                                .parseBoolean(replicationCompletedElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setReplicationCompleted(replicationCompletedInstance);
                    }

                    Element eulaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement != null) {
                        URI eulaInstance;
                        eulaInstance = new URI(eulaElement.getTextContent());
                        resourceExtensionInstance.setEula(eulaInstance);
                    }

                    Element privacyUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement.getTextContent());
                        resourceExtensionInstance.setPrivacyUri(privacyUriInstance);
                    }

                    Element homepageUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "HomepageUri");
                    if (homepageUriElement != null) {
                        URI homepageUriInstance;
                        homepageUriInstance = new URI(homepageUriElement.getTextContent());
                        resourceExtensionInstance.setHomepageUri(homepageUriInstance);
                    }

                    Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsJsonExtension");
                    if (isJsonExtensionElement != null && isJsonExtensionElement.getTextContent() != null
                            && !isJsonExtensionElement.getTextContent().isEmpty()) {
                        boolean isJsonExtensionInstance;
                        isJsonExtensionInstance = DatatypeConverter
                                .parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsJsonExtension(isJsonExtensionInstance);
                    }

                    Element isInternalExtensionElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "IsInternalExtension");
                    if (isInternalExtensionElement != null
                            && isInternalExtensionElement.getTextContent() != null
                            && !isInternalExtensionElement.getTextContent().isEmpty()) {
                        boolean isInternalExtensionInstance;
                        isInternalExtensionInstance = DatatypeConverter
                                .parseBoolean(isInternalExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsInternalExtension(isInternalExtensionInstance);
                    }

                    Element disallowMajorVersionUpgradeElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "DisallowMajorVersionUpgrade");
                    if (disallowMajorVersionUpgradeElement != null
                            && disallowMajorVersionUpgradeElement.getTextContent() != null
                            && !disallowMajorVersionUpgradeElement.getTextContent().isEmpty()) {
                        boolean disallowMajorVersionUpgradeInstance;
                        disallowMajorVersionUpgradeInstance = DatatypeConverter.parseBoolean(
                                disallowMajorVersionUpgradeElement.getTextContent().toLowerCase());
                        resourceExtensionInstance
                                .setDisallowMajorVersionUpgrade(disallowMajorVersionUpgradeInstance);
                    }

                    Element supportedOSElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SupportedOS");
                    if (supportedOSElement != null) {
                        String supportedOSInstance;
                        supportedOSInstance = supportedOSElement.getTextContent();
                        resourceExtensionInstance.setSupportedOS(supportedOSInstance);
                    }

                    Element companyNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "CompanyName");
                    if (companyNameElement != null) {
                        String companyNameInstance;
                        companyNameInstance = companyNameElement.getTextContent();
                        resourceExtensionInstance.setCompanyName(companyNameInstance);
                    }

                    Element publishedDateElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement != null && publishedDateElement.getTextContent() != null
                            && !publishedDateElement.getTextContent().isEmpty()) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement.getTextContent());
                        resourceExtensionInstance.setPublishedDate(publishedDateInstance);
                    }

                    Element regionsElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Regions");
                    if (regionsElement != null) {
                        String regionsInstance;
                        regionsInstance = regionsElement.getTextContent();
                        resourceExtensionInstance.setRegions(regionsInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.microsoft.windowsazure.management.sql.DatabaseCopyOperationsImpl.java

/**
* Starts a SQL Server database copy./*  w ww.j a v  a  2s  .c om*/
*
* @param serverName Required. The name of the SQL Server where the source
* database resides.
* @param databaseName Required. The name of the source database.
* @param parameters Required. The additional parameters for the create
* database copy operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents a response to the create request.
*/
@Override
public DatabaseCopyCreateResponse create(String serverName, String databaseName,
        DatabaseCopyCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPartnerDatabase() == null) {
        throw new NullPointerException("parameters.PartnerDatabase");
    }
    if (parameters.getPartnerServer() == null) {
        throw new NullPointerException("parameters.PartnerServer");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/databasecopies";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

    Element partnerServerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PartnerServer");
    partnerServerElement.appendChild(requestDoc.createTextNode(parameters.getPartnerServer()));
    serviceResourceElement.appendChild(partnerServerElement);

    Element partnerDatabaseElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PartnerDatabase");
    partnerDatabaseElement.appendChild(requestDoc.createTextNode(parameters.getPartnerDatabase()));
    serviceResourceElement.appendChild(partnerDatabaseElement);

    Element isContinuousElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsContinuous");
    isContinuousElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isContinuous()).toLowerCase()));
    serviceResourceElement.appendChild(isContinuousElement);

    Element isOfflineSecondaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsOfflineSecondary");
    isOfflineSecondaryElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(parameters.isOfflineSecondary()).toLowerCase()));
    serviceResourceElement.appendChild(isOfflineSecondaryElement);

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

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

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

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

                Element sourceServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceServerName");
                if (sourceServerNameElement != null) {
                    String sourceServerNameInstance;
                    sourceServerNameInstance = sourceServerNameElement.getTextContent();
                    serviceResourceInstance.setSourceServerName(sourceServerNameInstance);
                }

                Element sourceDatabaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName");
                if (sourceDatabaseNameElement != null) {
                    String sourceDatabaseNameInstance;
                    sourceDatabaseNameInstance = sourceDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance);
                }

                Element destinationServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "DestinationServerName");
                if (destinationServerNameElement != null) {
                    String destinationServerNameInstance;
                    destinationServerNameInstance = destinationServerNameElement.getTextContent();
                    serviceResourceInstance.setDestinationServerName(destinationServerNameInstance);
                }

                Element destinationDatabaseNameElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "DestinationDatabaseName");
                if (destinationDatabaseNameElement != null) {
                    String destinationDatabaseNameInstance;
                    destinationDatabaseNameInstance = destinationDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setDestinationDatabaseName(destinationDatabaseNameInstance);
                }

                Element isContinuousElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsContinuous");
                if (isContinuousElement2 != null) {
                    boolean isContinuousInstance;
                    isContinuousInstance = DatatypeConverter
                            .parseBoolean(isContinuousElement2.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsContinuous(isContinuousInstance);
                }

                Element replicationStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ReplicationState");
                if (replicationStateElement != null) {
                    byte replicationStateInstance;
                    replicationStateInstance = DatatypeConverter
                            .parseByte(replicationStateElement.getTextContent());
                    serviceResourceInstance.setReplicationState(replicationStateInstance);
                }

                Element replicationStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ReplicationStateDescription");
                if (replicationStateDescriptionElement != null) {
                    String replicationStateDescriptionInstance;
                    replicationStateDescriptionInstance = replicationStateDescriptionElement.getTextContent();
                    serviceResourceInstance.setReplicationStateDescription(replicationStateDescriptionInstance);
                }

                Element localDatabaseIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "LocalDatabaseId");
                if (localDatabaseIdElement != null) {
                    int localDatabaseIdInstance;
                    localDatabaseIdInstance = DatatypeConverter
                            .parseInt(localDatabaseIdElement.getTextContent());
                    serviceResourceInstance.setLocalDatabaseId(localDatabaseIdInstance);
                }

                Element isLocalDatabaseReplicationTargetElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "IsLocalDatabaseReplicationTarget");
                if (isLocalDatabaseReplicationTargetElement != null) {
                    boolean isLocalDatabaseReplicationTargetInstance;
                    isLocalDatabaseReplicationTargetInstance = DatatypeConverter.parseBoolean(
                            isLocalDatabaseReplicationTargetElement.getTextContent().toLowerCase());
                    serviceResourceInstance
                            .setIsLocalDatabaseReplicationTarget(isLocalDatabaseReplicationTargetInstance);
                }

                Element isInterlinkConnectedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsInterlinkConnected");
                if (isInterlinkConnectedElement != null) {
                    boolean isInterlinkConnectedInstance;
                    isInterlinkConnectedInstance = DatatypeConverter
                            .parseBoolean(isInterlinkConnectedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsInterlinkConnected(isInterlinkConnectedInstance);
                }

                Element startDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartDate");
                if (startDateElement != null) {
                    String startDateInstance;
                    startDateInstance = startDateElement.getTextContent();
                    serviceResourceInstance.setStartDate(startDateInstance);
                }

                Element modifyDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ModifyDate");
                if (modifyDateElement != null) {
                    String modifyDateInstance;
                    modifyDateInstance = modifyDateElement.getTextContent();
                    serviceResourceInstance.setModifyDate(modifyDateInstance);
                }

                Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "PercentComplete");
                if (percentCompleteElement != null) {
                    float percentCompleteInstance;
                    percentCompleteInstance = DatatypeConverter
                            .parseFloat(percentCompleteElement.getTextContent());
                    serviceResourceInstance.setPercentComplete(percentCompleteInstance);
                }

                Element isOfflineSecondaryElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsOfflineSecondary");
                if (isOfflineSecondaryElement2 != null) {
                    boolean isOfflineSecondaryInstance;
                    isOfflineSecondaryInstance = DatatypeConverter
                            .parseBoolean(isOfflineSecondaryElement2.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsOfflineSecondary(isOfflineSecondaryInstance);
                }

                Element isTerminationAllowedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsTerminationAllowed");
                if (isTerminationAllowedElement != null) {
                    boolean isTerminationAllowedInstance;
                    isTerminationAllowedInstance = DatatypeConverter
                            .parseBoolean(isTerminationAllowedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsTerminationAllowed(isTerminationAllowedInstance);
                }

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

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

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

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.microsoft.windowsazure.management.sql.DatabaseOperationsImpl.java

/**
* Creates a database in an Azure SQL Database Server.
*
* @param serverName Required. The name of the Azure SQL Database Server
* where the database will be created.//  w  w w  .j  a va 2s.  com
* @param parameters Required. The parameters for the create database
* operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the response to a create database request from the
* service.
*/
@Override
public DatabaseCreateResponse create(String serverName, DatabaseCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}