Example usage for javax.xml.bind DatatypeConverter parseInt

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

Introduction

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

Prototype

public static int parseInt(String lexicalXSDInt) 

Source Link

Document

Convert the string argument into an int value.

Usage

From source file:com.microsoft.azure.management.storage.StorageManagementClientImpl.java

/**
* The Get Create Operation Status operation returns the status of the
* specified create operation. After calling the asynchronous Begin Create
* operation, you can call Get Create Operation Status to determine whether
* the operation has succeeded, failed, or is still in progress.
*
* @param operationStatusLink Required. The URL where the status of the
* long-running create operation can be checked.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.//from www.  jav a2  s .c  o m
* @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 getCreateOperationStatus(String operationStatusLink)
        throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (operationStatusLink == null) {
        throw new NullPointerException("operationStatusLink");
    }

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

    // Construct URL
    String url = "";
    url = url + operationStatusLink;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("x-ms-client-request-id", UUID.randomUUID().toString());

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.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_INTERNAL_SERVER_ERROR) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, 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
                || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new StorageAccountCreateResponse();
            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) {
                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 tagsKey = property.getKey();
                        String tagsValue = property.getValue().getTextValue();
                        storageAccountInstance.getTags().put(tagsKey, tagsValue);
                    }
                }

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

                    JsonNode accountTypeValue = propertiesValue.get("accountType");
                    if (accountTypeValue != null && accountTypeValue instanceof NullNode == false) {
                        AccountType accountTypeInstance;
                        accountTypeInstance = com.microsoft.azure.management.storage.StorageManagementClientImpl
                                .parseAccountType(accountTypeValue.getTextValue());
                        storageAccountInstance.setAccountType(accountTypeInstance);
                    }

                    JsonNode primaryEndpointsValue = propertiesValue.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 = propertiesValue.get("primaryLocation");
                    if (primaryLocationValue != null && primaryLocationValue instanceof NullNode == false) {
                        String primaryLocationInstance;
                        primaryLocationInstance = primaryLocationValue.getTextValue();
                        storageAccountInstance.setPrimaryLocation(primaryLocationInstance);
                    }

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

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

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

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

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

                    JsonNode customDomainValue = propertiesValue.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 = propertiesValue.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) {
            result.setStatus(OperationStatus.Failed);
        }
        if (statusCode == HttpStatus.SC_ACCEPTED) {
            result.setStatus(OperationStatus.InProgress);
        }
        if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            result.setStatus(OperationStatus.InProgress);
        }
        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.network.SubnetOperationsImpl.java

/**
* The delete subnet operation deletes the specified subnet.
*
* @param resourceGroupName Required. The name of the resource group.
* @param virtualNetworkName Required. The name of the virtual network.
* @param subnetName Required. The name of the subnet.
* @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.  j  a va2s  .  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 virtualNetworkName,
        String subnetName) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (virtualNetworkName == null) {
        throw new NullPointerException("virtualNetworkName");
    }
    if (subnetName == null) {
        throw new NullPointerException("subnetName");
    }

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

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

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

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

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

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

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

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

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

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

    // Construct URL
    String url = "/"
            + (this.getClient().getCredentials().getSubscriptionId() != null
                    ? this.getClient().getCredentials().getSubscriptionId().trim()
                    : "")
            + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms/" + serverFarmName.trim();
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;

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

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

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

        // Create Result
        ServerFarmGetResponse result = null;
        // Deserialize Response
        InputStream responseContent = httpResponse.getEntity().getContent();
        result = new ServerFarmGetResponse();
        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) {
            Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmElement,
                    "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
            if (currentNumberOfWorkersElement != null) {
                int currentNumberOfWorkersInstance;
                currentNumberOfWorkersInstance = DatatypeConverter
                        .parseInt(currentNumberOfWorkersElement.getTextContent());
                result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
            }

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

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

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

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

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

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

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

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

/**
* The Delete LocalNetworkGateway operation deletes the specifed local
* network Gateway through Network resource provider.
*
* @param resourceGroupName Required. The name of the resource group.
* @param localNetworkGatewayName Required. The name of the local network
* gateway.//  w w  w .  java 2  s.com
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return If the resource provide needs to return an error to any
* operation, it should return the appropriate HTTP error code and a
* message body as can be seen below.The message should be localized per
* the Accept-Language header specified in the original request such thatit
* could be directly be exposed to users
*/
@Override
public UpdateOperationResponse beginDeleting(String resourceGroupName, String localNetworkGatewayName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (localNetworkGatewayName == null) {
        throw new NullPointerException("localNetworkGatewayName");
    }

    // 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);
        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 + "/localNetworkGateways/";
    url = url + URLEncoder.encode(localNetworkGatewayName, "UTF-8");
    url = url + "/";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-05-01-preview");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

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

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

/**
* The delete network security rule operation deletes the specified network
* security rule.//from w ww .  j  av  a 2  s.  c  o  m
*
* @param resourceGroupName Required. The name of the resource group.
* @param networkSecurityGroupName Required. The name of the network
* security group.
* @param securityRuleName Required. The name of the security rule.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return If the resource provide needs to return an error to any
* operation, it should return the appropriate HTTP error code and a
* message body as can be seen below.The message should be localized per
* the Accept-Language header specified in the original request such thatit
* could be directly be exposed to users
*/
@Override
public UpdateOperationResponse beginDeleting(String resourceGroupName, String networkSecurityGroupName,
        String securityRuleName) 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");
    }

    // 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);
        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 + "/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
    CustomHttpDelete httpRequest = new CustomHttpDelete(url);

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

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

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

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

From source file:com.microsoft.windowsazure.management.servicebus.QueueOperationsImpl.java

/**
* Creates a new queue. Once created, this queue's resource manifest is
* immutable. This operation is idempotent. Repeating the create call,
* after a queue with same name has been created successfully, will result
* in a 409 Conflict error message.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856295.aspx for
* more information)/*from   w  w w  .  j a v  a 2  s  . c  om*/
*
* @param namespaceName Required. The namespace name.
* @param queue Required. The service bus queue.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return A response to a request for a particular queue.
*/
@Override
public ServiceBusQueueResponse create(String namespaceName, ServiceBusQueueCreateParameters queue)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (queue == null) {
        throw new NullPointerException("queue");
    }
    if (queue.getName() == null) {
        throw new NullPointerException("queue.Name");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/queues/";
    url = url + URLEncoder.encode(queue.getName(), "UTF-8");
    url = url + "/";
    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/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-08-01");
    httpRequest.setHeader("x-process-at", "ServiceBus");

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

    Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
    requestDoc.appendChild(entryElement);

    Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
    entryElement.appendChild(contentElement);

    Attr typeAttribute = requestDoc.createAttribute("type");
    typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8");
    contentElement.setAttributeNode(typeAttribute);

    Element queueDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "QueueDescription");
    contentElement.appendChild(queueDescriptionElement);

    if (queue.getLockDuration() != null) {
        Element lockDurationElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "LockDuration");
        lockDurationElement.appendChild(requestDoc.createTextNode(queue.getLockDuration()));
        queueDescriptionElement.appendChild(lockDurationElement);
    }

    Element maxSizeInMegabytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes");
    maxSizeInMegabytesElement
            .appendChild(requestDoc.createTextNode(Integer.toString(queue.getMaxSizeInMegabytes())));
    queueDescriptionElement.appendChild(maxSizeInMegabytesElement);

    Element requiresDuplicateDetectionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "RequiresDuplicateDetection");
    requiresDuplicateDetectionElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(queue.isRequiresDuplicateDetection()).toLowerCase()));
    queueDescriptionElement.appendChild(requiresDuplicateDetectionElement);

    Element requiresSessionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RequiresSession");
    requiresSessionElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(queue.isRequiresSession()).toLowerCase()));
    queueDescriptionElement.appendChild(requiresSessionElement);

    if (queue.getDefaultMessageTimeToLive() != null) {
        Element defaultMessageTimeToLiveElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DefaultMessageTimeToLive");
        defaultMessageTimeToLiveElement
                .appendChild(requestDoc.createTextNode(queue.getDefaultMessageTimeToLive()));
        queueDescriptionElement.appendChild(defaultMessageTimeToLiveElement);
    }

    Element deadLetteringOnMessageExpirationElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "DeadLetteringOnMessageExpiration");
    deadLetteringOnMessageExpirationElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(queue.isDeadLetteringOnMessageExpiration()).toLowerCase()));
    queueDescriptionElement.appendChild(deadLetteringOnMessageExpirationElement);

    if (queue.getDuplicateDetectionHistoryTimeWindow() != null) {
        Element duplicateDetectionHistoryTimeWindowElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DuplicateDetectionHistoryTimeWindow");
        duplicateDetectionHistoryTimeWindowElement
                .appendChild(requestDoc.createTextNode(queue.getDuplicateDetectionHistoryTimeWindow()));
        queueDescriptionElement.appendChild(duplicateDetectionHistoryTimeWindowElement);
    }

    Element enableBatchedOperationsElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations");
    enableBatchedOperationsElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(queue.isEnableBatchedOperations()).toLowerCase()));
    queueDescriptionElement.appendChild(enableBatchedOperationsElement);

    Element sizeInBytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes");
    sizeInBytesElement.appendChild(requestDoc.createTextNode(Integer.toString(queue.getSizeInBytes())));
    queueDescriptionElement.appendChild(sizeInBytesElement);

    Element messageCountElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MessageCount");
    messageCountElement.appendChild(requestDoc.createTextNode(Integer.toString(queue.getMessageCount())));
    queueDescriptionElement.appendChild(messageCountElement);

    Element isAnonymousAccessibleElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible");
    isAnonymousAccessibleElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(queue.isAnonymousAccessible()).toLowerCase()));
    queueDescriptionElement.appendChild(isAnonymousAccessibleElement);

    if (queue.getAuthorizationRules() != null) {
        if (queue.getAuthorizationRules() instanceof LazyCollection == false
                || ((LazyCollection) queue.getAuthorizationRules()).isInitialized()) {
            Element authorizationRulesSequenceElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                    "AuthorizationRules");
            for (ServiceBusSharedAccessAuthorizationRule authorizationRulesItem : queue
                    .getAuthorizationRules()) {
                Element authorizationRuleElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                        "AuthorizationRule");
                authorizationRulesSequenceElement.appendChild(authorizationRuleElement);

                Attr typeAttribute2 = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                        "type");
                typeAttribute2.setValue("SharedAccessAuthorizationRule");
                authorizationRuleElement.setAttributeNode(typeAttribute2);

                if (authorizationRulesItem.getClaimType() != null) {
                    Element claimTypeElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType");
                    claimTypeElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimType()));
                    authorizationRuleElement.appendChild(claimTypeElement);
                }

                if (authorizationRulesItem.getClaimValue() != null) {
                    Element claimValueElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "ClaimValue");
                    claimValueElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimValue()));
                    authorizationRuleElement.appendChild(claimValueElement);
                }

                if (authorizationRulesItem.getRights() != null) {
                    if (authorizationRulesItem.getRights() instanceof LazyCollection == false
                            || ((LazyCollection) authorizationRulesItem.getRights()).isInitialized()) {
                        Element rightsSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        for (AccessRight rightsItem : authorizationRulesItem.getRights()) {
                            Element rightsItemElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                    "AccessRights");
                            rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                            rightsSequenceElement.appendChild(rightsItemElement);
                        }
                        authorizationRuleElement.appendChild(rightsSequenceElement);
                    }
                }

                Element createdTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                createdTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime())));
                authorizationRuleElement.appendChild(createdTimeElement);

                if (authorizationRulesItem.getKeyName() != null) {
                    Element keyNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName");
                    keyNameElement.appendChild(requestDoc.createTextNode(authorizationRulesItem.getKeyName()));
                    authorizationRuleElement.appendChild(keyNameElement);
                }

                Element modifiedTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
                modifiedTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime())));
                authorizationRuleElement.appendChild(modifiedTimeElement);

                if (authorizationRulesItem.getPrimaryKey() != null) {
                    Element primaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "PrimaryKey");
                    primaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getPrimaryKey()));
                    authorizationRuleElement.appendChild(primaryKeyElement);
                }

                if (authorizationRulesItem.getSecondaryKey() != null) {
                    Element secondaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SecondaryKey");
                    secondaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getSecondaryKey()));
                    authorizationRuleElement.appendChild(secondaryKeyElement);
                }
            }
            queueDescriptionElement.appendChild(authorizationRulesSequenceElement);
        }
    }

    if (queue.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status");
        statusElement.appendChild(requestDoc.createTextNode(queue.getStatus()));
        queueDescriptionElement.appendChild(statusElement);
    }

    Element supportOrderingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering");
    supportOrderingElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(queue.isSupportOrdering()).toLowerCase()));
    queueDescriptionElement.appendChild(supportOrderingElement);

    if (queue.getCountDetails() != null) {
        Element countDetailsElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails");
        queueDescriptionElement.appendChild(countDetailsElement);

        Element activeMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount");
        activeMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(queue.getCountDetails().getActiveMessageCount())));
        countDetailsElement.appendChild(activeMessageCountElement);

        Element deadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount");
        deadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(queue.getCountDetails().getDeadLetterMessageCount())));
        countDetailsElement.appendChild(deadLetterMessageCountElement);

        Element scheduledMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount");
        scheduledMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(queue.getCountDetails().getScheduledMessageCount())));
        countDetailsElement.appendChild(scheduledMessageCountElement);

        Element transferDeadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                "TransferDeadLetterMessageCount");
        transferDeadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(queue.getCountDetails().getTransferDeadLetterMessageCount())));
        countDetailsElement.appendChild(transferDeadLetterMessageCountElement);

        Element transferMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount");
        transferMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(queue.getCountDetails().getTransferMessageCount())));
        countDetailsElement.appendChild(transferMessageCountElement);
    }

    if (queue.getAutoDeleteOnIdle() != null) {
        Element autoDeleteOnIdleElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle");
        autoDeleteOnIdleElement.appendChild(requestDoc.createTextNode(queue.getAutoDeleteOnIdle()));
        queueDescriptionElement.appendChild(autoDeleteOnIdleElement);
    }

    if (queue.getEntityAvailabilityStatus() != null) {
        Element entityAvailabilityStatusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "EntityAvailabilityStatus");
        entityAvailabilityStatusElement
                .appendChild(requestDoc.createTextNode(queue.getEntityAvailabilityStatus()));
        queueDescriptionElement.appendChild(entityAvailabilityStatusElement);
    }

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

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

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

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element titleElement = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "title");
                if (titleElement != null) {
                }

                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element queueDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "QueueDescription");
                    if (queueDescriptionElement2 != null) {
                        ServiceBusQueue queueDescriptionInstance = new ServiceBusQueue();
                        result.setQueue(queueDescriptionInstance);

                        Element lockDurationElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "LockDuration");
                        if (lockDurationElement2 != null) {
                            String lockDurationInstance;
                            lockDurationInstance = lockDurationElement2.getTextContent();
                            queueDescriptionInstance.setLockDuration(lockDurationInstance);
                        }

                        Element maxSizeInMegabytesElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxSizeInMegabytes");
                        if (maxSizeInMegabytesElement2 != null) {
                            int maxSizeInMegabytesInstance;
                            maxSizeInMegabytesInstance = DatatypeConverter
                                    .parseInt(maxSizeInMegabytesElement2.getTextContent());
                            queueDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance);
                        }

                        Element requiresDuplicateDetectionElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresDuplicateDetection");
                        if (requiresDuplicateDetectionElement2 != null) {
                            boolean requiresDuplicateDetectionInstance;
                            requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean(
                                    requiresDuplicateDetectionElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance
                                    .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance);
                        }

                        Element requiresSessionElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresSession");
                        if (requiresSessionElement2 != null) {
                            boolean requiresSessionInstance;
                            requiresSessionInstance = DatatypeConverter
                                    .parseBoolean(requiresSessionElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setRequiresSession(requiresSessionInstance);
                        }

                        Element defaultMessageTimeToLiveElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DefaultMessageTimeToLive");
                        if (defaultMessageTimeToLiveElement2 != null) {
                            String defaultMessageTimeToLiveInstance;
                            defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement2
                                    .getTextContent();
                            queueDescriptionInstance
                                    .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance);
                        }

                        Element deadLetteringOnMessageExpirationElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DeadLetteringOnMessageExpiration");
                        if (deadLetteringOnMessageExpirationElement2 != null) {
                            boolean deadLetteringOnMessageExpirationInstance;
                            deadLetteringOnMessageExpirationInstance = DatatypeConverter.parseBoolean(
                                    deadLetteringOnMessageExpirationElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setDeadLetteringOnMessageExpiration(
                                    deadLetteringOnMessageExpirationInstance);
                        }

                        Element duplicateDetectionHistoryTimeWindowElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DuplicateDetectionHistoryTimeWindow");
                        if (duplicateDetectionHistoryTimeWindowElement2 != null) {
                            String duplicateDetectionHistoryTimeWindowInstance;
                            duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement2
                                    .getTextContent();
                            queueDescriptionInstance.setDuplicateDetectionHistoryTimeWindow(
                                    duplicateDetectionHistoryTimeWindowInstance);
                        }

                        Element maxDeliveryCountElement = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxDeliveryCount");
                        if (maxDeliveryCountElement != null) {
                            int maxDeliveryCountInstance;
                            maxDeliveryCountInstance = DatatypeConverter
                                    .parseInt(maxDeliveryCountElement.getTextContent());
                            queueDescriptionInstance.setMaxDeliveryCount(maxDeliveryCountInstance);
                        }

                        Element enableBatchedOperationsElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EnableBatchedOperations");
                        if (enableBatchedOperationsElement2 != null) {
                            boolean enableBatchedOperationsInstance;
                            enableBatchedOperationsInstance = DatatypeConverter.parseBoolean(
                                    enableBatchedOperationsElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance
                                    .setEnableBatchedOperations(enableBatchedOperationsInstance);
                        }

                        Element sizeInBytesElement2 = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SizeInBytes");
                        if (sizeInBytesElement2 != null) {
                            int sizeInBytesInstance;
                            sizeInBytesInstance = DatatypeConverter
                                    .parseInt(sizeInBytesElement2.getTextContent());
                            queueDescriptionInstance.setSizeInBytes(sizeInBytesInstance);
                        }

                        Element messageCountElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MessageCount");
                        if (messageCountElement2 != null) {
                            int messageCountInstance;
                            messageCountInstance = DatatypeConverter
                                    .parseInt(messageCountElement2.getTextContent());
                            queueDescriptionInstance.setMessageCount(messageCountInstance);
                        }

                        Element isAnonymousAccessibleElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "IsAnonymousAccessible");
                        if (isAnonymousAccessibleElement2 != null) {
                            boolean isAnonymousAccessibleInstance;
                            isAnonymousAccessibleInstance = DatatypeConverter
                                    .parseBoolean(isAnonymousAccessibleElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance);
                        }

                        Element authorizationRulesSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AuthorizationRules");
                        if (authorizationRulesSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AuthorizationRule")
                                    .size(); i1 = i1 + 1) {
                                org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                "AuthorizationRule")
                                        .get(i1));
                                ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                                queueDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance);

                                Element claimTypeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimType");
                                if (claimTypeElement2 != null) {
                                    String claimTypeInstance;
                                    claimTypeInstance = claimTypeElement2.getTextContent();
                                    authorizationRuleInstance.setClaimType(claimTypeInstance);
                                }

                                Element claimValueElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimValue");
                                if (claimValueElement2 != null) {
                                    String claimValueInstance;
                                    claimValueInstance = claimValueElement2.getTextContent();
                                    authorizationRuleInstance.setClaimValue(claimValueInstance);
                                }

                                Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "Rights");
                                if (rightsSequenceElement2 != null) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(rightsSequenceElement2,
                                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                    "AccessRights")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(rightsSequenceElement2,
                                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                        "AccessRights")
                                                .get(i2));
                                        authorizationRuleInstance.getRights()
                                                .add(AccessRight.valueOf(rightsElement.getTextContent()));
                                    }
                                }

                                Element createdTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "CreatedTime");
                                if (createdTimeElement2 != null) {
                                    Calendar createdTimeInstance;
                                    createdTimeInstance = DatatypeConverter
                                            .parseDateTime(createdTimeElement2.getTextContent());
                                    authorizationRuleInstance.setCreatedTime(createdTimeInstance);
                                }

                                Element keyNameElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "KeyName");
                                if (keyNameElement2 != null) {
                                    String keyNameInstance;
                                    keyNameInstance = keyNameElement2.getTextContent();
                                    authorizationRuleInstance.setKeyName(keyNameInstance);
                                }

                                Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ModifiedTime");
                                if (modifiedTimeElement2 != null) {
                                    Calendar modifiedTimeInstance;
                                    modifiedTimeInstance = DatatypeConverter
                                            .parseDateTime(modifiedTimeElement2.getTextContent());
                                    authorizationRuleInstance.setModifiedTime(modifiedTimeInstance);
                                }

                                Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "PrimaryKey");
                                if (primaryKeyElement2 != null) {
                                    String primaryKeyInstance;
                                    primaryKeyInstance = primaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setPrimaryKey(primaryKeyInstance);
                                }

                                Element secondaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "SecondaryKey");
                                if (secondaryKeyElement2 != null) {
                                    String secondaryKeyInstance;
                                    secondaryKeyInstance = secondaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance);
                                }
                            }
                        }

                        Element statusElement2 = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Status");
                        if (statusElement2 != null) {
                            String statusInstance;
                            statusInstance = statusElement2.getTextContent();
                            queueDescriptionInstance.setStatus(statusInstance);
                        }

                        Element createdAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedAt");
                        if (createdAtElement != null) {
                            Calendar createdAtInstance;
                            createdAtInstance = DatatypeConverter
                                    .parseDateTime(createdAtElement.getTextContent());
                            queueDescriptionInstance.setCreatedAt(createdAtInstance);
                        }

                        Element updatedAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "UpdatedAt");
                        if (updatedAtElement != null) {
                            Calendar updatedAtInstance;
                            updatedAtInstance = DatatypeConverter
                                    .parseDateTime(updatedAtElement.getTextContent());
                            queueDescriptionInstance.setUpdatedAt(updatedAtInstance);
                        }

                        Element accessedAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AccessedAt");
                        if (accessedAtElement != null) {
                            Calendar accessedAtInstance;
                            accessedAtInstance = DatatypeConverter
                                    .parseDateTime(accessedAtElement.getTextContent());
                            queueDescriptionInstance.setAccessedAt(accessedAtInstance);
                        }

                        Element supportOrderingElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SupportOrdering");
                        if (supportOrderingElement2 != null) {
                            boolean supportOrderingInstance;
                            supportOrderingInstance = DatatypeConverter
                                    .parseBoolean(supportOrderingElement2.getTextContent().toLowerCase());
                            queueDescriptionInstance.setSupportOrdering(supportOrderingInstance);
                        }

                        Element countDetailsElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CountDetails");
                        if (countDetailsElement2 != null) {
                            CountDetails countDetailsInstance = new CountDetails();
                            queueDescriptionInstance.setCountDetails(countDetailsInstance);

                            Element activeMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "ActiveMessageCount");
                            if (activeMessageCountElement2 != null) {
                                int activeMessageCountInstance;
                                activeMessageCountInstance = DatatypeConverter
                                        .parseInt(activeMessageCountElement2.getTextContent());
                                countDetailsInstance.setActiveMessageCount(activeMessageCountInstance);
                            }

                            Element deadLetterMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "DeadLetterMessageCount");
                            if (deadLetterMessageCountElement2 != null) {
                                int deadLetterMessageCountInstance;
                                deadLetterMessageCountInstance = DatatypeConverter
                                        .parseInt(deadLetterMessageCountElement2.getTextContent());
                                countDetailsInstance.setDeadLetterMessageCount(deadLetterMessageCountInstance);
                            }

                            Element scheduledMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "ScheduledMessageCount");
                            if (scheduledMessageCountElement2 != null) {
                                int scheduledMessageCountInstance;
                                scheduledMessageCountInstance = DatatypeConverter
                                        .parseInt(scheduledMessageCountElement2.getTextContent());
                                countDetailsInstance.setScheduledMessageCount(scheduledMessageCountInstance);
                            }

                            Element transferDeadLetterMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "TransferDeadLetterMessageCount");
                            if (transferDeadLetterMessageCountElement2 != null) {
                                int transferDeadLetterMessageCountInstance;
                                transferDeadLetterMessageCountInstance = DatatypeConverter
                                        .parseInt(transferDeadLetterMessageCountElement2.getTextContent());
                                countDetailsInstance.setTransferDeadLetterMessageCount(
                                        transferDeadLetterMessageCountInstance);
                            }

                            Element transferMessageCountElement2 = XmlUtility.getElementByTagNameNS(
                                    countDetailsElement2,
                                    "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                                    "TransferMessageCount");
                            if (transferMessageCountElement2 != null) {
                                int transferMessageCountInstance;
                                transferMessageCountInstance = DatatypeConverter
                                        .parseInt(transferMessageCountElement2.getTextContent());
                                countDetailsInstance.setTransferMessageCount(transferMessageCountInstance);
                            }
                        }

                        Element autoDeleteOnIdleElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AutoDeleteOnIdle");
                        if (autoDeleteOnIdleElement2 != null) {
                            String autoDeleteOnIdleInstance;
                            autoDeleteOnIdleInstance = autoDeleteOnIdleElement2.getTextContent();
                            queueDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance);
                        }

                        Element entityAvailabilityStatusElement2 = XmlUtility.getElementByTagNameNS(
                                queueDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EntityAvailabilityStatus");
                        if (entityAvailabilityStatusElement2 != null) {
                            String entityAvailabilityStatusInstance;
                            entityAvailabilityStatusInstance = entityAvailabilityStatusElement2
                                    .getTextContent();
                            queueDescriptionInstance
                                    .setEntityAvailabilityStatus(entityAvailabilityStatusInstance);
                        }
                    }
                }
            }

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

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

From source file:com.microsoft.windowsazure.management.servicebus.TopicOperationsImpl.java

/**
* Creates a new topic. Once created, this topic resource manifest is
* immutable. This operation is not idempotent. Repeating the create call,
* after a topic with same name has been created successfully, will result
* in a 409 Conflict error message.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/hh780728.aspx for
* more information)/*from   ww w  .j  a v  a2 s .co  m*/
*
* @param namespaceName Required. The namespace name.
* @param topic Required. The Service Bus topic.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return A response to a request for a particular topic.
*/
@Override
public ServiceBusTopicResponse create(String namespaceName, ServiceBusTopic topic)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (topic == null) {
        throw new NullPointerException("topic");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/topics/";
    if (topic.getName() != null) {
        url = url + URLEncoder.encode(topic.getName(), "UTF-8");
    }
    url = url + "/";
    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/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-08-01");
    httpRequest.setHeader("x-process-at", "ServiceBus");

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

    Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
    requestDoc.appendChild(entryElement);

    Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
    entryElement.appendChild(contentElement);

    Attr typeAttribute = requestDoc.createAttribute("type");
    typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8");
    contentElement.setAttributeNode(typeAttribute);

    Element topicDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "TopicDescription");
    contentElement.appendChild(topicDescriptionElement);

    if (topic.getDefaultMessageTimeToLive() != null) {
        Element defaultMessageTimeToLiveElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DefaultMessageTimeToLive");
        defaultMessageTimeToLiveElement
                .appendChild(requestDoc.createTextNode(topic.getDefaultMessageTimeToLive()));
        topicDescriptionElement.appendChild(defaultMessageTimeToLiveElement);
    }

    Element maxSizeInMegabytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes");
    maxSizeInMegabytesElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getMaxSizeInMegabytes())));
    topicDescriptionElement.appendChild(maxSizeInMegabytesElement);

    Element requiresDuplicateDetectionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "RequiresDuplicateDetection");
    requiresDuplicateDetectionElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isRequiresDuplicateDetection()).toLowerCase()));
    topicDescriptionElement.appendChild(requiresDuplicateDetectionElement);

    if (topic.getDuplicateDetectionHistoryTimeWindow() != null) {
        Element duplicateDetectionHistoryTimeWindowElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DuplicateDetectionHistoryTimeWindow");
        duplicateDetectionHistoryTimeWindowElement
                .appendChild(requestDoc.createTextNode(topic.getDuplicateDetectionHistoryTimeWindow()));
        topicDescriptionElement.appendChild(duplicateDetectionHistoryTimeWindowElement);
    }

    Element enableBatchedOperationsElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations");
    enableBatchedOperationsElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isEnableBatchedOperations()).toLowerCase()));
    topicDescriptionElement.appendChild(enableBatchedOperationsElement);

    Element sizeInBytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes");
    sizeInBytesElement.appendChild(requestDoc.createTextNode(Integer.toString(topic.getSizeInBytes())));
    topicDescriptionElement.appendChild(sizeInBytesElement);

    Element filteringMessagesBeforePublishingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "FilteringMessagesBeforePublishing");
    filteringMessagesBeforePublishingElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(topic.isFilteringMessagesBeforePublishing()).toLowerCase()));
    topicDescriptionElement.appendChild(filteringMessagesBeforePublishingElement);

    Element isAnonymousAccessibleElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible");
    isAnonymousAccessibleElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isAnonymousAccessible()).toLowerCase()));
    topicDescriptionElement.appendChild(isAnonymousAccessibleElement);

    if (topic.getAuthorizationRules() != null) {
        if (topic.getAuthorizationRules() instanceof LazyCollection == false
                || ((LazyCollection) topic.getAuthorizationRules()).isInitialized()) {
            Element authorizationRulesSequenceElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                    "AuthorizationRules");
            for (ServiceBusSharedAccessAuthorizationRule authorizationRulesItem : topic
                    .getAuthorizationRules()) {
                Element authorizationRuleElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                        "AuthorizationRule");
                authorizationRulesSequenceElement.appendChild(authorizationRuleElement);

                Attr typeAttribute2 = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                        "type");
                typeAttribute2.setValue("SharedAccessAuthorizationRule");
                authorizationRuleElement.setAttributeNode(typeAttribute2);

                if (authorizationRulesItem.getClaimType() != null) {
                    Element claimTypeElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType");
                    claimTypeElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimType()));
                    authorizationRuleElement.appendChild(claimTypeElement);
                }

                if (authorizationRulesItem.getClaimValue() != null) {
                    Element claimValueElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "ClaimValue");
                    claimValueElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimValue()));
                    authorizationRuleElement.appendChild(claimValueElement);
                }

                if (authorizationRulesItem.getRights() != null) {
                    if (authorizationRulesItem.getRights() instanceof LazyCollection == false
                            || ((LazyCollection) authorizationRulesItem.getRights()).isInitialized()) {
                        Element rightsSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        for (AccessRight rightsItem : authorizationRulesItem.getRights()) {
                            Element rightsItemElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                    "AccessRights");
                            rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                            rightsSequenceElement.appendChild(rightsItemElement);
                        }
                        authorizationRuleElement.appendChild(rightsSequenceElement);
                    }
                }

                Element createdTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                createdTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime())));
                authorizationRuleElement.appendChild(createdTimeElement);

                if (authorizationRulesItem.getKeyName() != null) {
                    Element keyNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName");
                    keyNameElement.appendChild(requestDoc.createTextNode(authorizationRulesItem.getKeyName()));
                    authorizationRuleElement.appendChild(keyNameElement);
                }

                Element modifiedTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
                modifiedTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime())));
                authorizationRuleElement.appendChild(modifiedTimeElement);

                if (authorizationRulesItem.getPrimaryKey() != null) {
                    Element primaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "PrimaryKey");
                    primaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getPrimaryKey()));
                    authorizationRuleElement.appendChild(primaryKeyElement);
                }

                if (authorizationRulesItem.getSecondaryKey() != null) {
                    Element secondaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SecondaryKey");
                    secondaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getSecondaryKey()));
                    authorizationRuleElement.appendChild(secondaryKeyElement);
                }
            }
            topicDescriptionElement.appendChild(authorizationRulesSequenceElement);
        }
    }

    if (topic.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status");
        statusElement.appendChild(requestDoc.createTextNode(topic.getStatus()));
        topicDescriptionElement.appendChild(statusElement);
    }

    Element createdAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedAt");
    SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat3.setTimeZone(TimeZone.getTimeZone("UTC"));
    createdAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat3.format(topic.getCreatedAt().getTime())));
    topicDescriptionElement.appendChild(createdAtElement);

    Element updatedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "UpdatedAt");
    SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat4.setTimeZone(TimeZone.getTimeZone("UTC"));
    updatedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat4.format(topic.getUpdatedAt().getTime())));
    topicDescriptionElement.appendChild(updatedAtElement);

    Element accessedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessedAt");
    SimpleDateFormat simpleDateFormat5 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat5.setTimeZone(TimeZone.getTimeZone("UTC"));
    accessedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat5.format(topic.getAccessedAt().getTime())));
    topicDescriptionElement.appendChild(accessedAtElement);

    Element supportOrderingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering");
    supportOrderingElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(topic.isSupportOrdering()).toLowerCase()));
    topicDescriptionElement.appendChild(supportOrderingElement);

    if (topic.getCountDetails() != null) {
        Element countDetailsElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails");
        topicDescriptionElement.appendChild(countDetailsElement);

        Element activeMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount");
        activeMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getActiveMessageCount())));
        countDetailsElement.appendChild(activeMessageCountElement);

        Element deadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount");
        deadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getDeadLetterMessageCount())));
        countDetailsElement.appendChild(deadLetterMessageCountElement);

        Element scheduledMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount");
        scheduledMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getScheduledMessageCount())));
        countDetailsElement.appendChild(scheduledMessageCountElement);

        Element transferDeadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                "TransferDeadLetterMessageCount");
        transferDeadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getTransferDeadLetterMessageCount())));
        countDetailsElement.appendChild(transferDeadLetterMessageCountElement);

        Element transferMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount");
        transferMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getTransferMessageCount())));
        countDetailsElement.appendChild(transferMessageCountElement);
    }

    Element subscriptionCountElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SubscriptionCount");
    subscriptionCountElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getSubscriptionCount())));
    topicDescriptionElement.appendChild(subscriptionCountElement);

    if (topic.getAutoDeleteOnIdle() != null) {
        Element autoDeleteOnIdleElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle");
        autoDeleteOnIdleElement.appendChild(requestDoc.createTextNode(topic.getAutoDeleteOnIdle()));
        topicDescriptionElement.appendChild(autoDeleteOnIdleElement);
    }

    if (topic.getEntityAvailabilityStatus() != null) {
        Element entityAvailabilityStatusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "EntityAvailabilityStatus");
        entityAvailabilityStatusElement
                .appendChild(requestDoc.createTextNode(topic.getEntityAvailabilityStatus()));
        topicDescriptionElement.appendChild(entityAvailabilityStatusElement);
    }

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

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

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

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element titleElement = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "title");
                if (titleElement != null) {
                }

                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element topicDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "TopicDescription");
                    if (topicDescriptionElement2 != null) {
                        ServiceBusTopic topicDescriptionInstance = new ServiceBusTopic();
                        result.setTopic(topicDescriptionInstance);

                        Element defaultMessageTimeToLiveElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DefaultMessageTimeToLive");
                        if (defaultMessageTimeToLiveElement2 != null) {
                            String defaultMessageTimeToLiveInstance;
                            defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance);
                        }

                        Element maxSizeInMegabytesElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxSizeInMegabytes");
                        if (maxSizeInMegabytesElement2 != null) {
                            int maxSizeInMegabytesInstance;
                            maxSizeInMegabytesInstance = DatatypeConverter
                                    .parseInt(maxSizeInMegabytesElement2.getTextContent());
                            topicDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance);
                        }

                        Element requiresDuplicateDetectionElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresDuplicateDetection");
                        if (requiresDuplicateDetectionElement2 != null) {
                            boolean requiresDuplicateDetectionInstance;
                            requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean(
                                    requiresDuplicateDetectionElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance);
                        }

                        Element duplicateDetectionHistoryTimeWindowElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DuplicateDetectionHistoryTimeWindow");
                        if (duplicateDetectionHistoryTimeWindowElement2 != null) {
                            String duplicateDetectionHistoryTimeWindowInstance;
                            duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement2
                                    .getTextContent();
                            topicDescriptionInstance.setDuplicateDetectionHistoryTimeWindow(
                                    duplicateDetectionHistoryTimeWindowInstance);
                        }

                        Element enableBatchedOperationsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EnableBatchedOperations");
                        if (enableBatchedOperationsElement2 != null) {
                            boolean enableBatchedOperationsInstance;
                            enableBatchedOperationsInstance = DatatypeConverter.parseBoolean(
                                    enableBatchedOperationsElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setEnableBatchedOperations(enableBatchedOperationsInstance);
                        }

                        Element sizeInBytesElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SizeInBytes");
                        if (sizeInBytesElement2 != null) {
                            int sizeInBytesInstance;
                            sizeInBytesInstance = DatatypeConverter
                                    .parseInt(sizeInBytesElement2.getTextContent());
                            topicDescriptionInstance.setSizeInBytes(sizeInBytesInstance);
                        }

                        Element filteringMessagesBeforePublishingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "FilteringMessagesBeforePublishing");
                        if (filteringMessagesBeforePublishingElement2 != null) {
                            boolean filteringMessagesBeforePublishingInstance;
                            filteringMessagesBeforePublishingInstance = DatatypeConverter.parseBoolean(
                                    filteringMessagesBeforePublishingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setFilteringMessagesBeforePublishing(
                                    filteringMessagesBeforePublishingInstance);
                        }

                        Element isAnonymousAccessibleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "IsAnonymousAccessible");
                        if (isAnonymousAccessibleElement2 != null) {
                            boolean isAnonymousAccessibleInstance;
                            isAnonymousAccessibleInstance = DatatypeConverter
                                    .parseBoolean(isAnonymousAccessibleElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance);
                        }

                        Element authorizationRulesSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AuthorizationRules");
                        if (authorizationRulesSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AuthorizationRule")
                                    .size(); i1 = i1 + 1) {
                                org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                "AuthorizationRule")
                                        .get(i1));
                                ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                                topicDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance);

                                Element claimTypeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimType");
                                if (claimTypeElement2 != null) {
                                    String claimTypeInstance;
                                    claimTypeInstance = claimTypeElement2.getTextContent();
                                    authorizationRuleInstance.setClaimType(claimTypeInstance);
                                }

                                Element claimValueElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimValue");
                                if (claimValueElement2 != null) {
                                    String claimValueInstance;
                                    claimValueInstance = claimValueElement2.getTextContent();
                                    authorizationRuleInstance.setClaimValue(claimValueInstance);
                                }

                                Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "Rights");
                                if (rightsSequenceElement2 != null) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(rightsSequenceElement2,
                                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                    "AccessRights")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(rightsSequenceElement2,
                                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                        "AccessRights")
                                                .get(i2));
                                        authorizationRuleInstance.getRights()
                                                .add(AccessRight.valueOf(rightsElement.getTextContent()));
                                    }
                                }

                                Element createdTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "CreatedTime");
                                if (createdTimeElement2 != null) {
                                    Calendar createdTimeInstance;
                                    createdTimeInstance = DatatypeConverter
                                            .parseDateTime(createdTimeElement2.getTextContent());
                                    authorizationRuleInstance.setCreatedTime(createdTimeInstance);
                                }

                                Element keyNameElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "KeyName");
                                if (keyNameElement2 != null) {
                                    String keyNameInstance;
                                    keyNameInstance = keyNameElement2.getTextContent();
                                    authorizationRuleInstance.setKeyName(keyNameInstance);
                                }

                                Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ModifiedTime");
                                if (modifiedTimeElement2 != null) {
                                    Calendar modifiedTimeInstance;
                                    modifiedTimeInstance = DatatypeConverter
                                            .parseDateTime(modifiedTimeElement2.getTextContent());
                                    authorizationRuleInstance.setModifiedTime(modifiedTimeInstance);
                                }

                                Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "PrimaryKey");
                                if (primaryKeyElement2 != null) {
                                    String primaryKeyInstance;
                                    primaryKeyInstance = primaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setPrimaryKey(primaryKeyInstance);
                                }

                                Element secondaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "SecondaryKey");
                                if (secondaryKeyElement2 != null) {
                                    String secondaryKeyInstance;
                                    secondaryKeyInstance = secondaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance);
                                }
                            }
                        }

                        Element statusElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Status");
                        if (statusElement2 != null) {
                            String statusInstance;
                            statusInstance = statusElement2.getTextContent();
                            topicDescriptionInstance.setStatus(statusInstance);
                        }

                        Element createdAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedAt");
                        if (createdAtElement2 != null) {
                            Calendar createdAtInstance;
                            createdAtInstance = DatatypeConverter
                                    .parseDateTime(createdAtElement2.getTextContent());
                            topicDescriptionInstance.setCreatedAt(createdAtInstance);
                        }

                        Element updatedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "UpdatedAt");
                        if (updatedAtElement2 != null) {
                            Calendar updatedAtInstance;
                            updatedAtInstance = DatatypeConverter
                                    .parseDateTime(updatedAtElement2.getTextContent());
                            topicDescriptionInstance.setUpdatedAt(updatedAtInstance);
                        }

                        Element accessedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AccessedAt");
                        if (accessedAtElement2 != null) {
                            Calendar accessedAtInstance;
                            accessedAtInstance = DatatypeConverter
                                    .parseDateTime(accessedAtElement2.getTextContent());
                            topicDescriptionInstance.setAccessedAt(accessedAtInstance);
                        }

                        Element supportOrderingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SupportOrdering");
                        if (supportOrderingElement2 != null) {
                            boolean supportOrderingInstance;
                            supportOrderingInstance = DatatypeConverter
                                    .parseBoolean(supportOrderingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setSupportOrdering(supportOrderingInstance);
                        }

                        Element countDetailsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CountDetails");
                        if (countDetailsElement2 != null) {
                            CountDetails countDetailsInstance = new CountDetails();
                            topicDescriptionInstance.setCountDetails(countDetailsInstance);
                        }

                        Element subscriptionCountElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionCount");
                        if (subscriptionCountElement2 != null) {
                            int subscriptionCountInstance;
                            subscriptionCountInstance = DatatypeConverter
                                    .parseInt(subscriptionCountElement2.getTextContent());
                            topicDescriptionInstance.setSubscriptionCount(subscriptionCountInstance);
                        }

                        Element autoDeleteOnIdleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AutoDeleteOnIdle");
                        if (autoDeleteOnIdleElement2 != null) {
                            String autoDeleteOnIdleInstance;
                            autoDeleteOnIdleInstance = autoDeleteOnIdleElement2.getTextContent();
                            topicDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance);
                        }

                        Element entityAvailabilityStatusElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EntityAvailabilityStatus");
                        if (entityAvailabilityStatusElement2 != null) {
                            String entityAvailabilityStatusInstance;
                            entityAvailabilityStatusInstance = entityAvailabilityStatusElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setEntityAvailabilityStatus(entityAvailabilityStatusInstance);
                        }
                    }
                }
            }

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

/**
* The delete publicIpAddress operation deletes the specified
* publicIpAddress.//from   w w w.j av  a2 s.  co  m
*
* @param resourceGroupName Required. The name of the resource group.
* @param publicIpAddressName Required. The name of the subnet.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return If the resource provide needs to return an error to any
* operation, it should return the appropriate HTTP error code and a
* message body as can be seen below.The message should be localized per
* the Accept-Language header specified in the original request such thatit
* could be directly be exposed to users
*/
@Override
public UpdateOperationResponse beginDeleting(String resourceGroupName, String publicIpAddressName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (publicIpAddressName == null) {
        throw new NullPointerException("publicIpAddressName");
    }

    // 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);
        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 + "/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
    CustomHttpDelete httpRequest = new CustomHttpDelete(url);

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

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

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

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

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

/**
* The Put VirtualNetworkGateway operation creates/updates a virtual network
* gateway in the specified resource group through Network resource
* provider./*from   w ww. java 2 s .com*/
*
* @param resourceGroupName Required. The name of the resource group.
* @param virtualNetworkGatewayName Required. The name of the virtual
* network gateway.
* @param parameters Required. Parameters supplied to the Begin Create or
* update Virtual 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 PutVirtualNetworkGateway Api servive call
*/
@Override
public VirtualNetworkGatewayPutResponse beginCreateOrUpdating(String resourceGroupName,
        String virtualNetworkGatewayName, VirtualNetworkGateway parameters)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (virtualNetworkGatewayName == null) {
        throw new NullPointerException("virtualNetworkGatewayName");
    }
    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("virtualNetworkGatewayName", virtualNetworkGatewayName);
        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 + "/virtualnetworkgateways/";
    url = url + URLEncoder.encode(virtualNetworkGatewayName, "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 virtualNetworkGatewayJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = virtualNetworkGatewayJsonFormatValue;

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

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

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

                if (ipConfigurationsItem.getPrivateIpAddress() != null) {
                    ((ObjectNode) propertiesValue2).put("privateIPAddress",
                            ipConfigurationsItem.getPrivateIpAddress());
                }

                if (ipConfigurationsItem.getPrivateIpAllocationMethod() != null) {
                    ((ObjectNode) propertiesValue2).put("privateIPAllocationMethod",
                            ipConfigurationsItem.getPrivateIpAllocationMethod());
                }

                if (ipConfigurationsItem.getSubnet() != null) {
                    ObjectNode subnetValue = objectMapper.createObjectNode();
                    ((ObjectNode) propertiesValue2).put("subnet", subnetValue);

                    if (ipConfigurationsItem.getSubnet().getId() != null) {
                        ((ObjectNode) subnetValue).put("id", ipConfigurationsItem.getSubnet().getId());
                    }
                }

                if (ipConfigurationsItem.getPublicIpAddress() != null) {
                    ObjectNode publicIPAddressValue = objectMapper.createObjectNode();
                    ((ObjectNode) propertiesValue2).put("publicIPAddress", publicIPAddressValue);

                    if (ipConfigurationsItem.getPublicIpAddress().getId() != null) {
                        ((ObjectNode) publicIPAddressValue).put("id",
                                ipConfigurationsItem.getPublicIpAddress().getId());
                    }
                }

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

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

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

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

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

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

    ((ObjectNode) propertiesValue).put("enableBgp", parameters.isEnableBgp());

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

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

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

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

    ((ObjectNode) virtualNetworkGatewayJsonFormatValue).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) virtualNetworkGatewayJsonFormatValue).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
        VirtualNetworkGatewayPutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualNetworkGatewayPutResponse();
            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) {
                VirtualNetworkGateway virtualNetworkGatewayInstance = new VirtualNetworkGateway();
                result.setVirtualNetworkGateway(virtualNetworkGatewayInstance);

                JsonNode propertiesValue3 = responseDoc.get("properties");
                if (propertiesValue3 != null && propertiesValue3 instanceof NullNode == false) {
                    JsonNode ipConfigurationsArray2 = propertiesValue3.get("ipConfigurations");
                    if (ipConfigurationsArray2 != null && ipConfigurationsArray2 instanceof NullNode == false) {
                        for (JsonNode ipConfigurationsValue : ((ArrayNode) ipConfigurationsArray2)) {
                            VirtualNetworkGatewayIpConfiguration virtualNetworkGatewayIpConfigurationJsonFormatInstance = new VirtualNetworkGatewayIpConfiguration();
                            virtualNetworkGatewayInstance.getIpConfigurations()
                                    .add(virtualNetworkGatewayIpConfigurationJsonFormatInstance);

                            JsonNode propertiesValue4 = ipConfigurationsValue.get("properties");
                            if (propertiesValue4 != null && propertiesValue4 instanceof NullNode == false) {
                                JsonNode privateIPAddressValue = propertiesValue4.get("privateIPAddress");
                                if (privateIPAddressValue != null
                                        && privateIPAddressValue instanceof NullNode == false) {
                                    String privateIPAddressInstance;
                                    privateIPAddressInstance = privateIPAddressValue.getTextValue();
                                    virtualNetworkGatewayIpConfigurationJsonFormatInstance
                                            .setPrivateIpAddress(privateIPAddressInstance);
                                }

                                JsonNode privateIPAllocationMethodValue = propertiesValue4
                                        .get("privateIPAllocationMethod");
                                if (privateIPAllocationMethodValue != null
                                        && privateIPAllocationMethodValue instanceof NullNode == false) {
                                    String privateIPAllocationMethodInstance;
                                    privateIPAllocationMethodInstance = privateIPAllocationMethodValue
                                            .getTextValue();
                                    virtualNetworkGatewayIpConfigurationJsonFormatInstance
                                            .setPrivateIpAllocationMethod(privateIPAllocationMethodInstance);
                                }

                                JsonNode subnetValue2 = propertiesValue4.get("subnet");
                                if (subnetValue2 != null && subnetValue2 instanceof NullNode == false) {
                                    ResourceId subnetInstance = new ResourceId();
                                    virtualNetworkGatewayIpConfigurationJsonFormatInstance
                                            .setSubnet(subnetInstance);

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

                                JsonNode publicIPAddressValue2 = propertiesValue4.get("publicIPAddress");
                                if (publicIPAddressValue2 != null
                                        && publicIPAddressValue2 instanceof NullNode == false) {
                                    ResourceId publicIPAddressInstance = new ResourceId();
                                    virtualNetworkGatewayIpConfigurationJsonFormatInstance
                                            .setPublicIpAddress(publicIPAddressInstance);

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

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

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

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

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

                    JsonNode gatewayTypeValue = propertiesValue3.get("gatewayType");
                    if (gatewayTypeValue != null && gatewayTypeValue instanceof NullNode == false) {
                        String gatewayTypeInstance;
                        gatewayTypeInstance = gatewayTypeValue.getTextValue();
                        virtualNetworkGatewayInstance.setGatewayType(gatewayTypeInstance);
                    }

                    JsonNode vpnTypeValue = propertiesValue3.get("vpnType");
                    if (vpnTypeValue != null && vpnTypeValue instanceof NullNode == false) {
                        String vpnTypeInstance;
                        vpnTypeInstance = vpnTypeValue.getTextValue();
                        virtualNetworkGatewayInstance.setVpnType(vpnTypeInstance);
                    }

                    JsonNode enableBgpValue = propertiesValue3.get("enableBgp");
                    if (enableBgpValue != null && enableBgpValue instanceof NullNode == false) {
                        boolean enableBgpInstance;
                        enableBgpInstance = enableBgpValue.getBooleanValue();
                        virtualNetworkGatewayInstance.setEnableBgp(enableBgpInstance);
                    }

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

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

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

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    virtualNetworkGatewayInstance.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();
                        virtualNetworkGatewayInstance.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 Delete RouteTable operation deletes the specifed Route Table
*
* @param resourceGroupName Required. The name of the resource group.
* @param routeTableName Required. The name of the route table.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.//from   w w w  . java  2  s  .c o  m
* @throws ServiceException Thrown if an unexpected response is found.
* @return If the resource provide needs to return an error to any
* operation, it should return the appropriate HTTP error code and a
* message body as can be seen below.The message should be localized per
* the Accept-Language header specified in the original request such thatit
* could be directly be exposed to users
*/
@Override
public UpdateOperationResponse beginDeleting(String resourceGroupName, String routeTableName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (routeTableName == null) {
        throw new NullPointerException("routeTableName");
    }

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