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.windowsazure.management.sql.DatabaseOperationOperationsImpl.java

/**
* Retrieves all of the operations that took place on a specific database.
*
* @param serverName Required. The name of the Azure SQL Database Server
* that hosts the database.//w  ww  . j  av  a  2 s  .co  m
* @param databaseName Required. The name of the database for which the
* operations should 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 Represents the response containing the list of database
* operations for a given server or database.
*/
@Override
public DatabaseOperationListResponse listByDatabase(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, "listByDatabaseAsync", 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("databaseName=" + URLEncoder.encode(databaseName, "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", "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.azure.management.network.LocalNetworkGatewayOperationsImpl.java

/**
* The Put LocalNetworkGateway operation creates/updates a local network
* gateway in the specified resource group through Network resource
* provider./*from   w ww.  j  av  a 2s  .  c  om*/
*
* @param resourceGroupName Required. The name of the resource group.
* @param localNetworkGatewayName Required. The name of the local network
* gateway.
* @param parameters Required. Parameters supplied to the Begin Create or
* update Local Network Gateway operation through Network resource provider.
* @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 PutLocalNetworkGateway Api servive call
*/
@Override
public LocalNetworkGatewayPutResponse beginCreateOrUpdating(String resourceGroupName,
        String localNetworkGatewayName, LocalNetworkGateway parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (localNetworkGatewayName == null) {
        throw new NullPointerException("localNetworkGatewayName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }

    // 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("localNetworkGatewayName", localNetworkGatewayName);
        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 + "/localNetworkGateways/";
    url = url + URLEncoder.encode(localNetworkGatewayName, "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 localNetworkGatewayJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = localNetworkGatewayJsonFormatValue;

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

    if (parameters.getLocalNetworkAddressSpace() != null) {
        ObjectNode localNetworkAddressSpaceValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("localNetworkAddressSpace", localNetworkAddressSpaceValue);

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

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

    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) localNetworkGatewayJsonFormatValue).put("etag", parameters.getEtag());
    }

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

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

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

    ((ObjectNode) localNetworkGatewayJsonFormatValue).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) localNetworkGatewayJsonFormatValue).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
        LocalNetworkGatewayPutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new LocalNetworkGatewayPutResponse();
            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) {
                LocalNetworkGateway localNetworkGatewayInstance = new LocalNetworkGateway();
                result.setLocalNetworkGateway(localNetworkGatewayInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    JsonNode localNetworkAddressSpaceValue2 = propertiesValue2.get("localNetworkAddressSpace");
                    if (localNetworkAddressSpaceValue2 != null
                            && localNetworkAddressSpaceValue2 instanceof NullNode == false) {
                        AddressSpace localNetworkAddressSpaceInstance = new AddressSpace();
                        localNetworkGatewayInstance
                                .setLocalNetworkAddressSpace(localNetworkAddressSpaceInstance);

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

                    JsonNode gatewayIpAddressValue = propertiesValue2.get("gatewayIpAddress");
                    if (gatewayIpAddressValue != null && gatewayIpAddressValue instanceof NullNode == false) {
                        String gatewayIpAddressInstance;
                        gatewayIpAddressInstance = gatewayIpAddressValue.getTextValue();
                        localNetworkGatewayInstance.setGatewayIpAddress(gatewayIpAddressInstance);
                    }

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

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

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

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    localNetworkGatewayInstance.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();
                        localNetworkGatewayInstance.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.azure.management.network.SecurityRuleOperationsImpl.java

/**
* The Put network security rule operation creates/updates a security rule
* in the specified network security group
*
* @param resourceGroupName Required. The name of the resource group.
* @param networkSecurityGroupName Required. The name of the network
* security group.//from ww w  .ja va 2 s  .  co m
* @param securityRuleName Required. The name of the security rule.
* @param securityRuleParameters Required. Parameters supplied to the
* create/update network security rule 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 PUT SecurityRule Api service call
*/
@Override
public SecurityRulePutResponse beginCreateOrUpdating(String resourceGroupName, String networkSecurityGroupName,
        String securityRuleName, SecurityRule securityRuleParameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (networkSecurityGroupName == null) {
        throw new NullPointerException("networkSecurityGroupName");
    }
    if (securityRuleName == null) {
        throw new NullPointerException("securityRuleName");
    }
    if (securityRuleParameters == null) {
        throw new NullPointerException("securityRuleParameters");
    }
    if (securityRuleParameters.getAccess() == null) {
        throw new NullPointerException("securityRuleParameters.Access");
    }
    if (securityRuleParameters.getDestinationAddressPrefix() == null) {
        throw new NullPointerException("securityRuleParameters.DestinationAddressPrefix");
    }
    if (securityRuleParameters.getDirection() == null) {
        throw new NullPointerException("securityRuleParameters.Direction");
    }
    if (securityRuleParameters.getProtocol() == null) {
        throw new NullPointerException("securityRuleParameters.Protocol");
    }
    if (securityRuleParameters.getSourceAddressPrefix() == null) {
        throw new NullPointerException("securityRuleParameters.SourceAddressPrefix");
    }

    // 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("networkSecurityGroupName", networkSecurityGroupName);
        tracingParameters.put("securityRuleName", securityRuleName);
        tracingParameters.put("securityRuleParameters", securityRuleParameters);
        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 + "/networkSecurityGroups/";
    url = url + URLEncoder.encode(networkSecurityGroupName, "UTF-8");
    url = url + "/securityRules/";
    url = url + URLEncoder.encode(securityRuleName, "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 securityRuleJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = securityRuleJsonFormatValue;

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

    if (securityRuleParameters.getDescription() != null) {
        ((ObjectNode) propertiesValue).put("description", securityRuleParameters.getDescription());
    }

    ((ObjectNode) propertiesValue).put("protocol", securityRuleParameters.getProtocol());

    if (securityRuleParameters.getSourcePortRange() != null) {
        ((ObjectNode) propertiesValue).put("sourcePortRange", securityRuleParameters.getSourcePortRange());
    }

    if (securityRuleParameters.getDestinationPortRange() != null) {
        ((ObjectNode) propertiesValue).put("destinationPortRange",
                securityRuleParameters.getDestinationPortRange());
    }

    ((ObjectNode) propertiesValue).put("sourceAddressPrefix", securityRuleParameters.getSourceAddressPrefix());

    ((ObjectNode) propertiesValue).put("destinationAddressPrefix",
            securityRuleParameters.getDestinationAddressPrefix());

    ((ObjectNode) propertiesValue).put("access", securityRuleParameters.getAccess());

    ((ObjectNode) propertiesValue).put("priority", securityRuleParameters.getPriority());

    ((ObjectNode) propertiesValue).put("direction", securityRuleParameters.getDirection());

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

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

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

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

    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
        SecurityRulePutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new SecurityRulePutResponse();
            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) {
                SecurityRule securityRuleInstance = new SecurityRule();
                result.setSecurityRule(securityRuleInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    JsonNode descriptionValue = propertiesValue2.get("description");
                    if (descriptionValue != null && descriptionValue instanceof NullNode == false) {
                        String descriptionInstance;
                        descriptionInstance = descriptionValue.getTextValue();
                        securityRuleInstance.setDescription(descriptionInstance);
                    }

                    JsonNode protocolValue = propertiesValue2.get("protocol");
                    if (protocolValue != null && protocolValue instanceof NullNode == false) {
                        String protocolInstance;
                        protocolInstance = protocolValue.getTextValue();
                        securityRuleInstance.setProtocol(protocolInstance);
                    }

                    JsonNode sourcePortRangeValue = propertiesValue2.get("sourcePortRange");
                    if (sourcePortRangeValue != null && sourcePortRangeValue instanceof NullNode == false) {
                        String sourcePortRangeInstance;
                        sourcePortRangeInstance = sourcePortRangeValue.getTextValue();
                        securityRuleInstance.setSourcePortRange(sourcePortRangeInstance);
                    }

                    JsonNode destinationPortRangeValue = propertiesValue2.get("destinationPortRange");
                    if (destinationPortRangeValue != null
                            && destinationPortRangeValue instanceof NullNode == false) {
                        String destinationPortRangeInstance;
                        destinationPortRangeInstance = destinationPortRangeValue.getTextValue();
                        securityRuleInstance.setDestinationPortRange(destinationPortRangeInstance);
                    }

                    JsonNode sourceAddressPrefixValue = propertiesValue2.get("sourceAddressPrefix");
                    if (sourceAddressPrefixValue != null
                            && sourceAddressPrefixValue instanceof NullNode == false) {
                        String sourceAddressPrefixInstance;
                        sourceAddressPrefixInstance = sourceAddressPrefixValue.getTextValue();
                        securityRuleInstance.setSourceAddressPrefix(sourceAddressPrefixInstance);
                    }

                    JsonNode destinationAddressPrefixValue = propertiesValue2.get("destinationAddressPrefix");
                    if (destinationAddressPrefixValue != null
                            && destinationAddressPrefixValue instanceof NullNode == false) {
                        String destinationAddressPrefixInstance;
                        destinationAddressPrefixInstance = destinationAddressPrefixValue.getTextValue();
                        securityRuleInstance.setDestinationAddressPrefix(destinationAddressPrefixInstance);
                    }

                    JsonNode accessValue = propertiesValue2.get("access");
                    if (accessValue != null && accessValue instanceof NullNode == false) {
                        String accessInstance;
                        accessInstance = accessValue.getTextValue();
                        securityRuleInstance.setAccess(accessInstance);
                    }

                    JsonNode priorityValue = propertiesValue2.get("priority");
                    if (priorityValue != null && priorityValue instanceof NullNode == false) {
                        int priorityInstance;
                        priorityInstance = priorityValue.getIntValue();
                        securityRuleInstance.setPriority(priorityInstance);
                    }

                    JsonNode directionValue = propertiesValue2.get("direction");
                    if (directionValue != null && directionValue instanceof NullNode == false) {
                        String directionInstance;
                        directionInstance = directionValue.getTextValue();
                        securityRuleInstance.setDirection(directionInstance);
                    }

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

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

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

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

                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.azure.management.network.RouteOperationsImpl.java

/**
* The delete route operation deletes the specified route from a route table.
*
* @param resourceGroupName Required. The name of the resource group.
* @param routeTableName Required. The name of the route table.
* @param routeName Required. The name of the route.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations./*  w  w w .  ja v  a 2s .co 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 routeTableName, String routeName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (routeTableName == null) {
        throw new NullPointerException("routeTableName");
    }
    if (routeName == null) {
        throw new NullPointerException("routeName");
    }

    // 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("routeTableName", routeTableName);
        tracingParameters.put("routeName", routeName);
        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 + "/routeTables/";
    url = url + URLEncoder.encode(routeTableName, "UTF-8");
    url = url + "/routes/";
    url = url + URLEncoder.encode(routeName, "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.azure.management.sql.ElasticPoolOperationsImpl.java

/**
* Begins creating a new Azure SQL Database Elastic Pool or updating an
* existing Azure SQL Database Elastic Pool. To determine the status of the
* operation call GetElasticPoolOperationStatus.
*
* @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./*ww w  .java2s  .co  m*/
* @param elasticPoolName Required. The name of the Azure SQL Database
* Elastic Pool to be operated on (Updated or created).
* @param parameters Required. The required parameters for createing or
* updating an Elastic Pool.
* @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 long running Azure Sql Database Elastic Pool
* operation.
*/
@Override
public ElasticPoolCreateOrUpdateResponse beginCreateOrUpdate(String resourceGroupName, String serverName,
        String elasticPoolName, ElasticPoolCreateOrUpdateParameters parameters)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (elasticPoolName == null) {
        throw new NullPointerException("elasticPoolName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    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("elasticPoolName", elasticPoolName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreateOrUpdateAsync", 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 + "/elasticPools/";
    url = url + URLEncoder.encode(elasticPoolName, "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 elasticPoolCreateOrUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = elasticPoolCreateOrUpdateParametersValue;

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

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

    if (parameters.getProperties().getDtu() != null) {
        ((ObjectNode) propertiesValue).put("dtu", Integer.toString(parameters.getProperties().getDtu()));
    }

    if (parameters.getProperties().getStorageMB() != null) {
        ((ObjectNode) propertiesValue).put("storageMB",
                Integer.toString(parameters.getProperties().getStorageMB()));
    }

    if (parameters.getProperties().getDatabaseDtuMin() != null) {
        ((ObjectNode) propertiesValue).put("databaseDtuMin",
                Integer.toString(parameters.getProperties().getDatabaseDtuMin()));
    }

    if (parameters.getProperties().getDatabaseDtuMax() != null) {
        ((ObjectNode) propertiesValue).put("databaseDtuMax",
                Integer.toString(parameters.getProperties().getDatabaseDtuMax()));
    }

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

        // Create Result
        ElasticPoolCreateOrUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                || statusCode == HttpStatus.SC_ACCEPTED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ElasticPoolCreateOrUpdateResponse();
            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);
                }

                ElasticPool elasticPoolInstance = new ElasticPool();
                result.setElasticPool(elasticPoolInstance);

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

                    JsonNode creationDateValue = propertiesValue2.get("creationDate");
                    if (creationDateValue != null && creationDateValue instanceof NullNode == false) {
                        Calendar creationDateInstance;
                        creationDateInstance = DatatypeConverter
                                .parseDateTime(creationDateValue.getTextValue());
                        propertiesInstance.setCreationDate(creationDateInstance);
                    }

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

                    JsonNode editionValue = propertiesValue2.get("edition");
                    if (editionValue != null && editionValue instanceof NullNode == false) {
                        String editionInstance;
                        editionInstance = editionValue.getTextValue();
                        propertiesInstance.setEdition(editionInstance);
                    }

                    JsonNode dtuValue = propertiesValue2.get("dtu");
                    if (dtuValue != null && dtuValue instanceof NullNode == false) {
                        int dtuInstance;
                        dtuInstance = dtuValue.getIntValue();
                        propertiesInstance.setDtu(dtuInstance);
                    }

                    JsonNode databaseDtuMaxValue = propertiesValue2.get("databaseDtuMax");
                    if (databaseDtuMaxValue != null && databaseDtuMaxValue instanceof NullNode == false) {
                        int databaseDtuMaxInstance;
                        databaseDtuMaxInstance = databaseDtuMaxValue.getIntValue();
                        propertiesInstance.setDatabaseDtuMax(databaseDtuMaxInstance);
                    }

                    JsonNode databaseDtuMinValue = propertiesValue2.get("databaseDtuMin");
                    if (databaseDtuMinValue != null && databaseDtuMinValue instanceof NullNode == false) {
                        int databaseDtuMinInstance;
                        databaseDtuMinInstance = databaseDtuMinValue.getIntValue();
                        propertiesInstance.setDatabaseDtuMin(databaseDtuMinInstance);
                    }

                    JsonNode storageMBValue = propertiesValue2.get("storageMB");
                    if (storageMBValue != null && storageMBValue instanceof NullNode == false) {
                        int storageMBInstance;
                        storageMBInstance = storageMBValue.getIntValue();
                        propertiesInstance.setStorageMB(storageMBInstance);
                    }
                }

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    elasticPoolInstance.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();
                        elasticPoolInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }
            }

        }
        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_CREATED) {
            result.setStatus(OperationStatus.Succeeded);
        }

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

/**
* The Put PublicIPAddress operation creates/updates a stable/dynamic
* PublicIP address// ww  w .j ava  2 s. c o m
*
* @param resourceGroupName Required. The name of the resource group.
* @param publicIpAddressName Required. The name of the publicIpAddress.
* @param parameters Required. Parameters supplied to the create/update
* PublicIPAddress 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 PutPublicIpAddress Api servive call
*/
@Override
public PublicIpAddressPutResponse beginCreateOrUpdating(String resourceGroupName, String publicIpAddressName,
        PublicIpAddress parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (publicIpAddressName == null) {
        throw new NullPointerException("publicIpAddressName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    if (parameters.getPublicIpAllocationMethod() == null) {
        throw new NullPointerException("parameters.PublicIpAllocationMethod");
    }

    // 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("publicIpAddressName", publicIpAddressName);
        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 + "/publicIPAddresses/";
    url = url + URLEncoder.encode(publicIpAddressName, "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
    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 publicIpAddressJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = publicIpAddressJsonFormatValue;

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

    ((ObjectNode) propertiesValue).put("publicIPAllocationMethod", parameters.getPublicIpAllocationMethod());

    if (parameters.getIpConfiguration() != null) {
        ObjectNode ipConfigurationValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("ipConfiguration", ipConfigurationValue);

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

    if (parameters.getDnsSettings() != null) {
        ObjectNode dnsSettingsValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("dnsSettings", dnsSettingsValue);

        if (parameters.getDnsSettings().getDomainNameLabel() != null) {
            ((ObjectNode) dnsSettingsValue).put("domainNameLabel",
                    parameters.getDnsSettings().getDomainNameLabel());
        }

        if (parameters.getDnsSettings().getFqdn() != null) {
            ((ObjectNode) dnsSettingsValue).put("fqdn", parameters.getDnsSettings().getFqdn());
        }

        if (parameters.getDnsSettings().getReverseFqdn() != null) {
            ((ObjectNode) dnsSettingsValue).put("reverseFqdn", parameters.getDnsSettings().getReverseFqdn());
        }
    }

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

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

    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) publicIpAddressJsonFormatValue).put("etag", parameters.getEtag());
    }

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

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

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

    ((ObjectNode) publicIpAddressJsonFormatValue).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) publicIpAddressJsonFormatValue).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
        PublicIpAddressPutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new PublicIpAddressPutResponse();
            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) {
                PublicIpAddress publicIpAddressInstance = new PublicIpAddress();
                result.setPublicIpAddress(publicIpAddressInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    JsonNode publicIPAllocationMethodValue = propertiesValue2.get("publicIPAllocationMethod");
                    if (publicIPAllocationMethodValue != null
                            && publicIPAllocationMethodValue instanceof NullNode == false) {
                        String publicIPAllocationMethodInstance;
                        publicIPAllocationMethodInstance = publicIPAllocationMethodValue.getTextValue();
                        publicIpAddressInstance.setPublicIpAllocationMethod(publicIPAllocationMethodInstance);
                    }

                    JsonNode ipConfigurationValue2 = propertiesValue2.get("ipConfiguration");
                    if (ipConfigurationValue2 != null && ipConfigurationValue2 instanceof NullNode == false) {
                        ResourceId ipConfigurationInstance = new ResourceId();
                        publicIpAddressInstance.setIpConfiguration(ipConfigurationInstance);

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

                    JsonNode dnsSettingsValue2 = propertiesValue2.get("dnsSettings");
                    if (dnsSettingsValue2 != null && dnsSettingsValue2 instanceof NullNode == false) {
                        PublicIpAddressDnsSettings dnsSettingsInstance = new PublicIpAddressDnsSettings();
                        publicIpAddressInstance.setDnsSettings(dnsSettingsInstance);

                        JsonNode domainNameLabelValue = dnsSettingsValue2.get("domainNameLabel");
                        if (domainNameLabelValue != null && domainNameLabelValue instanceof NullNode == false) {
                            String domainNameLabelInstance;
                            domainNameLabelInstance = domainNameLabelValue.getTextValue();
                            dnsSettingsInstance.setDomainNameLabel(domainNameLabelInstance);
                        }

                        JsonNode fqdnValue = dnsSettingsValue2.get("fqdn");
                        if (fqdnValue != null && fqdnValue instanceof NullNode == false) {
                            String fqdnInstance;
                            fqdnInstance = fqdnValue.getTextValue();
                            dnsSettingsInstance.setFqdn(fqdnInstance);
                        }

                        JsonNode reverseFqdnValue = dnsSettingsValue2.get("reverseFqdn");
                        if (reverseFqdnValue != null && reverseFqdnValue instanceof NullNode == false) {
                            String reverseFqdnInstance;
                            reverseFqdnInstance = reverseFqdnValue.getTextValue();
                            dnsSettingsInstance.setReverseFqdn(reverseFqdnInstance);
                        }
                    }

                    JsonNode ipAddressValue = propertiesValue2.get("ipAddress");
                    if (ipAddressValue != null && ipAddressValue instanceof NullNode == false) {
                        String ipAddressInstance;
                        ipAddressInstance = ipAddressValue.getTextValue();
                        publicIpAddressInstance.setIpAddress(ipAddressInstance);
                    }

                    JsonNode idleTimeoutInMinutesValue = propertiesValue2.get("idleTimeoutInMinutes");
                    if (idleTimeoutInMinutesValue != null
                            && idleTimeoutInMinutesValue instanceof NullNode == false) {
                        int idleTimeoutInMinutesInstance;
                        idleTimeoutInMinutesInstance = idleTimeoutInMinutesValue.getIntValue();
                        publicIpAddressInstance.setIdleTimeoutInMinutes(idleTimeoutInMinutesInstance);
                    }

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

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

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

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    publicIpAddressInstance.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();
                        publicIpAddressInstance.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.azure.management.network.RouteTableOperationsImpl.java

/**
* The Put RouteTable operation creates/updates a route tablein the
* specified resource group.//from w  w w. j a v  a  2s . c  o m
*
* @param resourceGroupName Required. The name of the resource group.
* @param routeTableName Required. The name of the route table.
* @param parameters Required. Parameters supplied to the create/update
* Route Table 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 PUT RouteTables Api servive call
*/
@Override
public RouteTablePutResponse beginCreateOrUpdating(String resourceGroupName, String routeTableName,
        RouteTable parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (routeTableName == null) {
        throw new NullPointerException("routeTableName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    if (parameters.getRoutes() != null) {
        for (Route routesParameterItem : parameters.getRoutes()) {
            if (routesParameterItem.getNextHopType() == null) {
                throw new NullPointerException("parameters.Routes.NextHopType");
            }
        }
    }

    // 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("routeTableName", routeTableName);
        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 + "/routeTables/";
    url = url + URLEncoder.encode(routeTableName, "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 routeTableJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = routeTableJsonFormatValue;

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

    if (parameters.getRoutes() != null) {
        if (parameters.getRoutes() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getRoutes()).isInitialized()) {
            ArrayNode routesArray = objectMapper.createArrayNode();
            for (Route routesItem : parameters.getRoutes()) {
                ObjectNode routeJsonFormatValue = objectMapper.createObjectNode();
                routesArray.add(routeJsonFormatValue);

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

                if (routesItem.getAddressPrefix() != null) {
                    ((ObjectNode) propertiesValue2).put("addressPrefix", routesItem.getAddressPrefix());
                }

                ((ObjectNode) propertiesValue2).put("nextHopType", routesItem.getNextHopType());

                if (routesItem.getNextHopIpAddress() != null) {
                    ((ObjectNode) propertiesValue2).put("nextHopIpAddress", routesItem.getNextHopIpAddress());
                }

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

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

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

                if (routesItem.getId() != null) {
                    ((ObjectNode) routeJsonFormatValue).put("id", routesItem.getId());
                }
            }
            ((ObjectNode) propertiesValue).put("routes", routesArray);
        }
    }

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

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

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

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

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

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

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

    ((ObjectNode) routeTableJsonFormatValue).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) routeTableJsonFormatValue).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
        RouteTablePutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new RouteTablePutResponse();
            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) {
                RouteTable routeTableInstance = new RouteTable();
                result.setRouteTable(routeTableInstance);

                JsonNode propertiesValue3 = responseDoc.get("properties");
                if (propertiesValue3 != null && propertiesValue3 instanceof NullNode == false) {
                    JsonNode routesArray2 = propertiesValue3.get("routes");
                    if (routesArray2 != null && routesArray2 instanceof NullNode == false) {
                        for (JsonNode routesValue : ((ArrayNode) routesArray2)) {
                            Route routeJsonFormatInstance = new Route();
                            routeTableInstance.getRoutes().add(routeJsonFormatInstance);

                            JsonNode propertiesValue4 = routesValue.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();
                                    routeJsonFormatInstance.setAddressPrefix(addressPrefixInstance);
                                }

                                JsonNode nextHopTypeValue = propertiesValue4.get("nextHopType");
                                if (nextHopTypeValue != null && nextHopTypeValue instanceof NullNode == false) {
                                    String nextHopTypeInstance;
                                    nextHopTypeInstance = nextHopTypeValue.getTextValue();
                                    routeJsonFormatInstance.setNextHopType(nextHopTypeInstance);
                                }

                                JsonNode nextHopIpAddressValue = propertiesValue4.get("nextHopIpAddress");
                                if (nextHopIpAddressValue != null
                                        && nextHopIpAddressValue instanceof NullNode == false) {
                                    String nextHopIpAddressInstance;
                                    nextHopIpAddressInstance = nextHopIpAddressValue.getTextValue();
                                    routeJsonFormatInstance.setNextHopIpAddress(nextHopIpAddressInstance);
                                }

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

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

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

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

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

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

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

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

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    routeTableInstance.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();
                        routeTableInstance.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.azure.management.storage.StorageAccountOperationsImpl.java

/**
* Asynchronously creates a new storage account with the specified
* parameters. Existing accounts cannot be updated with this API and should
* instead use the Update Storage Account API. If an account is already
* created and subsequent PUT request is issued with exact same set of
* properties, then HTTP 200 would be returned.
*
* @param resourceGroupName Required. The name of the resource group within
* the user's subscription./*from   ww w .j a v  a2  s .  com*/
* @param accountName Required. The name of the storage account within the
* specified resource group. Storage account names must be between 3 and 24
* characters in length and use numbers and lower-case letters only.
* @param parameters Required. The parameters to provide for the created
* account.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create storage account operation response.
*/
@Override
public StorageAccountCreateResponse beginCreate(String resourceGroupName, String accountName,
        StorageAccountCreateParameters parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (accountName == null) {
        throw new NullPointerException("accountName");
    }
    if (accountName.length() < 3) {
        throw new IllegalArgumentException("accountName");
    }
    if (accountName.length() > 24) {
        throw new IllegalArgumentException("accountName");
    }
    for (char accountNameChar : accountName.toCharArray()) {
        if (Character.isLowerCase(accountNameChar) == false && Character.isDigit(accountNameChar) == false) {
            throw new IllegalArgumentException("accountName");
        }
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getAccountType() == null) {
        throw new NullPointerException("parameters.AccountType");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }

    // 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("accountName", accountName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreateAsync", 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/Microsoft.Storage/storageAccounts/";
    url = url + URLEncoder.encode(accountName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-06-15");
    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");
    httpRequest.setHeader("x-ms-client-request-id", UUID.randomUUID().toString());

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

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

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

    if (parameters.getTags() != null) {
        if (parameters.getTags() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getTags()).isInitialized()) {
            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) storageAccountCreateParametersJsonValue).put("tags", tagsDictionary);
        }
    }

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

    ((ObjectNode) propertiesValue).put("accountType",
            StorageManagementClientImpl.accountTypeToString(parameters.getAccountType()));

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

        // Create Result
        StorageAccountCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new StorageAccountCreateResponse();
            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) {
                StorageAccount storageAccountInstance = new StorageAccount();
                result.setStorageAccount(storageAccountInstance);

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    storageAccountInstance.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();
                        storageAccountInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    JsonNode provisioningStateValue = propertiesValue2.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        ProvisioningState provisioningStateInstance;
                        provisioningStateInstance = EnumUtility.fromString(ProvisioningState.class,
                                provisioningStateValue.getTextValue());
                        storageAccountInstance.setProvisioningState(provisioningStateInstance);
                    }

                    JsonNode accountTypeValue = propertiesValue2.get("accountType");
                    if (accountTypeValue != null && accountTypeValue instanceof NullNode == false) {
                        AccountType accountTypeInstance;
                        accountTypeInstance = StorageManagementClientImpl
                                .parseAccountType(accountTypeValue.getTextValue());
                        storageAccountInstance.setAccountType(accountTypeInstance);
                    }

                    JsonNode primaryEndpointsValue = propertiesValue2.get("primaryEndpoints");
                    if (primaryEndpointsValue != null && primaryEndpointsValue instanceof NullNode == false) {
                        Endpoints primaryEndpointsInstance = new Endpoints();
                        storageAccountInstance.setPrimaryEndpoints(primaryEndpointsInstance);

                        JsonNode blobValue = primaryEndpointsValue.get("blob");
                        if (blobValue != null && blobValue instanceof NullNode == false) {
                            URI blobInstance;
                            blobInstance = new URI(blobValue.getTextValue());
                            primaryEndpointsInstance.setBlob(blobInstance);
                        }

                        JsonNode queueValue = primaryEndpointsValue.get("queue");
                        if (queueValue != null && queueValue instanceof NullNode == false) {
                            URI queueInstance;
                            queueInstance = new URI(queueValue.getTextValue());
                            primaryEndpointsInstance.setQueue(queueInstance);
                        }

                        JsonNode tableValue = primaryEndpointsValue.get("table");
                        if (tableValue != null && tableValue instanceof NullNode == false) {
                            URI tableInstance;
                            tableInstance = new URI(tableValue.getTextValue());
                            primaryEndpointsInstance.setTable(tableInstance);
                        }

                        JsonNode fileValue = primaryEndpointsValue.get("file");
                        if (fileValue != null && fileValue instanceof NullNode == false) {
                            URI fileInstance;
                            fileInstance = new URI(fileValue.getTextValue());
                            primaryEndpointsInstance.setFile(fileInstance);
                        }
                    }

                    JsonNode primaryLocationValue = propertiesValue2.get("primaryLocation");
                    if (primaryLocationValue != null && primaryLocationValue instanceof NullNode == false) {
                        String primaryLocationInstance;
                        primaryLocationInstance = primaryLocationValue.getTextValue();
                        storageAccountInstance.setPrimaryLocation(primaryLocationInstance);
                    }

                    JsonNode statusOfPrimaryValue = propertiesValue2.get("statusOfPrimary");
                    if (statusOfPrimaryValue != null && statusOfPrimaryValue instanceof NullNode == false) {
                        AccountStatus statusOfPrimaryInstance;
                        statusOfPrimaryInstance = EnumUtility.fromString(AccountStatus.class,
                                statusOfPrimaryValue.getTextValue());
                        storageAccountInstance.setStatusOfPrimary(statusOfPrimaryInstance);
                    }

                    JsonNode lastGeoFailoverTimeValue = propertiesValue2.get("lastGeoFailoverTime");
                    if (lastGeoFailoverTimeValue != null
                            && lastGeoFailoverTimeValue instanceof NullNode == false) {
                        Calendar lastGeoFailoverTimeInstance;
                        lastGeoFailoverTimeInstance = DatatypeConverter
                                .parseDateTime(lastGeoFailoverTimeValue.getTextValue());
                        storageAccountInstance.setLastGeoFailoverTime(lastGeoFailoverTimeInstance);
                    }

                    JsonNode secondaryLocationValue = propertiesValue2.get("secondaryLocation");
                    if (secondaryLocationValue != null && secondaryLocationValue instanceof NullNode == false) {
                        String secondaryLocationInstance;
                        secondaryLocationInstance = secondaryLocationValue.getTextValue();
                        storageAccountInstance.setSecondaryLocation(secondaryLocationInstance);
                    }

                    JsonNode statusOfSecondaryValue = propertiesValue2.get("statusOfSecondary");
                    if (statusOfSecondaryValue != null && statusOfSecondaryValue instanceof NullNode == false) {
                        AccountStatus statusOfSecondaryInstance;
                        statusOfSecondaryInstance = EnumUtility.fromString(AccountStatus.class,
                                statusOfSecondaryValue.getTextValue());
                        storageAccountInstance.setStatusOfSecondary(statusOfSecondaryInstance);
                    }

                    JsonNode creationTimeValue = propertiesValue2.get("creationTime");
                    if (creationTimeValue != null && creationTimeValue instanceof NullNode == false) {
                        Calendar creationTimeInstance;
                        creationTimeInstance = DatatypeConverter
                                .parseDateTime(creationTimeValue.getTextValue());
                        storageAccountInstance.setCreationTime(creationTimeInstance);
                    }

                    JsonNode customDomainValue = propertiesValue2.get("customDomain");
                    if (customDomainValue != null && customDomainValue instanceof NullNode == false) {
                        CustomDomain customDomainInstance = new CustomDomain();
                        storageAccountInstance.setCustomDomain(customDomainInstance);

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

                        JsonNode useSubDomainValue = customDomainValue.get("useSubDomain");
                        if (useSubDomainValue != null && useSubDomainValue instanceof NullNode == false) {
                            boolean useSubDomainInstance;
                            useSubDomainInstance = useSubDomainValue.getBooleanValue();
                            customDomainInstance.setUseSubDomain(useSubDomainInstance);
                        }
                    }

                    JsonNode secondaryEndpointsValue = propertiesValue2.get("secondaryEndpoints");
                    if (secondaryEndpointsValue != null
                            && secondaryEndpointsValue instanceof NullNode == false) {
                        Endpoints secondaryEndpointsInstance = new Endpoints();
                        storageAccountInstance.setSecondaryEndpoints(secondaryEndpointsInstance);

                        JsonNode blobValue2 = secondaryEndpointsValue.get("blob");
                        if (blobValue2 != null && blobValue2 instanceof NullNode == false) {
                            URI blobInstance2;
                            blobInstance2 = new URI(blobValue2.getTextValue());
                            secondaryEndpointsInstance.setBlob(blobInstance2);
                        }

                        JsonNode queueValue2 = secondaryEndpointsValue.get("queue");
                        if (queueValue2 != null && queueValue2 instanceof NullNode == false) {
                            URI queueInstance2;
                            queueInstance2 = new URI(queueValue2.getTextValue());
                            secondaryEndpointsInstance.setQueue(queueInstance2);
                        }

                        JsonNode tableValue2 = secondaryEndpointsValue.get("table");
                        if (tableValue2 != null && tableValue2 instanceof NullNode == false) {
                            URI tableInstance2;
                            tableInstance2 = new URI(tableValue2.getTextValue());
                            secondaryEndpointsInstance.setTable(tableInstance2);
                        }

                        JsonNode fileValue2 = secondaryEndpointsValue.get("file");
                        if (fileValue2 != null && fileValue2 instanceof NullNode == false) {
                            URI fileInstance2;
                            fileInstance2 = new URI(fileValue2.getTextValue());
                            secondaryEndpointsInstance.setFile(fileInstance2);
                        }
                    }
                }
            }

        }
        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_CONFLICT || statusCode == HttpStatus.SC_BAD_REQUEST) {
            result.setStatus(OperationStatus.Failed);
        }
        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();
        }
    }
}

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

/**
* Begins deleting an existing Azure SQL Server Active Directory
* Administrator.To determine the status of the operation call
* GetServerAdministratorDeleteOperationStatus.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the server belongs./*from   ww  w .  ja v a 2s  .c  o  m*/
* @param serverName Required. The name of the Azure SQL Server to which the
* Azure SQL Server Active Directory administrator belongs
* @param administratorName Required. The name of the Azure SQL Server
* Active Directory Administrator.
* @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 long running Azure SQL Server Active Directory
* administrator delete operations.
*/
@Override
public ServerAdministratorDeleteResponse beginDelete(String resourceGroupName, String serverName,
        String administratorName) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (administratorName == null) {
        throw new NullPointerException("administratorName");
    }

    // 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("administratorName", administratorName);
        CloudTracing.enter(invocationId, this, "beginDeleteAsync", 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 + "/administrators/";
    url = url + URLEncoder.encode(administratorName, "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
    CustomHttpDelete httpRequest = new CustomHttpDelete(url);

    // Set Headers
    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 && statusCode != HttpStatus.SC_ACCEPTED
                && statusCode != HttpStatus.SC_NO_CONTENT) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ServerAdministratorDeleteResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED
                || statusCode == HttpStatus.SC_NO_CONTENT) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServerAdministratorDeleteResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            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);
                }
            }

        }
        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 (statusCode == HttpStatus.SC_NO_CONTENT) {
            result.setStatus(OperationStatus.Succeeded);
        }

        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

/**
* Gets details of an existing Web Hosting Plan  (see
* http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
* for more information)//  w  w  w . j a v  a2  s.  com
*
* @param webSpaceName Required. The name of the web space.
* @param webHostingPlanName Required. The name of the web hosting plan.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Web Hosting Plan operation response.
*/
@Override
public WebHostingPlanGetResponse get(String webSpaceName, String webHostingPlanName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webHostingPlanName == null) {
        throw new NullPointerException("webHostingPlanName");
    }

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

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

            Element serverFarmElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServerFarm");
            if (serverFarmElement != null) {
                WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
                result.setWebHostingPlan(webHostingPlanInstance);

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

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

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

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

                Element adminSiteNameElement = XmlUtility.getElementByTagNameNS(serverFarmElement,
                        "http://schemas.microsoft.com/windowsazure", "AdminSiteName");
                if (adminSiteNameElement != null) {
                    String adminSiteNameInstance;
                    adminSiteNameInstance = adminSiteNameElement.getTextContent();
                    webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance);
                }
            }

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