Example usage for javax.xml.bind DatatypeConverter parseInt

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

Introduction

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

Prototype

public static int parseInt(String lexicalXSDInt) 

Source Link

Document

Convert the string argument into an int value.

Usage

From source file:com.microsoft.azure.management.network.VirtualNetworkOperationsImpl.java

/**
* The Put VirtualNetwork operation creates/updates a virtual network in the
* specified resource group.// w  w w . j a  v  a2 s  .com
*
* @param resourceGroupName Required. The name of the resource group.
* @param virtualNetworkName Required. The name of the virtual network.
* @param parameters Required. Parameters supplied to the create/update
* Virtual Network operation
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Response for PutVirtualNetworks API service calls.
*/
@Override
public VirtualNetworkPutResponse beginCreateOrUpdating(String resourceGroupName, String virtualNetworkName,
        VirtualNetwork parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (virtualNetworkName == null) {
        throw new NullPointerException("virtualNetworkName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    if (parameters.getSubnets() != null) {
        for (Subnet subnetsParameterItem : parameters.getSubnets()) {
            if (subnetsParameterItem.getAddressPrefix() == null) {
                throw new NullPointerException("parameters.Subnets.AddressPrefix");
            }
        }
    }

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

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

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

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

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode virtualNetworkJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = virtualNetworkJsonFormatValue;

    ObjectNode propertiesValue = objectMapper.createObjectNode();
    ((ObjectNode) virtualNetworkJsonFormatValue).put("properties", propertiesValue);

    if (parameters.getAddressSpace() != null) {
        ObjectNode addressSpaceValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("addressSpace", addressSpaceValue);

        if (parameters.getAddressSpace().getAddressPrefixes() != null) {
            if (parameters.getAddressSpace().getAddressPrefixes() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getAddressSpace().getAddressPrefixes()).isInitialized()) {
                ArrayNode addressPrefixesArray = objectMapper.createArrayNode();
                for (String addressPrefixesItem : parameters.getAddressSpace().getAddressPrefixes()) {
                    addressPrefixesArray.add(addressPrefixesItem);
                }
                ((ObjectNode) addressSpaceValue).put("addressPrefixes", addressPrefixesArray);
            }
        }
    }

    if (parameters.getDhcpOptions() != null) {
        ObjectNode dhcpOptionsValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("dhcpOptions", dhcpOptionsValue);

        if (parameters.getDhcpOptions().getDnsServers() != null) {
            if (parameters.getDhcpOptions().getDnsServers() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getDhcpOptions().getDnsServers()).isInitialized()) {
                ArrayNode dnsServersArray = objectMapper.createArrayNode();
                for (String dnsServersItem : parameters.getDhcpOptions().getDnsServers()) {
                    dnsServersArray.add(dnsServersItem);
                }
                ((ObjectNode) dhcpOptionsValue).put("dnsServers", dnsServersArray);
            }
        }
    }

    if (parameters.getSubnets() != null) {
        if (parameters.getSubnets() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getSubnets()).isInitialized()) {
            ArrayNode subnetsArray = objectMapper.createArrayNode();
            for (Subnet subnetsItem : parameters.getSubnets()) {
                ObjectNode subnetJsonFormatValue = objectMapper.createObjectNode();
                subnetsArray.add(subnetJsonFormatValue);

                ObjectNode propertiesValue2 = objectMapper.createObjectNode();
                ((ObjectNode) subnetJsonFormatValue).put("properties", propertiesValue2);

                ((ObjectNode) propertiesValue2).put("addressPrefix", subnetsItem.getAddressPrefix());

                if (subnetsItem.getNetworkSecurityGroup() != null) {
                    ObjectNode networkSecurityGroupValue = objectMapper.createObjectNode();
                    ((ObjectNode) propertiesValue2).put("networkSecurityGroup", networkSecurityGroupValue);

                    if (subnetsItem.getNetworkSecurityGroup().getId() != null) {
                        ((ObjectNode) networkSecurityGroupValue).put("id",
                                subnetsItem.getNetworkSecurityGroup().getId());
                    }
                }

                if (subnetsItem.getRouteTable() != null) {
                    ObjectNode routeTableValue = objectMapper.createObjectNode();
                    ((ObjectNode) propertiesValue2).put("routeTable", routeTableValue);

                    if (subnetsItem.getRouteTable().getId() != null) {
                        ((ObjectNode) routeTableValue).put("id", subnetsItem.getRouteTable().getId());
                    }
                }

                if (subnetsItem.getIpConfigurations() != null) {
                    if (subnetsItem.getIpConfigurations() instanceof LazyCollection == false
                            || ((LazyCollection) subnetsItem.getIpConfigurations()).isInitialized()) {
                        ArrayNode ipConfigurationsArray = objectMapper.createArrayNode();
                        for (ResourceId ipConfigurationsItem : subnetsItem.getIpConfigurations()) {
                            ObjectNode resourceIdValue = objectMapper.createObjectNode();
                            ipConfigurationsArray.add(resourceIdValue);

                            if (ipConfigurationsItem.getId() != null) {
                                ((ObjectNode) resourceIdValue).put("id", ipConfigurationsItem.getId());
                            }
                        }
                        ((ObjectNode) propertiesValue2).put("ipConfigurations", ipConfigurationsArray);
                    }
                }

                if (subnetsItem.getProvisioningState() != null) {
                    ((ObjectNode) propertiesValue2).put("provisioningState",
                            subnetsItem.getProvisioningState());
                }

                if (subnetsItem.getName() != null) {
                    ((ObjectNode) subnetJsonFormatValue).put("name", subnetsItem.getName());
                }

                if (subnetsItem.getEtag() != null) {
                    ((ObjectNode) subnetJsonFormatValue).put("etag", subnetsItem.getEtag());
                }

                if (subnetsItem.getId() != null) {
                    ((ObjectNode) subnetJsonFormatValue).put("id", subnetsItem.getId());
                }
            }
            ((ObjectNode) propertiesValue).put("subnets", subnetsArray);
        }
    }

    if (parameters.getResourceGuid() != null) {
        ((ObjectNode) propertiesValue).put("resourceGuid", parameters.getResourceGuid());
    }

    if (parameters.getProvisioningState() != null) {
        ((ObjectNode) propertiesValue).put("provisioningState", parameters.getProvisioningState());
    }

    if (parameters.getEtag() != null) {
        ((ObjectNode) virtualNetworkJsonFormatValue).put("etag", parameters.getEtag());
    }

    if (parameters.getId() != null) {
        ((ObjectNode) virtualNetworkJsonFormatValue).put("id", parameters.getId());
    }

    if (parameters.getName() != null) {
        ((ObjectNode) virtualNetworkJsonFormatValue).put("name", parameters.getName());
    }

    if (parameters.getType() != null) {
        ((ObjectNode) virtualNetworkJsonFormatValue).put("type", parameters.getType());
    }

    ((ObjectNode) virtualNetworkJsonFormatValue).put("location", parameters.getLocation());

    if (parameters.getTags() != null) {
        ObjectNode tagsDictionary = objectMapper.createObjectNode();
        for (Map.Entry<String, String> entry : parameters.getTags().entrySet()) {
            String tagsKey = entry.getKey();
            String tagsValue = entry.getValue();
            ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue);
        }
        ((ObjectNode) virtualNetworkJsonFormatValue).put("tags", tagsDictionary);
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json");

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

        // Create Result
        VirtualNetworkPutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualNetworkPutResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                VirtualNetwork virtualNetworkInstance = new VirtualNetwork();
                result.setVirtualNetwork(virtualNetworkInstance);

                JsonNode propertiesValue3 = responseDoc.get("properties");
                if (propertiesValue3 != null && propertiesValue3 instanceof NullNode == false) {
                    JsonNode addressSpaceValue2 = propertiesValue3.get("addressSpace");
                    if (addressSpaceValue2 != null && addressSpaceValue2 instanceof NullNode == false) {
                        AddressSpace addressSpaceInstance = new AddressSpace();
                        virtualNetworkInstance.setAddressSpace(addressSpaceInstance);

                        JsonNode addressPrefixesArray2 = addressSpaceValue2.get("addressPrefixes");
                        if (addressPrefixesArray2 != null
                                && addressPrefixesArray2 instanceof NullNode == false) {
                            for (JsonNode addressPrefixesValue : ((ArrayNode) addressPrefixesArray2)) {
                                addressSpaceInstance.getAddressPrefixes()
                                        .add(addressPrefixesValue.getTextValue());
                            }
                        }
                    }

                    JsonNode dhcpOptionsValue2 = propertiesValue3.get("dhcpOptions");
                    if (dhcpOptionsValue2 != null && dhcpOptionsValue2 instanceof NullNode == false) {
                        DhcpOptions dhcpOptionsInstance = new DhcpOptions();
                        virtualNetworkInstance.setDhcpOptions(dhcpOptionsInstance);

                        JsonNode dnsServersArray2 = dhcpOptionsValue2.get("dnsServers");
                        if (dnsServersArray2 != null && dnsServersArray2 instanceof NullNode == false) {
                            for (JsonNode dnsServersValue : ((ArrayNode) dnsServersArray2)) {
                                dhcpOptionsInstance.getDnsServers().add(dnsServersValue.getTextValue());
                            }
                        }
                    }

                    JsonNode subnetsArray2 = propertiesValue3.get("subnets");
                    if (subnetsArray2 != null && subnetsArray2 instanceof NullNode == false) {
                        for (JsonNode subnetsValue : ((ArrayNode) subnetsArray2)) {
                            Subnet subnetJsonFormatInstance = new Subnet();
                            virtualNetworkInstance.getSubnets().add(subnetJsonFormatInstance);

                            JsonNode propertiesValue4 = subnetsValue.get("properties");
                            if (propertiesValue4 != null && propertiesValue4 instanceof NullNode == false) {
                                JsonNode addressPrefixValue = propertiesValue4.get("addressPrefix");
                                if (addressPrefixValue != null
                                        && addressPrefixValue instanceof NullNode == false) {
                                    String addressPrefixInstance;
                                    addressPrefixInstance = addressPrefixValue.getTextValue();
                                    subnetJsonFormatInstance.setAddressPrefix(addressPrefixInstance);
                                }

                                JsonNode networkSecurityGroupValue2 = propertiesValue4
                                        .get("networkSecurityGroup");
                                if (networkSecurityGroupValue2 != null
                                        && networkSecurityGroupValue2 instanceof NullNode == false) {
                                    ResourceId networkSecurityGroupInstance = new ResourceId();
                                    subnetJsonFormatInstance
                                            .setNetworkSecurityGroup(networkSecurityGroupInstance);

                                    JsonNode idValue = networkSecurityGroupValue2.get("id");
                                    if (idValue != null && idValue instanceof NullNode == false) {
                                        String idInstance;
                                        idInstance = idValue.getTextValue();
                                        networkSecurityGroupInstance.setId(idInstance);
                                    }
                                }

                                JsonNode routeTableValue2 = propertiesValue4.get("routeTable");
                                if (routeTableValue2 != null && routeTableValue2 instanceof NullNode == false) {
                                    ResourceId routeTableInstance = new ResourceId();
                                    subnetJsonFormatInstance.setRouteTable(routeTableInstance);

                                    JsonNode idValue2 = routeTableValue2.get("id");
                                    if (idValue2 != null && idValue2 instanceof NullNode == false) {
                                        String idInstance2;
                                        idInstance2 = idValue2.getTextValue();
                                        routeTableInstance.setId(idInstance2);
                                    }
                                }

                                JsonNode ipConfigurationsArray2 = propertiesValue4.get("ipConfigurations");
                                if (ipConfigurationsArray2 != null
                                        && ipConfigurationsArray2 instanceof NullNode == false) {
                                    for (JsonNode ipConfigurationsValue : ((ArrayNode) ipConfigurationsArray2)) {
                                        ResourceId resourceIdInstance = new ResourceId();
                                        subnetJsonFormatInstance.getIpConfigurations().add(resourceIdInstance);

                                        JsonNode idValue3 = ipConfigurationsValue.get("id");
                                        if (idValue3 != null && idValue3 instanceof NullNode == false) {
                                            String idInstance3;
                                            idInstance3 = idValue3.getTextValue();
                                            resourceIdInstance.setId(idInstance3);
                                        }
                                    }
                                }

                                JsonNode provisioningStateValue = propertiesValue4.get("provisioningState");
                                if (provisioningStateValue != null
                                        && provisioningStateValue instanceof NullNode == false) {
                                    String provisioningStateInstance;
                                    provisioningStateInstance = provisioningStateValue.getTextValue();
                                    subnetJsonFormatInstance.setProvisioningState(provisioningStateInstance);
                                }
                            }

                            JsonNode nameValue = subnetsValue.get("name");
                            if (nameValue != null && nameValue instanceof NullNode == false) {
                                String nameInstance;
                                nameInstance = nameValue.getTextValue();
                                subnetJsonFormatInstance.setName(nameInstance);
                            }

                            JsonNode etagValue = subnetsValue.get("etag");
                            if (etagValue != null && etagValue instanceof NullNode == false) {
                                String etagInstance;
                                etagInstance = etagValue.getTextValue();
                                subnetJsonFormatInstance.setEtag(etagInstance);
                            }

                            JsonNode idValue4 = subnetsValue.get("id");
                            if (idValue4 != null && idValue4 instanceof NullNode == false) {
                                String idInstance4;
                                idInstance4 = idValue4.getTextValue();
                                subnetJsonFormatInstance.setId(idInstance4);
                            }
                        }
                    }

                    JsonNode resourceGuidValue = propertiesValue3.get("resourceGuid");
                    if (resourceGuidValue != null && resourceGuidValue instanceof NullNode == false) {
                        String resourceGuidInstance;
                        resourceGuidInstance = resourceGuidValue.getTextValue();
                        virtualNetworkInstance.setResourceGuid(resourceGuidInstance);
                    }

                    JsonNode provisioningStateValue2 = propertiesValue3.get("provisioningState");
                    if (provisioningStateValue2 != null
                            && provisioningStateValue2 instanceof NullNode == false) {
                        String provisioningStateInstance2;
                        provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                        virtualNetworkInstance.setProvisioningState(provisioningStateInstance2);
                    }
                }

                JsonNode etagValue2 = responseDoc.get("etag");
                if (etagValue2 != null && etagValue2 instanceof NullNode == false) {
                    String etagInstance2;
                    etagInstance2 = etagValue2.getTextValue();
                    virtualNetworkInstance.setEtag(etagInstance2);
                }

                JsonNode idValue5 = responseDoc.get("id");
                if (idValue5 != null && idValue5 instanceof NullNode == false) {
                    String idInstance5;
                    idInstance5 = idValue5.getTextValue();
                    virtualNetworkInstance.setId(idInstance5);
                }

                JsonNode nameValue2 = responseDoc.get("name");
                if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                    String nameInstance2;
                    nameInstance2 = nameValue2.getTextValue();
                    virtualNetworkInstance.setName(nameInstance2);
                }

                JsonNode typeValue = responseDoc.get("type");
                if (typeValue != null && typeValue instanceof NullNode == false) {
                    String typeInstance;
                    typeInstance = typeValue.getTextValue();
                    virtualNetworkInstance.setType(typeInstance);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    virtualNetworkInstance.setLocation(locationInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                    while (itr.hasNext()) {
                        Map.Entry<String, JsonNode> property = itr.next();
                        String tagsKey2 = property.getKey();
                        String tagsValue2 = property.getValue().getTextValue();
                        virtualNetworkInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }

                JsonNode errorValue = responseDoc.get("error");
                if (errorValue != null && errorValue instanceof NullNode == false) {
                    Error errorInstance = new Error();
                    result.setError(errorInstance);

                    JsonNode codeValue = errorValue.get("code");
                    if (codeValue != null && codeValue instanceof NullNode == false) {
                        String codeInstance;
                        codeInstance = codeValue.getTextValue();
                        errorInstance.setCode(codeInstance);
                    }

                    JsonNode messageValue = errorValue.get("message");
                    if (messageValue != null && messageValue instanceof NullNode == false) {
                        String messageInstance;
                        messageInstance = messageValue.getTextValue();
                        errorInstance.setMessage(messageInstance);
                    }

                    JsonNode targetValue = errorValue.get("target");
                    if (targetValue != null && targetValue instanceof NullNode == false) {
                        String targetInstance;
                        targetInstance = targetValue.getTextValue();
                        errorInstance.setTarget(targetInstance);
                    }

                    JsonNode detailsArray = errorValue.get("details");
                    if (detailsArray != null && detailsArray instanceof NullNode == false) {
                        for (JsonNode detailsValue : ((ArrayNode) detailsArray)) {
                            ErrorDetails errorDetailsInstance = new ErrorDetails();
                            errorInstance.getDetails().add(errorDetailsInstance);

                            JsonNode codeValue2 = detailsValue.get("code");
                            if (codeValue2 != null && codeValue2 instanceof NullNode == false) {
                                String codeInstance2;
                                codeInstance2 = codeValue2.getTextValue();
                                errorDetailsInstance.setCode(codeInstance2);
                            }

                            JsonNode targetValue2 = detailsValue.get("target");
                            if (targetValue2 != null && targetValue2 instanceof NullNode == false) {
                                String targetInstance2;
                                targetInstance2 = targetValue2.getTextValue();
                                errorDetailsInstance.setTarget(targetInstance2);
                            }

                            JsonNode messageValue2 = detailsValue.get("message");
                            if (messageValue2 != null && messageValue2 instanceof NullNode == false) {
                                String messageInstance2;
                                messageInstance2 = messageValue2.getTextValue();
                                errorDetailsInstance.setMessage(messageInstance2);
                            }
                        }
                    }

                    JsonNode innerErrorValue = errorValue.get("innerError");
                    if (innerErrorValue != null && innerErrorValue instanceof NullNode == false) {
                        String innerErrorInstance;
                        innerErrorInstance = innerErrorValue.getTextValue();
                        errorInstance.setInnerError(innerErrorInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Azure-AsyncOperation").length > 0) {
            result.setAzureAsyncOperation(httpResponse.getFirstHeader("Azure-AsyncOperation").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        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.DatabaseOperationOperationsImpl.java

/**
* Retrieves all of the operations that occured on the Azure SQL Database
* Server.//from  ww  w  . j  a va2  s  . c  o m
*
* @param serverName Required. The name of the Azure SQL Database Server to
* be queried.
* @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 Represents the response containing the list of database
* operations for a given server or database.
*/
@Override
public DatabaseOperationListResponse listByServer(String serverName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }

    // 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);
        CloudTracing.enter(invocationId, this, "listByServerAsync", 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 + "/databaseoperations";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("contentview=generic");
    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", "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
        DatabaseOperationListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseOperationListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResources");
            if (serviceResourcesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                            .get(i1));
                    DatabaseOperation serviceResourceInstance = new DatabaseOperation();
                    result.getDatabaseOperations().add(serviceResourceInstance);

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

                    Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "StateId");
                    if (stateIdElement != null) {
                        int stateIdInstance;
                        stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent());
                        serviceResourceInstance.setStateId(stateIdInstance);
                    }

                    Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "SessionActivityId");
                    if (sessionActivityIdElement != null) {
                        String sessionActivityIdInstance;
                        sessionActivityIdInstance = sessionActivityIdElement.getTextContent();
                        serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance);
                    }

                    Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "DatabaseName");
                    if (databaseNameElement != null) {
                        String databaseNameInstance;
                        databaseNameInstance = databaseNameElement.getTextContent();
                        serviceResourceInstance.setDatabaseName(databaseNameInstance);
                    }

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

                    Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "ErrorCode");
                    if (errorCodeElement != null) {
                        int errorCodeInstance;
                        errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent());
                        serviceResourceInstance.setErrorCode(errorCodeInstance);
                    }

                    Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Error");
                    if (errorElement != null) {
                        String errorInstance;
                        errorInstance = errorElement.getTextContent();
                        serviceResourceInstance.setError(errorInstance);
                    }

                    Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "ErrorSeverity");
                    if (errorSeverityElement != null) {
                        int errorSeverityInstance;
                        errorSeverityInstance = DatatypeConverter
                                .parseInt(errorSeverityElement.getTextContent());
                        serviceResourceInstance.setErrorSeverity(errorSeverityInstance);
                    }

                    Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "ErrorState");
                    if (errorStateElement != null) {
                        int errorStateInstance;
                        errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent());
                        serviceResourceInstance.setErrorState(errorStateInstance);
                    }

                    Element startTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "StartTime");
                    if (startTimeElement != null) {
                        Calendar startTimeInstance;
                        startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent());
                        serviceResourceInstance.setStartTime(startTimeInstance);
                    }

                    Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "LastModifyTime");
                    if (lastModifyTimeElement != null) {
                        Calendar lastModifyTimeInstance;
                        lastModifyTimeInstance = DatatypeConverter
                                .parseDateTime(lastModifyTimeElement.getTextContent());
                        serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance);
                    }

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

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

                    Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "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

/**
* Returns information about an Azure SQL Database.
*
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.//from w  w  w  . j  a v a 2  s  .  c  om
* @param databaseName Required. The name of the Azure SQL Database to be
* retrieved.
* @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 Contains the response to a Get Database request.
*/
@Override
public DatabaseGetResponse get(String serverName, String databaseName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }

    // 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);
        CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
    }

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

    // Create HTTP transport objects
    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
        DatabaseGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseGetResponse();
            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) {
                Database serviceResourceInstance = new Database();
                result.setDatabase(serviceResourceInstance);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "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.websites.ServerFarmOperationsImpl.java

/**
* You can create a server farm by issuing an HTTP POST request. Only one
* server farm per webspace is permitted. You can retrieve server farm
* details by using HTTP GET, change server farm properties by using HTTP
* PUT, and delete a server farm by using HTTP DELETE. A request body is
* required for server farm creation (HTTP POST) and server farm update
* (HTTP PUT). Warning: Creating a server farm changes your webspace's
* Compute Mode from Shared to Dedicated. You will be charged from the
* moment the server farm is created, even if all your sites are still
* running in Free mode.  (see/*from w  w w  .  jav  a 2s.  c o m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @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 Server Farm operation response.
*/
@Override
public ServerFarmListResponse list(String webSpaceName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }

    // 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);
        CloudTracing.enter(invocationId, this, "listAsync", tracingParameters);
    }

    // Construct URL
    String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null
            ? this.getClient().getCredentials().getSubscriptionId().trim()
            : "") + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms";
    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;

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

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

        Element serverFarmsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                "http://schemas.microsoft.com/windowsazure", "ServerFarms");
        if (serverFarmsSequenceElement != null) {
            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                    .getElementsByTagNameNS(serverFarmsSequenceElement,
                            "http://schemas.microsoft.com/windowsazure", "ServerFarm")
                    .size(); i1 = i1 + 1) {
                org.w3c.dom.Element serverFarmsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(serverFarmsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ServerFarm")
                        .get(i1));
                ServerFarmListResponse.ServerFarm serverFarmInstance = new ServerFarmListResponse.ServerFarm();
                result.getServerFarms().add(serverFarmInstance);

                Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                        "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
                if (currentNumberOfWorkersElement != null) {
                    int currentNumberOfWorkersInstance;
                    currentNumberOfWorkersInstance = DatatypeConverter
                            .parseInt(currentNumberOfWorkersElement.getTextContent());
                    serverFarmInstance.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
                }

                Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                        "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
                if (currentWorkerSizeElement != null) {
                    ServerFarmWorkerSize currentWorkerSizeInstance;
                    currentWorkerSizeInstance = ServerFarmWorkerSize
                            .valueOf(currentWorkerSizeElement.getTextContent());
                    serverFarmInstance.setCurrentWorkerSize(currentWorkerSizeInstance);
                }

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

                Element numberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                        "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
                if (numberOfWorkersElement != null) {
                    int numberOfWorkersInstance;
                    numberOfWorkersInstance = DatatypeConverter
                            .parseInt(numberOfWorkersElement.getTextContent());
                    serverFarmInstance.setNumberOfWorkers(numberOfWorkersInstance);
                }

                Element workerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                        "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                if (workerSizeElement != null) {
                    ServerFarmWorkerSize workerSizeInstance;
                    workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement.getTextContent());
                    serverFarmInstance.setWorkerSize(workerSizeInstance);
                }

                Element statusElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null) {
                    ServerFarmStatus statusInstance;
                    statusInstance = ServerFarmStatus.valueOf(statusElement.getTextContent());
                    serverFarmInstance.setStatus(statusInstance);
                }
            }
        }

        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

/**
* Retrieves information about a SQL Server database copy.
*
* @param serverName Required. The name of the source or destination SQL
* Server instance.//from  w ww.  ja  v a2s .c  o  m
* @param databaseName Required. The name of the database.
* @param databaseCopyName Required. The unique identifier for the database
* copy to retrieve.
* @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 Represents a response to the get request.
*/
@Override
public DatabaseCopyGetResponse get(String serverName, String databaseName, String databaseCopyName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (databaseCopyName == null) {
        throw new NullPointerException("databaseCopyName");
    }

    // 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("databaseCopyName", databaseCopyName);
        CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/databasecopies/";
    url = url + URLEncoder.encode(databaseCopyName, "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
        DatabaseCopyGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseCopyGetResponse();
            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) {
                DatabaseCopy serviceResourceInstance = new DatabaseCopy();
                result.setDatabaseCopy(serviceResourceInstance);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "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.websites.WebSpaceOperationsImpl.java

/**
* You can list the web spaces under the current subscription by issuing a
* GET request.  (see//from   w  w w. j a v  a  2s.  c  o m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.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.
* @return The List Web Spaces operation response.
*/
@Override
public WebSpacesListResponse 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 + "/services/WebSpaces";
    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
        WebSpacesListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSpacesListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element webSpacesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "WebSpaces");
            if (webSpacesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(webSpacesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "WebSpace")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element webSpacesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(webSpacesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "WebSpace")
                            .get(i1));
                    WebSpacesListResponse.WebSpace webSpaceInstance = new WebSpacesListResponse.WebSpace();
                    result.getWebSpaces().add(webSpaceInstance);

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

                    Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
                    if (currentNumberOfWorkersElement != null
                            && currentNumberOfWorkersElement.getTextContent() != null
                            && !currentNumberOfWorkersElement.getTextContent().isEmpty()) {
                        boolean isNil = false;
                        Attr nilAttribute = currentNumberOfWorkersElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute != null) {
                            isNil = "true".equals(nilAttribute.getValue());
                        }
                        if (isNil == false) {
                            int currentNumberOfWorkersInstance;
                            currentNumberOfWorkersInstance = DatatypeConverter
                                    .parseInt(currentNumberOfWorkersElement.getTextContent());
                            webSpaceInstance.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
                        }
                    }

                    Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
                    if (currentWorkerSizeElement != null && currentWorkerSizeElement.getTextContent() != null
                            && !currentWorkerSizeElement.getTextContent().isEmpty()) {
                        boolean isNil2 = false;
                        Attr nilAttribute2 = currentWorkerSizeElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute2 != null) {
                            isNil2 = "true".equals(nilAttribute2.getValue());
                        }
                        if (isNil2 == false) {
                            WorkerSizeOptions currentWorkerSizeInstance;
                            currentWorkerSizeInstance = WorkerSizeOptions
                                    .valueOf(currentWorkerSizeElement.getTextContent());
                            webSpaceInstance.setCurrentWorkerSize(currentWorkerSizeInstance);
                        }
                    }

                    Element geoLocationElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "GeoLocation");
                    if (geoLocationElement != null) {
                        String geoLocationInstance;
                        geoLocationInstance = geoLocationElement.getTextContent();
                        webSpaceInstance.setGeoLocation(geoLocationInstance);
                    }

                    Element geoRegionElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "GeoRegion");
                    if (geoRegionElement != null) {
                        String geoRegionInstance;
                        geoRegionInstance = geoRegionElement.getTextContent();
                        webSpaceInstance.setGeoRegion(geoRegionInstance);
                    }

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

                    Element planElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "Plan");
                    if (planElement != null) {
                        String planInstance;
                        planInstance = planElement.getTextContent();
                        webSpaceInstance.setPlan(planInstance);
                    }

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

                    Element subscriptionElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "Subscription");
                    if (subscriptionElement != null) {
                        String subscriptionInstance;
                        subscriptionInstance = subscriptionElement.getTextContent();
                        webSpaceInstance.setSubscription(subscriptionInstance);
                    }

                    Element workerSizeElement = XmlUtility.getElementByTagNameNS(webSpacesElement,
                            "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                    if (workerSizeElement != null && workerSizeElement.getTextContent() != null
                            && !workerSizeElement.getTextContent().isEmpty()) {
                        WorkerSizeOptions workerSizeInstance;
                        workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement.getTextContent());
                        webSpaceInstance.setWorkerSize(workerSizeInstance);
                    }
                }
            }

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

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

From source file:com.microsoft.azure.management.network.VirtualNetworkGatewayOperationsImpl.java

/**
* The Delete VirtualNetworkGateway operation deletes the specifed virtual
* network Gateway through Network resource provider.
*
* @param resourceGroupName Required. The name of the resource group.
* @param virtualNetworkGatewayName Required. The name of the virtual
* network gateway.//from   w  ww .  j a  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.
* @return If the resource provide needs to return an error to any
* operation, it should return the appropriate HTTP error code and a
* message body as can be seen below.The message should be localized per
* the Accept-Language header specified in the original request such thatit
* could be directly be exposed to users
*/
@Override
public UpdateOperationResponse beginDeleting(String resourceGroupName, String virtualNetworkGatewayName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (virtualNetworkGatewayName == null) {
        throw new NullPointerException("virtualNetworkGatewayName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Network";
    url = url + "/virtualNetworkGateways/";
    url = url + URLEncoder.encode(virtualNetworkGatewayName, "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-05-01-preview");
    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
    CustomHttpDelete httpRequest = new CustomHttpDelete(url);

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

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

        // Create Result
        UpdateOperationResponse result = null;
        // Deserialize Response
        result = new UpdateOperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Azure-AsyncOperation").length > 0) {
            result.setAzureAsyncOperation(httpResponse.getFirstHeader("Azure-AsyncOperation").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

From source file:com.microsoft.azure.management.network.VirtualNetworkOperationsImpl.java

/**
* The Delete VirtualNetwork operation deletes the specifed virtual network
*
* @param resourceGroupName Required. The name of the resource group.
* @param virtualNetworkName Required. The name of the virtual network.
* @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.//from www. ja va 2s .  c  o m
* @throws ServiceException Thrown if an unexpected response is found.
* @return If the resource provide needs to return an error to any
* operation, it should return the appropriate HTTP error code and a
* message body as can be seen below.The message should be localized per
* the Accept-Language header specified in the original request such thatit
* could be directly be exposed to users
*/
@Override
public UpdateOperationResponse beginDeleting(String resourceGroupName, String virtualNetworkName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (virtualNetworkName == null) {
        throw new NullPointerException("virtualNetworkName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Network";
    url = url + "/virtualnetworks/";
    url = url + URLEncoder.encode(virtualNetworkName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-05-01-preview");
    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
    CustomHttpDelete httpRequest = new CustomHttpDelete(url);

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

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

        // Create Result
        UpdateOperationResponse result = null;
        // Deserialize Response
        result = new UpdateOperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Azure-AsyncOperation").length > 0) {
            result.setAzureAsyncOperation(httpResponse.getFirstHeader("Azure-AsyncOperation").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        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.WebHostingPlanOperationsImpl.java

/**
* You can retrieve historical usage metrics for a site by issuing an HTTP
* GET request.  (see//from   w ww  . j a v  a 2s  . c o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param webHostingPlanName Required. The name of the web hosting plan.
* @param parameters Required. Parameters supplied to the Get Historical
* Usage Metrics Web hosting plan operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The Get Historical Usage Metrics Web hosting plan operation
* response.
*/
@Override
public WebHostingPlanGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName,
        String webHostingPlanName, WebHostingPlanGetHistoricalUsageMetricsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webHostingPlanName == null) {
        throw new NullPointerException("webHostingPlanName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/serverFarms/";
    url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
    url = url + "/metrics";
    ArrayList<String> queryParameters = new ArrayList<String>();
    if (parameters.getMetricNames() != null && parameters.getMetricNames().size() > 0) {
        queryParameters.add("names="
                + URLEncoder.encode(CollectionStringBuilder.join(parameters.getMetricNames(), ","), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getStartTime() != null) {
        queryParameters.add("StartTime="
                + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getEndTime() != null) {
        queryParameters.add("EndTime="
                + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
    }
    if (parameters.getTimeGrain() != null) {
        queryParameters.add("timeGrain=" + URLEncoder.encode(parameters.getTimeGrain(), "UTF-8"));
    }
    queryParameters.add("details=" + URLEncoder
            .encode(Boolean.toString(parameters.isIncludeInstanceBreakdown()).toLowerCase(), "UTF-8"));
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

            Element metricResponsesElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "MetricResponses");
            if (metricResponsesElement != null) {
                if (metricResponsesElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(metricResponsesElement,
                                    "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element usageMetricsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metricResponsesElement,
                                        "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                                .get(i1));
                        HistoricalUsageMetric metricResponseInstance = new HistoricalUsageMetric();
                        result.getUsageMetrics().add(metricResponseInstance);

                        Element codeElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Code");
                        if (codeElement != null) {
                            String codeInstance;
                            codeInstance = codeElement.getTextContent();
                            metricResponseInstance.setCode(codeInstance);
                        }

                        Element dataElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Data");
                        if (dataElement != null) {
                            HistoricalUsageMetricData dataInstance = new HistoricalUsageMetricData();
                            metricResponseInstance.setData(dataInstance);

                            Element displayNameElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "DisplayName");
                            if (displayNameElement != null) {
                                String displayNameInstance;
                                displayNameInstance = displayNameElement.getTextContent();
                                dataInstance.setDisplayName(displayNameInstance);
                            }

                            Element endTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "EndTime");
                            if (endTimeElement != null) {
                                Calendar endTimeInstance;
                                endTimeInstance = DatatypeConverter
                                        .parseDateTime(endTimeElement.getTextContent());
                                dataInstance.setEndTime(endTimeInstance);
                            }

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

                            Element primaryAggregationTypeElement = XmlUtility.getElementByTagNameNS(
                                    dataElement, "http://schemas.microsoft.com/windowsazure",
                                    "PrimaryAggregationType");
                            if (primaryAggregationTypeElement != null) {
                                String primaryAggregationTypeInstance;
                                primaryAggregationTypeInstance = primaryAggregationTypeElement.getTextContent();
                                dataInstance.setPrimaryAggregationType(primaryAggregationTypeInstance);
                            }

                            Element startTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "StartTime");
                            if (startTimeElement != null) {
                                Calendar startTimeInstance;
                                startTimeInstance = DatatypeConverter
                                        .parseDateTime(startTimeElement.getTextContent());
                                dataInstance.setStartTime(startTimeInstance);
                            }

                            Element timeGrainElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "TimeGrain");
                            if (timeGrainElement != null) {
                                String timeGrainInstance;
                                timeGrainInstance = timeGrainElement.getTextContent();
                                dataInstance.setTimeGrain(timeGrainInstance);
                            }

                            Element unitElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "Unit");
                            if (unitElement != null) {
                                String unitInstance;
                                unitInstance = unitElement.getTextContent();
                                dataInstance.setUnit(unitInstance);
                            }

                            Element valuesSequenceElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "Values");
                            if (valuesSequenceElement != null) {
                                for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(valuesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                        .size(); i2 = i2 + 1) {
                                    org.w3c.dom.Element valuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(valuesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                            .get(i2));
                                    HistoricalUsageMetricSample metricSampleInstance = new HistoricalUsageMetricSample();
                                    dataInstance.getValues().add(metricSampleInstance);

                                    Element countElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Count");
                                    if (countElement != null) {
                                        int countInstance;
                                        countInstance = DatatypeConverter
                                                .parseInt(countElement.getTextContent());
                                        metricSampleInstance.setCount(countInstance);
                                    }

                                    Element maximumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Maximum");
                                    if (maximumElement != null) {
                                        boolean isNil = false;
                                        Attr nilAttribute = maximumElement.getAttributeNodeNS(
                                                "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                        if (nilAttribute != null) {
                                            isNil = "true".equals(nilAttribute.getValue());
                                        }
                                        if (isNil == false) {
                                            String maximumInstance;
                                            maximumInstance = maximumElement.getTextContent();
                                            metricSampleInstance.setMaximum(maximumInstance);
                                        }
                                    }

                                    Element minimumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Minimum");
                                    if (minimumElement != null) {
                                        boolean isNil2 = false;
                                        Attr nilAttribute2 = minimumElement.getAttributeNodeNS(
                                                "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                        if (nilAttribute2 != null) {
                                            isNil2 = "true".equals(nilAttribute2.getValue());
                                        }
                                        if (isNil2 == false) {
                                            String minimumInstance;
                                            minimumInstance = minimumElement.getTextContent();
                                            metricSampleInstance.setMinimum(minimumInstance);
                                        }
                                    }

                                    Element timeCreatedElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "TimeCreated");
                                    if (timeCreatedElement != null) {
                                        Calendar timeCreatedInstance;
                                        timeCreatedInstance = DatatypeConverter
                                                .parseDateTime(timeCreatedElement.getTextContent());
                                        metricSampleInstance.setTimeCreated(timeCreatedInstance);
                                    }

                                    Element totalElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Total");
                                    if (totalElement != null) {
                                        String totalInstance;
                                        totalInstance = totalElement.getTextContent();
                                        metricSampleInstance.setTotal(totalInstance);
                                    }

                                    Element instanceNameElement = XmlUtility.getElementByTagNameNS(
                                            valuesElement, "http://schemas.microsoft.com/windowsazure",
                                            "InstanceName");
                                    if (instanceNameElement != null) {
                                        String instanceNameInstance;
                                        instanceNameInstance = instanceNameElement.getTextContent();
                                        metricSampleInstance.setInstanceName(instanceNameInstance);
                                    }
                                }
                            }
                        }

                        Element messageElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Message");
                        if (messageElement != null) {
                            String messageInstance;
                            messageInstance = messageElement.getTextContent();
                            metricResponseInstance.setMessage(messageInstance);
                        }
                    }
                }
            }

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

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

From source file:com.microsoft.azure.management.sql.RecommendedIndexOperationsImpl.java

/**
* We execute or cancel index operations by updating index state. Allowed
* state transitions are :Active          -> Pending          - Start index
* creation processPending         -> Active           - Cancel index
* creationActive/Pending  -> Ignored          - Ignore index
* recommendation so it will no longer show in active
* recommendationsIgnored         -> Active           - Restore index
* recommendationSuccess         -> Pending Revert   - Revert index that
* has been createdPending Revert  -> Revert Canceled  - Cancel index
* revert operation/*from ww  w. j  a v a  2s  . c o  m*/
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the Azure SQL Database Server belongs.
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.
* @param databaseName Required. The name of the Azure SQL Database.
* @param schemaName Required. The name of the Azure SQL Database schema.
* @param tableName Required. The name of the Azure SQL Database table.
* @param indexName Required. The name of the Azure SQL Database recommended
* index.
* @param parameters Required. The required parameters for updating index
* state.
* @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 get recommended index request.
*/
@Override
public RecommendedIndexUpdateResponse update(String resourceGroupName, String serverName, String databaseName,
        String schemaName, String tableName, String indexName, RecommendedIndexUpdateParameters parameters)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (schemaName == null) {
        throw new NullPointerException("schemaName");
    }
    if (tableName == null) {
        throw new NullPointerException("tableName");
    }
    if (indexName == null) {
        throw new NullPointerException("indexName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getProperties() == null) {
        throw new NullPointerException("parameters.Properties");
    }

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

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Sql";
    url = url + "/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/schemas/";
    url = url + URLEncoder.encode(schemaName, "UTF-8");
    url = url + "/tables/";
    url = url + URLEncoder.encode(tableName, "UTF-8");
    url = url + "/recommendedIndexes/";
    url = url + URLEncoder.encode(indexName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode recommendedIndexUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = recommendedIndexUpdateParametersValue;

    ObjectNode propertiesValue = objectMapper.createObjectNode();
    ((ObjectNode) recommendedIndexUpdateParametersValue).put("properties", propertiesValue);

    if (parameters.getProperties().getState() != null) {
        ((ObjectNode) propertiesValue).put("state", parameters.getProperties().getState());
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // 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.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        RecommendedIndexUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new RecommendedIndexUpdateResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                ErrorResponse errorInstance = new ErrorResponse();
                result.setError(errorInstance);

                JsonNode codeValue = responseDoc.get("code");
                if (codeValue != null && codeValue instanceof NullNode == false) {
                    String codeInstance;
                    codeInstance = codeValue.getTextValue();
                    errorInstance.setCode(codeInstance);
                }

                JsonNode messageValue = responseDoc.get("message");
                if (messageValue != null && messageValue instanceof NullNode == false) {
                    String messageInstance;
                    messageInstance = messageValue.getTextValue();
                    errorInstance.setMessage(messageInstance);
                }

                JsonNode targetValue = responseDoc.get("target");
                if (targetValue != null && targetValue instanceof NullNode == false) {
                    String targetInstance;
                    targetInstance = targetValue.getTextValue();
                    errorInstance.setTarget(targetInstance);
                }

                RecommendedIndex recommendedIndexInstance = new RecommendedIndex();
                result.setRecommendedIndex(recommendedIndexInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    RecommendedIndexProperties propertiesInstance = new RecommendedIndexProperties();
                    recommendedIndexInstance.setProperties(propertiesInstance);

                    JsonNode actionValue = propertiesValue2.get("action");
                    if (actionValue != null && actionValue instanceof NullNode == false) {
                        String actionInstance;
                        actionInstance = actionValue.getTextValue();
                        propertiesInstance.setAction(actionInstance);
                    }

                    JsonNode stateValue = propertiesValue2.get("state");
                    if (stateValue != null && stateValue instanceof NullNode == false) {
                        String stateInstance;
                        stateInstance = stateValue.getTextValue();
                        propertiesInstance.setState(stateInstance);
                    }

                    JsonNode createdValue = propertiesValue2.get("created");
                    if (createdValue != null && createdValue instanceof NullNode == false) {
                        Calendar createdInstance;
                        createdInstance = DatatypeConverter.parseDateTime(createdValue.getTextValue());
                        propertiesInstance.setCreated(createdInstance);
                    }

                    JsonNode lastModifiedValue = propertiesValue2.get("lastModified");
                    if (lastModifiedValue != null && lastModifiedValue instanceof NullNode == false) {
                        Calendar lastModifiedInstance;
                        lastModifiedInstance = DatatypeConverter
                                .parseDateTime(lastModifiedValue.getTextValue());
                        propertiesInstance.setLastModified(lastModifiedInstance);
                    }

                    JsonNode indexTypeValue = propertiesValue2.get("indexType");
                    if (indexTypeValue != null && indexTypeValue instanceof NullNode == false) {
                        String indexTypeInstance;
                        indexTypeInstance = indexTypeValue.getTextValue();
                        propertiesInstance.setIndexType(indexTypeInstance);
                    }

                    JsonNode schemaValue = propertiesValue2.get("schema");
                    if (schemaValue != null && schemaValue instanceof NullNode == false) {
                        String schemaInstance;
                        schemaInstance = schemaValue.getTextValue();
                        propertiesInstance.setSchema(schemaInstance);
                    }

                    JsonNode tableValue = propertiesValue2.get("table");
                    if (tableValue != null && tableValue instanceof NullNode == false) {
                        String tableInstance;
                        tableInstance = tableValue.getTextValue();
                        propertiesInstance.setTable(tableInstance);
                    }

                    JsonNode columnsArray = propertiesValue2.get("columns");
                    if (columnsArray != null && columnsArray instanceof NullNode == false) {
                        for (JsonNode columnsValue : ((ArrayNode) columnsArray)) {
                            propertiesInstance.getColumns().add(columnsValue.getTextValue());
                        }
                    }

                    JsonNode includedColumnsArray = propertiesValue2.get("includedColumns");
                    if (includedColumnsArray != null && includedColumnsArray instanceof NullNode == false) {
                        for (JsonNode includedColumnsValue : ((ArrayNode) includedColumnsArray)) {
                            propertiesInstance.getIncludedColumns().add(includedColumnsValue.getTextValue());
                        }
                    }

                    JsonNode indexScriptValue = propertiesValue2.get("indexScript");
                    if (indexScriptValue != null && indexScriptValue instanceof NullNode == false) {
                        String indexScriptInstance;
                        indexScriptInstance = indexScriptValue.getTextValue();
                        propertiesInstance.setIndexScript(indexScriptInstance);
                    }

                    JsonNode estimatedImpactArray = propertiesValue2.get("estimatedImpact");
                    if (estimatedImpactArray != null && estimatedImpactArray instanceof NullNode == false) {
                        for (JsonNode estimatedImpactValue : ((ArrayNode) estimatedImpactArray)) {
                            OperationImpact operationImpactInstance = new OperationImpact();
                            propertiesInstance.getEstimatedImpact().add(operationImpactInstance);

                            JsonNode nameValue = estimatedImpactValue.get("name");
                            if (nameValue != null && nameValue instanceof NullNode == false) {
                                String nameInstance;
                                nameInstance = nameValue.getTextValue();
                                operationImpactInstance.setName(nameInstance);
                            }

                            JsonNode unitValue = estimatedImpactValue.get("unit");
                            if (unitValue != null && unitValue instanceof NullNode == false) {
                                String unitInstance;
                                unitInstance = unitValue.getTextValue();
                                operationImpactInstance.setUnit(unitInstance);
                            }

                            JsonNode changeValueAbsoluteValue = estimatedImpactValue.get("changeValueAbsolute");
                            if (changeValueAbsoluteValue != null
                                    && changeValueAbsoluteValue instanceof NullNode == false) {
                                double changeValueAbsoluteInstance;
                                changeValueAbsoluteInstance = changeValueAbsoluteValue.getDoubleValue();
                                operationImpactInstance.setChangeValueAbsolute(changeValueAbsoluteInstance);
                            }

                            JsonNode changeValueRelativeValue = estimatedImpactValue.get("changeValueRelative");
                            if (changeValueRelativeValue != null
                                    && changeValueRelativeValue instanceof NullNode == false) {
                                double changeValueRelativeInstance;
                                changeValueRelativeInstance = changeValueRelativeValue.getDoubleValue();
                                operationImpactInstance.setChangeValueRelative(changeValueRelativeInstance);
                            }
                        }
                    }

                    JsonNode reportedImpactArray = propertiesValue2.get("reportedImpact");
                    if (reportedImpactArray != null && reportedImpactArray instanceof NullNode == false) {
                        for (JsonNode reportedImpactValue : ((ArrayNode) reportedImpactArray)) {
                            OperationImpact operationImpactInstance2 = new OperationImpact();
                            propertiesInstance.getReportedImpact().add(operationImpactInstance2);

                            JsonNode nameValue2 = reportedImpactValue.get("name");
                            if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                                String nameInstance2;
                                nameInstance2 = nameValue2.getTextValue();
                                operationImpactInstance2.setName(nameInstance2);
                            }

                            JsonNode unitValue2 = reportedImpactValue.get("unit");
                            if (unitValue2 != null && unitValue2 instanceof NullNode == false) {
                                String unitInstance2;
                                unitInstance2 = unitValue2.getTextValue();
                                operationImpactInstance2.setUnit(unitInstance2);
                            }

                            JsonNode changeValueAbsoluteValue2 = reportedImpactValue.get("changeValueAbsolute");
                            if (changeValueAbsoluteValue2 != null
                                    && changeValueAbsoluteValue2 instanceof NullNode == false) {
                                double changeValueAbsoluteInstance2;
                                changeValueAbsoluteInstance2 = changeValueAbsoluteValue2.getDoubleValue();
                                operationImpactInstance2.setChangeValueAbsolute(changeValueAbsoluteInstance2);
                            }

                            JsonNode changeValueRelativeValue2 = reportedImpactValue.get("changeValueRelative");
                            if (changeValueRelativeValue2 != null
                                    && changeValueRelativeValue2 instanceof NullNode == false) {
                                double changeValueRelativeInstance2;
                                changeValueRelativeInstance2 = changeValueRelativeValue2.getDoubleValue();
                                operationImpactInstance2.setChangeValueRelative(changeValueRelativeInstance2);
                            }
                        }
                    }
                }

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    recommendedIndexInstance.setId(idInstance);
                }

                JsonNode nameValue3 = responseDoc.get("name");
                if (nameValue3 != null && nameValue3 instanceof NullNode == false) {
                    String nameInstance3;
                    nameInstance3 = nameValue3.getTextValue();
                    recommendedIndexInstance.setName(nameInstance3);
                }

                JsonNode typeValue = responseDoc.get("type");
                if (typeValue != null && typeValue instanceof NullNode == false) {
                    String typeInstance;
                    typeInstance = typeValue.getTextValue();
                    recommendedIndexInstance.setType(typeInstance);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    recommendedIndexInstance.setLocation(locationInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                    while (itr.hasNext()) {
                        Map.Entry<String, JsonNode> property = itr.next();
                        String tagsKey = property.getKey();
                        String tagsValue = property.getValue().getTextValue();
                        recommendedIndexInstance.getTags().put(tagsKey, tagsValue);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Location").length > 0) {
            result.setOperationStatusLink(httpResponse.getFirstHeader("Location").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }
        if (statusCode == HttpStatus.SC_OK) {
            result.setStatus(OperationStatus.Succeeded);
        }

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