Example usage for org.w3c.dom Document createElementNS

List of usage examples for org.w3c.dom Document createElementNS

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

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

/**
* Set the specified route for the provided table in this subscription.
*
* @param routeTableName Required. The name of the route table where the
* provided route will be set.// ww  w  .  ja va2  s . co  m
* @param routeName Required. The name of the route that will be set on the
* provided route table.
* @param parameters Required. The parameters necessary to create a new
* route table.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginSetRoute(String routeTableName, String routeName, SetRouteParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (routeTableName == null) {
        throw new NullPointerException("routeTableName");
    }
    if (routeName == null) {
        throw new NullPointerException("routeName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

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

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

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

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

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

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        routeElement.appendChild(nameElement);
    }

    if (parameters.getAddressPrefix() != null) {
        Element addressPrefixElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AddressPrefix");
        addressPrefixElement.appendChild(requestDoc.createTextNode(parameters.getAddressPrefix()));
        routeElement.appendChild(addressPrefixElement);
    }

    if (parameters.getNextHop() != null) {
        Element nextHopTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "NextHopType");
        routeElement.appendChild(nextHopTypeElement);

        if (parameters.getNextHop().getType() != null) {
            Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Type");
            typeElement.appendChild(requestDoc.createTextNode(parameters.getNextHop().getType()));
            nextHopTypeElement.appendChild(typeElement);
        }

        if (parameters.getNextHop().getIpAddress() != null) {
            Element ipAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "IpAddress");
            ipAddressElement.appendChild(requestDoc.createTextNode(parameters.getNextHop().getIpAddress()));
            nextHopTypeElement.appendChild(ipAddressElement);
        }
    }

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

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

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

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

/**
* Creates a new service namespace. Once created, this namespace's resource
* manifest is immutable. This operation is idempotent.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for
* more information)//from w ww . java 2 s . c o  m
*
* @param namespaceName Required. The namespace name.
* @param region Optional. The namespace region.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The response to a request for a particular namespace.
*/
@Override
public ServiceBusNamespaceResponse create(String namespaceName, String region)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("namespaceName", namespaceName);
        tracingParameters.put("region", region);
        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");
    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("Accept", "application/atom+xml");
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-07-01");

    // 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/xml");
    contentElement.setAttributeNode(typeAttribute);

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

    if (region != null) {
        Element regionElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Region");
        regionElement.appendChild(requestDoc.createTextNode(region));
        namespaceDescriptionElement.appendChild(regionElement);
    }

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

        // Create Result
        ServiceBusNamespaceResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusNamespaceResponse();
            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 contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element namespaceDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "NamespaceDescription");
                    if (namespaceDescriptionElement2 != null) {
                        ServiceBusNamespace namespaceDescriptionInstance = new ServiceBusNamespace();
                        result.setNamespace(namespaceDescriptionInstance);

                        Element nameElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Name");
                        if (nameElement != null) {
                            String nameInstance;
                            nameInstance = nameElement.getTextContent();
                            namespaceDescriptionInstance.setName(nameInstance);
                        }

                        Element regionElement2 = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Region");
                        if (regionElement2 != null) {
                            String regionInstance;
                            regionInstance = regionElement2.getTextContent();
                            namespaceDescriptionInstance.setRegion(regionInstance);
                        }

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

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

                        Element acsManagementEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AcsManagementEndpoint");
                        if (acsManagementEndpointElement != null) {
                            URI acsManagementEndpointInstance;
                            acsManagementEndpointInstance = new URI(
                                    acsManagementEndpointElement.getTextContent());
                            namespaceDescriptionInstance
                                    .setAcsManagementEndpoint(acsManagementEndpointInstance);
                        }

                        Element serviceBusEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ServiceBusEndpoint");
                        if (serviceBusEndpointElement != null) {
                            URI serviceBusEndpointInstance;
                            serviceBusEndpointInstance = new URI(serviceBusEndpointElement.getTextContent());
                            namespaceDescriptionInstance.setServiceBusEndpoint(serviceBusEndpointInstance);
                        }

                        Element subscriptionIdElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionId");
                        if (subscriptionIdElement != null) {
                            String subscriptionIdInstance;
                            subscriptionIdInstance = subscriptionIdElement.getTextContent();
                            namespaceDescriptionInstance.setSubscriptionId(subscriptionIdInstance);
                        }

                        Element enabledElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Enabled");
                        if (enabledElement != null) {
                            boolean enabledInstance;
                            enabledInstance = DatatypeConverter
                                    .parseBoolean(enabledElement.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setEnabled(enabledInstance);
                        }

                        Element createACSNamespaceElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreateACSNamespace");
                        if (createACSNamespaceElement != null) {
                            boolean createACSNamespaceInstance;
                            createACSNamespaceInstance = DatatypeConverter
                                    .parseBoolean(createACSNamespaceElement.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setCreateACSNamespace(createACSNamespaceInstance);
                        }

                        Element namespaceTypeElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "NamespaceType");
                        if (namespaceTypeElement != null && namespaceTypeElement.getTextContent() != null
                                && !namespaceTypeElement.getTextContent().isEmpty()) {
                            NamespaceType namespaceTypeInstance;
                            namespaceTypeInstance = NamespaceType
                                    .valueOf(namespaceTypeElement.getTextContent());
                            namespaceDescriptionInstance.setNamespaceType(namespaceTypeInstance);
                        }
                    }
                }
            }

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

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

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

/**
* The Update OS Image operation updates an OS image that in your image
* repository.  (see/* w  w  w .j  a  v  a2  s . c  o m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for
* more information)
*
* @param imageName Required. The name of the virtual machine image to be
* updated.
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine Image operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @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 ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Parameters returned from the Create Virtual Machine Image
* operation.
*/
@Override
public VirtualMachineOSImageUpdateResponse update(String imageName,
        VirtualMachineOSImageUpdateParameters parameters)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
    // Validate
    if (imageName == null) {
        throw new NullPointerException("imageName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }

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

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

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

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

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

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

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
    oSImageElement.appendChild(labelElement);

    if (parameters.getEula() != null) {
        Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
        eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula()));
        oSImageElement.appendChild(eulaElement);
    }

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        oSImageElement.appendChild(descriptionElement);
    }

    if (parameters.getImageFamily() != null) {
        Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ImageFamily");
        imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily()));
        oSImageElement.appendChild(imageFamilyElement);
    }

    if (parameters.isShowInGui() != null) {
        Element showInGuiElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ShowInGui");
        showInGuiElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isShowInGui()).toLowerCase()));
        oSImageElement.appendChild(showInGuiElement);
    }

    if (parameters.getPublishedDate() != null) {
        Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublishedDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        publishedDateElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
        oSImageElement.appendChild(publishedDateElement);
    }

    if (parameters.isPremium() != null) {
        Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IsPremium");
        isPremiumElement
                .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase()));
        oSImageElement.appendChild(isPremiumElement);
    }

    if (parameters.getPrivacyUri() != null) {
        Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PrivacyUri");
        privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
        oSImageElement.appendChild(privacyUriElement);
    }

    if (parameters.getIconUri() != null) {
        Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IconUri");
        iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri()));
        oSImageElement.appendChild(iconUriElement);
    }

    if (parameters.getRecommendedVMSize() != null) {
        Element recommendedVMSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
        recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize()));
        oSImageElement.appendChild(recommendedVMSizeElement);
    }

    if (parameters.getSmallIconUri() != null) {
        Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SmallIconUri");
        smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri()));
        oSImageElement.appendChild(smallIconUriElement);
    }

    if (parameters.getLanguage() != null) {
        Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Language");
        languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage()));
        oSImageElement.appendChild(languageElement);
    }

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

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

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

            Element oSImageElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OSImage");
            if (oSImageElement2 != null) {
                Element locationElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Location");
                if (locationElement != null) {
                    String locationInstance;
                    locationInstance = locationElement.getTextContent();
                    result.setLocation(locationInstance);
                }

                Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Category");
                if (categoryElement != null) {
                    String categoryInstance;
                    categoryInstance = categoryElement.getTextContent();
                    result.setCategory(categoryInstance);
                }

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

                Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                if (logicalSizeInGBElement != null) {
                    double logicalSizeInGBInstance;
                    logicalSizeInGBInstance = DatatypeConverter
                            .parseDouble(logicalSizeInGBElement.getTextContent());
                    result.setLogicalSizeInGB(logicalSizeInGBInstance);
                }

                Element mediaLinkElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "MediaLink");
                if (mediaLinkElement != null) {
                    URI mediaLinkInstance;
                    mediaLinkInstance = new URI(mediaLinkElement.getTextContent());
                    result.setMediaLinkUri(mediaLinkInstance);
                }

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

                Element osElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "OS");
                if (osElement != null) {
                    String osInstance;
                    osInstance = osElement.getTextContent();
                    result.setOperatingSystemType(osInstance);
                }

                Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Eula");
                if (eulaElement2 != null) {
                    String eulaInstance;
                    eulaInstance = eulaElement2.getTextContent();
                    result.setEula(eulaInstance);
                }

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

                Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                if (imageFamilyElement2 != null) {
                    String imageFamilyInstance;
                    imageFamilyInstance = imageFamilyElement2.getTextContent();
                    result.setImageFamily(imageFamilyInstance);
                }

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

                Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublisherName");
                if (publisherNameElement != null) {
                    String publisherNameInstance;
                    publisherNameInstance = publisherNameElement.getTextContent();
                    result.setPublisherName(publisherNameInstance);
                }

                Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsPremium");
                if (isPremiumElement2 != null && isPremiumElement2.getTextContent() != null
                        && !isPremiumElement2.getTextContent().isEmpty()) {
                    boolean isPremiumInstance;
                    isPremiumInstance = DatatypeConverter
                            .parseBoolean(isPremiumElement2.getTextContent().toLowerCase());
                    result.setIsPremium(isPremiumInstance);
                }

                Element showInGuiElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                if (showInGuiElement2 != null && showInGuiElement2.getTextContent() != null
                        && !showInGuiElement2.getTextContent().isEmpty()) {
                    boolean showInGuiInstance;
                    showInGuiInstance = DatatypeConverter
                            .parseBoolean(showInGuiElement2.getTextContent().toLowerCase());
                    result.setShowInGui(showInGuiInstance);
                }

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

                Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IconUri");
                if (iconUriElement2 != null) {
                    String iconUriInstance;
                    iconUriInstance = iconUriElement2.getTextContent();
                    result.setIconUri(iconUriInstance);
                }

                Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                if (recommendedVMSizeElement2 != null) {
                    String recommendedVMSizeInstance;
                    recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent();
                    result.setRecommendedVMSize(recommendedVMSizeInstance);
                }

                Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                if (smallIconUriElement2 != null) {
                    String smallIconUriInstance;
                    smallIconUriInstance = smallIconUriElement2.getTextContent();
                    result.setSmallIconUri(smallIconUriInstance);
                }

                Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Language");
                if (languageElement2 != null) {
                    String languageInstance;
                    languageInstance = languageElement2.getTextContent();
                    result.setLanguage(languageInstance);
                }

                Element iOTypeElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IOType");
                if (iOTypeElement != null) {
                    String iOTypeInstance;
                    iOTypeInstance = iOTypeElement.getTextContent();
                    result.setIOType(iOTypeInstance);
                }
            }

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

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

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

/**
* The Create OS Image operation adds an operating system image that is
* stored in a storage account and is available from the image repository.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx
* for more information)//from   w w w .  ja v  a 2  s  .co m
*
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Image operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @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 ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Parameters returned from the Create Virtual Machine Image
* operation.
*/
@Override
public VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getMediaLinkUri() == null) {
        throw new NullPointerException("parameters.MediaLinkUri");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getOperatingSystemType() == null) {
        throw new NullPointerException("parameters.OperatingSystemType");
    }

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

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

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

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

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

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

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
    oSImageElement.appendChild(labelElement);

    Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "MediaLink");
    mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString()));
    oSImageElement.appendChild(mediaLinkElement);

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

    Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS");
    osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType()));
    oSImageElement.appendChild(osElement);

    if (parameters.getEula() != null) {
        Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
        eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula()));
        oSImageElement.appendChild(eulaElement);
    }

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        oSImageElement.appendChild(descriptionElement);
    }

    if (parameters.getImageFamily() != null) {
        Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ImageFamily");
        imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily()));
        oSImageElement.appendChild(imageFamilyElement);
    }

    if (parameters.getPublishedDate() != null) {
        Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublishedDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        publishedDateElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
        oSImageElement.appendChild(publishedDateElement);
    }

    Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsPremium");
    isPremiumElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase()));
    oSImageElement.appendChild(isPremiumElement);

    Element showInGuiElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ShowInGui");
    showInGuiElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isShowInGui()).toLowerCase()));
    oSImageElement.appendChild(showInGuiElement);

    if (parameters.getPrivacyUri() != null) {
        Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PrivacyUri");
        privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
        oSImageElement.appendChild(privacyUriElement);
    }

    if (parameters.getIconUri() != null) {
        Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IconUri");
        iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri()));
        oSImageElement.appendChild(iconUriElement);
    }

    if (parameters.getRecommendedVMSize() != null) {
        Element recommendedVMSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
        recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize()));
        oSImageElement.appendChild(recommendedVMSizeElement);
    }

    if (parameters.getSmallIconUri() != null) {
        Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SmallIconUri");
        smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri()));
        oSImageElement.appendChild(smallIconUriElement);
    }

    if (parameters.getLanguage() != null) {
        Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Language");
        languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage()));
        oSImageElement.appendChild(languageElement);
    }

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

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

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

            Element oSImageElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OSImage");
            if (oSImageElement2 != null) {
                Element locationElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Location");
                if (locationElement != null) {
                    String locationInstance;
                    locationInstance = locationElement.getTextContent();
                    result.setLocation(locationInstance);
                }

                Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Category");
                if (categoryElement != null) {
                    String categoryInstance;
                    categoryInstance = categoryElement.getTextContent();
                    result.setCategory(categoryInstance);
                }

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

                Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                if (logicalSizeInGBElement != null) {
                    double logicalSizeInGBInstance;
                    logicalSizeInGBInstance = DatatypeConverter
                            .parseDouble(logicalSizeInGBElement.getTextContent());
                    result.setLogicalSizeInGB(logicalSizeInGBInstance);
                }

                Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "MediaLink");
                if (mediaLinkElement2 != null) {
                    URI mediaLinkInstance;
                    mediaLinkInstance = new URI(mediaLinkElement2.getTextContent());
                    result.setMediaLinkUri(mediaLinkInstance);
                }

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

                Element osElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "OS");
                if (osElement2 != null) {
                    String osInstance;
                    osInstance = osElement2.getTextContent();
                    result.setOperatingSystemType(osInstance);
                }

                Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Eula");
                if (eulaElement2 != null) {
                    String eulaInstance;
                    eulaInstance = eulaElement2.getTextContent();
                    result.setEula(eulaInstance);
                }

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

                Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                if (imageFamilyElement2 != null) {
                    String imageFamilyInstance;
                    imageFamilyInstance = imageFamilyElement2.getTextContent();
                    result.setImageFamily(imageFamilyInstance);
                }

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

                Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublisherName");
                if (publisherNameElement != null) {
                    String publisherNameInstance;
                    publisherNameInstance = publisherNameElement.getTextContent();
                    result.setPublisherName(publisherNameInstance);
                }

                Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsPremium");
                if (isPremiumElement2 != null && isPremiumElement2.getTextContent() != null
                        && !isPremiumElement2.getTextContent().isEmpty()) {
                    boolean isPremiumInstance;
                    isPremiumInstance = DatatypeConverter
                            .parseBoolean(isPremiumElement2.getTextContent().toLowerCase());
                    result.setIsPremium(isPremiumInstance);
                }

                Element showInGuiElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                if (showInGuiElement2 != null && showInGuiElement2.getTextContent() != null
                        && !showInGuiElement2.getTextContent().isEmpty()) {
                    boolean showInGuiInstance;
                    showInGuiInstance = DatatypeConverter
                            .parseBoolean(showInGuiElement2.getTextContent().toLowerCase());
                    result.setShowInGui(showInGuiInstance);
                }

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

                Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IconUri");
                if (iconUriElement2 != null) {
                    String iconUriInstance;
                    iconUriInstance = iconUriElement2.getTextContent();
                    result.setIconUri(iconUriInstance);
                }

                Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                if (recommendedVMSizeElement2 != null) {
                    String recommendedVMSizeInstance;
                    recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent();
                    result.setRecommendedVMSize(recommendedVMSizeInstance);
                }

                Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                if (smallIconUriElement2 != null) {
                    String smallIconUriInstance;
                    smallIconUriInstance = smallIconUriElement2.getTextContent();
                    result.setSmallIconUri(smallIconUriInstance);
                }

                Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Language");
                if (languageElement2 != null) {
                    String languageInstance;
                    languageInstance = languageElement2.getTextContent();
                    result.setLanguage(languageInstance);
                }

                Element iOTypeElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IOType");
                if (iOTypeElement != null) {
                    String iOTypeInstance;
                    iOTypeInstance = iOTypeElement.getTextContent();
                    result.setIOType(iOTypeInstance);
                }
            }

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

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

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

/**
* Creates a new service namespace. Once created, this namespace's resource
* manifest is immutable. This operation is idempotent.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for
* more information)//  w  w w .ja v  a 2s.c  om
*
* @param namespaceName Required. The namespace name.
* @param namespaceEntity Required. The service bus namespace.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The response to a request for a particular namespace.
*/
@Override
public ServiceBusNamespaceResponse createNamespace(String namespaceName,
        ServiceBusNamespaceCreateParameters namespaceEntity) throws ParserConfigurationException, SAXException,
        TransformerException, IOException, ServiceException, URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (namespaceEntity == null) {
        throw new NullPointerException("namespaceEntity");
    }
    if (namespaceEntity.getNamespaceType() == null) {
        throw new NullPointerException("namespaceEntity.NamespaceType");
    }
    if (namespaceEntity.getRegion() == null) {
        throw new NullPointerException("namespaceEntity.Region");
    }

    // 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("namespaceEntity", namespaceEntity);
        CloudTracing.enter(invocationId, this, "createNamespaceAsync", 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");
    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("Accept", "application/atom+xml");
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2014-06-01");

    // 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 namespaceDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceDescription");
    contentElement.appendChild(namespaceDescriptionElement);

    if (namespaceEntity.getRegion() != null) {
        Element regionElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Region");
        regionElement.appendChild(requestDoc.createTextNode(namespaceEntity.getRegion()));
        namespaceDescriptionElement.appendChild(regionElement);
    }

    Element createACSNamespaceElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreateACSNamespace");
    createACSNamespaceElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(namespaceEntity.isCreateACSNamespace()).toLowerCase()));
    namespaceDescriptionElement.appendChild(createACSNamespaceElement);

    if (namespaceEntity.getNamespaceType() != null) {
        Element namespaceTypeElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceType");
        namespaceTypeElement
                .appendChild(requestDoc.createTextNode(namespaceEntity.getNamespaceType().toString()));
        namespaceDescriptionElement.appendChild(namespaceTypeElement);
    }

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

        // Create Result
        ServiceBusNamespaceResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusNamespaceResponse();
            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 contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element namespaceDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "NamespaceDescription");
                    if (namespaceDescriptionElement2 != null) {
                        ServiceBusNamespace namespaceDescriptionInstance = new ServiceBusNamespace();
                        result.setNamespace(namespaceDescriptionInstance);

                        Element nameElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Name");
                        if (nameElement != null) {
                            String nameInstance;
                            nameInstance = nameElement.getTextContent();
                            namespaceDescriptionInstance.setName(nameInstance);
                        }

                        Element regionElement2 = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Region");
                        if (regionElement2 != null) {
                            String regionInstance;
                            regionInstance = regionElement2.getTextContent();
                            namespaceDescriptionInstance.setRegion(regionInstance);
                        }

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

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

                        Element acsManagementEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AcsManagementEndpoint");
                        if (acsManagementEndpointElement != null) {
                            URI acsManagementEndpointInstance;
                            acsManagementEndpointInstance = new URI(
                                    acsManagementEndpointElement.getTextContent());
                            namespaceDescriptionInstance
                                    .setAcsManagementEndpoint(acsManagementEndpointInstance);
                        }

                        Element serviceBusEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ServiceBusEndpoint");
                        if (serviceBusEndpointElement != null) {
                            URI serviceBusEndpointInstance;
                            serviceBusEndpointInstance = new URI(serviceBusEndpointElement.getTextContent());
                            namespaceDescriptionInstance.setServiceBusEndpoint(serviceBusEndpointInstance);
                        }

                        Element subscriptionIdElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionId");
                        if (subscriptionIdElement != null) {
                            String subscriptionIdInstance;
                            subscriptionIdInstance = subscriptionIdElement.getTextContent();
                            namespaceDescriptionInstance.setSubscriptionId(subscriptionIdInstance);
                        }

                        Element enabledElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Enabled");
                        if (enabledElement != null) {
                            boolean enabledInstance;
                            enabledInstance = DatatypeConverter
                                    .parseBoolean(enabledElement.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setEnabled(enabledInstance);
                        }

                        Element createACSNamespaceElement2 = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreateACSNamespace");
                        if (createACSNamespaceElement2 != null) {
                            boolean createACSNamespaceInstance;
                            createACSNamespaceInstance = DatatypeConverter
                                    .parseBoolean(createACSNamespaceElement2.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setCreateACSNamespace(createACSNamespaceInstance);
                        }

                        Element namespaceTypeElement2 = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "NamespaceType");
                        if (namespaceTypeElement2 != null && namespaceTypeElement2.getTextContent() != null
                                && !namespaceTypeElement2.getTextContent().isEmpty()) {
                            NamespaceType namespaceTypeInstance;
                            namespaceTypeInstance = NamespaceType
                                    .valueOf(namespaceTypeElement2.getTextContent());
                            namespaceDescriptionInstance.setNamespaceType(namespaceTypeInstance);
                        }
                    }
                }
            }

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

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

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

/**
* The create namespace authorization rule operation creates an
* authorization rule for a namespace//  ww  w .ja  v a 2 s . c  o m
*
* @param namespaceName Required. The namespace name.
* @param rule Required. The shared access authorization rule.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A response to a request for a particular authorization rule.
*/
@Override
public ServiceBusAuthorizationRuleResponse createAuthorizationRule(String namespaceName,
        ServiceBusSharedAccessAuthorizationRule rule)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (rule == null) {
        throw new NullPointerException("rule");
    }

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

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

    // Set Headers
    httpRequest.setHeader("Accept", "application/atom+xml");
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-08-01");

    // 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");
    contentElement.setAttributeNode(typeAttribute);

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

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

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

    if (rule.getRights() != null) {
        if (rule.getRights() instanceof LazyCollection == false
                || ((LazyCollection) rule.getRights()).isInitialized()) {
            Element rightsSequenceElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights");
            for (AccessRight rightsItem : rule.getRights()) {
                Element rightsItemElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights");
                rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                rightsSequenceElement.appendChild(rightsItemElement);
            }
            sharedAccessAuthorizationRuleElement.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(rule.getCreatedTime().getTime())));
    sharedAccessAuthorizationRuleElement.appendChild(createdTimeElement);

    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(rule.getModifiedTime().getTime())));
    sharedAccessAuthorizationRuleElement.appendChild(modifiedTimeElement);

    Element revisionElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Revision");
    revisionElement.appendChild(requestDoc.createTextNode(Integer.toString(rule.getRevision())));
    sharedAccessAuthorizationRuleElement.appendChild(revisionElement);

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

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

    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
        ServiceBusAuthorizationRuleResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusAuthorizationRuleResponse();
            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 contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element sharedAccessAuthorizationRuleElement2 = XmlUtility.getElementByTagNameNS(
                            contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SharedAccessAuthorizationRule");
                    if (sharedAccessAuthorizationRuleElement2 != null) {
                        ServiceBusSharedAccessAuthorizationRule sharedAccessAuthorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                        result.setAuthorizationRule(sharedAccessAuthorizationRuleInstance);

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

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

                        Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        if (rightsSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(rightsSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AccessRights")
                                    .size(); i1 = i1 + 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(i1));
                                sharedAccessAuthorizationRuleInstance.getRights()
                                        .add(AccessRight.valueOf(rightsElement.getTextContent()));
                            }
                        }

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

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

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

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

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

                        Element revisionElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Revision");
                        if (revisionElement2 != null) {
                            int revisionInstance;
                            revisionInstance = DatatypeConverter.parseInt(revisionElement2.getTextContent());
                            sharedAccessAuthorizationRuleInstance.setRevision(revisionInstance);
                        }
                    }
                }
            }

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

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

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

/**
* The update authorization rule operation updates an authorization rule for
* a namespace.//ww w  .ja v  a 2 s.  co  m
*
* @param namespaceName Required. The namespace name.
* @param rule Optional. Updated access authorization rule.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A response to a request for a particular authorization rule.
*/
@Override
public ServiceBusAuthorizationRuleResponse updateAuthorizationRule(String namespaceName,
        ServiceBusSharedAccessAuthorizationRule rule)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("namespaceName", namespaceName);
        tracingParameters.put("rule", rule);
        CloudTracing.enter(invocationId, this, "updateAuthorizationRuleAsync", 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 + "/AuthorizationRules/";
    if (rule != null && rule.getKeyName() != null) {
        url = url + URLEncoder.encode(rule.getKeyName(), "UTF-8");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("Accept", "application/atom+xml");
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("if-match", "*");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

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

    if (rule != null) {
        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");
        contentElement.setAttributeNode(typeAttribute);

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

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

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

        if (rule.getRights() != null) {
            if (rule.getRights() instanceof LazyCollection == false
                    || ((LazyCollection) rule.getRights()).isInitialized()) {
                Element rightsSequenceElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights");
                for (AccessRight rightsItem : rule.getRights()) {
                    Element rightsItemElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "AccessRights");
                    rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                    rightsSequenceElement.appendChild(rightsItemElement);
                }
                sharedAccessAuthorizationRuleElement.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(rule.getCreatedTime().getTime())));
        sharedAccessAuthorizationRuleElement.appendChild(createdTimeElement);

        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(rule.getModifiedTime().getTime())));
        sharedAccessAuthorizationRuleElement.appendChild(modifiedTimeElement);

        Element revisionElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Revision");
        revisionElement.appendChild(requestDoc.createTextNode(Integer.toString(rule.getRevision())));
        sharedAccessAuthorizationRuleElement.appendChild(revisionElement);

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

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

    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
        ServiceBusAuthorizationRuleResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusAuthorizationRuleResponse();
            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 contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element sharedAccessAuthorizationRuleElement2 = XmlUtility.getElementByTagNameNS(
                            contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SharedAccessAuthorizationRule");
                    if (sharedAccessAuthorizationRuleElement2 != null) {
                        ServiceBusSharedAccessAuthorizationRule sharedAccessAuthorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                        result.setAuthorizationRule(sharedAccessAuthorizationRuleInstance);

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

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

                        Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        if (rightsSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(rightsSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AccessRights")
                                    .size(); i1 = i1 + 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(i1));
                                sharedAccessAuthorizationRuleInstance.getRights()
                                        .add(AccessRight.valueOf(rightsElement.getTextContent()));
                            }
                        }

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

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

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

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

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

                        Element revisionElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Revision");
                        if (revisionElement2 != null) {
                            int revisionInstance;
                            revisionInstance = DatatypeConverter.parseInt(revisionElement2.getTextContent());
                            sharedAccessAuthorizationRuleInstance.setRevision(revisionInstance);
                        }
                    }
                }
            }

        }
        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  w  w  w.j a va2 s.  com
*
* @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.windowsazure.management.servicebus.TopicOperationsImpl.java

/**
* Updates a topic.  (see/* ww  w . jav  a 2  s .  c o m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/jj839740.aspx for
* more information)
*
* @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.
* @return A response to a request for a particular topic.
*/
@Override
public ServiceBusTopicResponse update(String namespaceName, ServiceBusTopic topic)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // 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, "updateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/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("if-match", "*");
    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_OK) {
            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_OK) {
            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:de.escidoc.core.test.EscidocTestBase.java

/**
 * Creates a new element node for the provided document.
 * //w  w w.j  av  a 2s  .  c  o m
 * @param doc
 *            The document for that the node shall be created.
 * @param namespaceUri
 *            The name space uri of the node to create. This may be null.
 * @param prefix
 *            The prefix to use.
 * @param tagName
 *            The tag name of the node.
 * @param textContent
 *            The text content of the node. This may be null.
 * @return Returns the created node.
 * @throws Exception
 *             Thrown if anything fails.
 */
public static Element createElementNode(final Document doc, final String namespaceUri, final String prefix,
        final String tagName, final String textContent) throws Exception {

    Element newNode = doc.createElementNS(namespaceUri, tagName);
    newNode.setPrefix(prefix);
    if (textContent != null) {
        newNode.setTextContent(textContent);
    }
    return newNode;
}