Example usage for org.w3c.dom Element setAttributeNode

List of usage examples for org.w3c.dom Element setAttributeNode

Introduction

In this page you can find the example usage for org.w3c.dom Element setAttributeNode.

Prototype

public Attr setAttributeNode(Attr newAttr) throws DOMException;

Source Link

Document

Adds a new attribute node.

Usage

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
* You can update the settings for a web site by using the HTTP PUT method
* and by specifying the settings in the request body.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn167005.aspx for
* more information)/*w  w w .j  a  va2  s  . c om*/
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param parameters Required. Parameters supplied to the Update Web Site
* operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Update Web Site operation response.
*/
@Override
public WebSiteUpdateResponse update(String webSpaceName, String webSiteName, WebSiteUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getHostNameSslStates() != null) {
        for (WebSiteUpdateParameters.WebSiteHostNameSslState hostNameSslStatesParameterItem : parameters
                .getHostNameSslStates()) {
            if (hostNameSslStatesParameterItem.getName() == null) {
                throw new NullPointerException("parameters.HostNameSslStates.Name");
            }
            if (hostNameSslStatesParameterItem.getSslState() == null) {
                throw new NullPointerException("parameters.HostNameSslStates.SslState");
            }
        }
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("webSpaceName", webSpaceName);
        tracingParameters.put("webSiteName", webSiteName);
        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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "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", "2014-04-01");

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

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

    if (parameters.getHostNameSslStates() != null) {
        if (parameters.getHostNameSslStates() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getHostNameSslStates()).isInitialized()) {
            Element hostNameSslStatesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "HostNameSslStates");
            for (WebSiteUpdateParameters.WebSiteHostNameSslState hostNameSslStatesItem : parameters
                    .getHostNameSslStates()) {
                Element webSiteHostNameSslStateElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/windowsazure", "WebSiteHostNameSslState");
                hostNameSslStatesSequenceElement.appendChild(webSiteHostNameSslStateElement);

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

                Element sslStateElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SslState");
                sslStateElement
                        .appendChild(requestDoc.createTextNode(hostNameSslStatesItem.getSslState().toString()));
                webSiteHostNameSslStateElement.appendChild(sslStateElement);

                if (hostNameSslStatesItem.getThumbprint() != null) {
                    Element thumbprintElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint");
                    thumbprintElement
                            .appendChild(requestDoc.createTextNode(hostNameSslStatesItem.getThumbprint()));
                    webSiteHostNameSslStateElement.appendChild(thumbprintElement);
                } else {
                    Element emptyElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint");
                    Attr nilAttribute = requestDoc
                            .createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    nilAttribute.setValue("true");
                    emptyElement.setAttributeNode(nilAttribute);
                    webSiteHostNameSslStateElement.appendChild(emptyElement);
                }

                Element toUpdateElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ToUpdate");
                toUpdateElement.appendChild(requestDoc.createTextNode("true"));
                webSiteHostNameSslStateElement.appendChild(toUpdateElement);
            }
            siteElement.appendChild(hostNameSslStatesSequenceElement);
        }
    }

    if (parameters.getHostNames() != null) {
        if (parameters.getHostNames() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getHostNames()).isInitialized()) {
            Element hostNamesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "HostNames");
            for (String hostNamesItem : parameters.getHostNames()) {
                Element hostNamesItemElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string");
                hostNamesItemElement.appendChild(requestDoc.createTextNode(hostNamesItem));
                hostNamesSequenceElement.appendChild(hostNamesItemElement);
            }
            siteElement.appendChild(hostNamesSequenceElement);
        }
    }

    if (parameters.getServerFarm() != null) {
        Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServerFarm");
        serverFarmElement.appendChild(requestDoc.createTextNode(parameters.getServerFarm()));
        siteElement.appendChild(serverFarmElement);
    }

    if (parameters.getState() != null) {
        Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State");
        stateElement.appendChild(requestDoc.createTextNode(parameters.getState()));
        siteElement.appendChild(stateElement);
    }

    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
        WebSiteUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebSiteUpdateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element siteElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Site");
            if (siteElement2 != null) {
                WebSite webSiteInstance = new WebSite();
                result.setWebSite(webSiteInstance);

                Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "AdminEnabled");
                if (adminEnabledElement != null && adminEnabledElement.getTextContent() != null
                        && !adminEnabledElement.getTextContent().isEmpty()) {
                    boolean adminEnabledInstance;
                    adminEnabledInstance = DatatypeConverter
                            .parseBoolean(adminEnabledElement.getTextContent().toLowerCase());
                    webSiteInstance.setAdminEnabled(adminEnabledInstance);
                }

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

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

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

                Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "EnabledHostNames");
                if (enabledHostNamesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i1));
                        webSiteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent());
                    }
                }

                Element hostNameSslStatesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "HostNameSslStates");
                if (hostNameSslStatesSequenceElement2 != null) {
                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNameSslStatesSequenceElement2,
                                    "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                            .size(); i2 = i2 + 1) {
                        org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNameSslStatesSequenceElement2,
                                        "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                                .get(i2));
                        WebSite.WebSiteHostNameSslState hostNameSslStateInstance = new WebSite.WebSiteHostNameSslState();
                        webSiteInstance.getHostNameSslStates().add(hostNameSslStateInstance);

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

                        Element sslStateElement2 = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "SslState");
                        if (sslStateElement2 != null && sslStateElement2.getTextContent() != null
                                && !sslStateElement2.getTextContent().isEmpty()) {
                            WebSiteSslState sslStateInstance;
                            sslStateInstance = WebSiteSslState.valueOf(sslStateElement2.getTextContent());
                            hostNameSslStateInstance.setSslState(sslStateInstance);
                        }

                        Element thumbprintElement2 = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                        if (thumbprintElement2 != null) {
                            boolean isNil = false;
                            Attr nilAttribute2 = thumbprintElement2
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute2 != null) {
                                isNil = "true".equals(nilAttribute2.getValue());
                            }
                            if (isNil == false) {
                                String thumbprintInstance;
                                thumbprintInstance = thumbprintElement2.getTextContent();
                                hostNameSslStateInstance.setThumbprint(thumbprintInstance);
                            }
                        }

                        Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "VirtualIP");
                        if (virtualIPElement != null) {
                            boolean isNil2 = false;
                            Attr nilAttribute3 = virtualIPElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute3 != null) {
                                isNil2 = "true".equals(nilAttribute3.getValue());
                            }
                            if (isNil2 == false) {
                                InetAddress virtualIPInstance;
                                virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent());
                                hostNameSslStateInstance.setVirtualIP(virtualIPInstance);
                            }
                        }
                    }
                }

                Element hostNamesSequenceElement2 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "HostNames");
                if (hostNamesSequenceElement2 != null) {
                    for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNamesSequenceElement2,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i3 = i3 + 1) {
                        org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNamesSequenceElement2,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i3));
                        webSiteInstance.getHostNames().add(hostNamesElement.getTextContent());
                    }
                }

                Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc");
                if (lastModifiedTimeUtcElement != null && lastModifiedTimeUtcElement.getTextContent() != null
                        && !lastModifiedTimeUtcElement.getTextContent().isEmpty()) {
                    Calendar lastModifiedTimeUtcInstance;
                    lastModifiedTimeUtcInstance = DatatypeConverter
                            .parseDateTime(lastModifiedTimeUtcElement.getTextContent());
                    webSiteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance);
                }

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

                Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "RepositorySiteName");
                if (repositorySiteNameElement != null) {
                    String repositorySiteNameInstance;
                    repositorySiteNameInstance = repositorySiteNameElement.getTextContent();
                    webSiteInstance.setRepositorySiteName(repositorySiteNameInstance);
                }

                Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState");
                if (runtimeAvailabilityStateElement != null
                        && runtimeAvailabilityStateElement.getTextContent() != null
                        && !runtimeAvailabilityStateElement.getTextContent().isEmpty()) {
                    WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance;
                    runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState
                            .valueOf(runtimeAvailabilityStateElement.getTextContent());
                    webSiteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance);
                }

                Element selfLinkElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "SelfLink");
                if (selfLinkElement != null) {
                    URI selfLinkInstance;
                    selfLinkInstance = new URI(selfLinkElement.getTextContent());
                    webSiteInstance.setUri(selfLinkInstance);
                }

                Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                if (serverFarmElement2 != null) {
                    String serverFarmInstance;
                    serverFarmInstance = serverFarmElement2.getTextContent();
                    webSiteInstance.setServerFarm(serverFarmInstance);
                }

                Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "SiteProperties");
                if (sitePropertiesElement != null) {
                    WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties();
                    webSiteInstance.setSiteProperties(sitePropertiesInstance);

                    Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "AppSettings");
                    if (appSettingsSequenceElement != null) {
                        for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(appSettingsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i4 = i4 + 1) {
                            org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(appSettingsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i4));
                            String appSettingsKey = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String appSettingsValue = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue);
                        }
                    }

                    Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Metadata");
                    if (metadataSequenceElement != null) {
                        for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metadataSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i5 = i5 + 1) {
                            org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(metadataSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i5));
                            String metadataKey = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String metadataValue = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue);
                        }
                    }

                    Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Properties");
                    if (propertiesSequenceElement != null) {
                        for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(propertiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i6 = i6 + 1) {
                            org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(propertiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i6));
                            String propertiesKey = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String propertiesValue = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue);
                        }
                    }
                }

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

                Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "UsageState");
                if (usageStateElement != null && usageStateElement.getTextContent() != null
                        && !usageStateElement.getTextContent().isEmpty()) {
                    WebSiteUsageState usageStateInstance;
                    usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent());
                    webSiteInstance.setUsageState(usageStateInstance);
                }

                Element webSpaceElement = XmlUtility.getElementByTagNameNS(siteElement2,
                        "http://schemas.microsoft.com/windowsazure", "WebSpace");
                if (webSpaceElement != null) {
                    String webSpaceInstance;
                    webSpaceInstance = webSpaceElement.getTextContent();
                    webSiteInstance.setWebSpace(webSpaceInstance);
                }
            }

        }
        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:org.ajax4jsf.webapp.tidy.TidyParser.java

private org.w3c.dom.Node importNode(Document document, org.w3c.dom.Node node, boolean recursive) {

    switch (node.getNodeType()) {
    case org.w3c.dom.Node.ELEMENT_NODE:
        Element element = document.createElement(node.getNodeName());

        NamedNodeMap attributes = node.getAttributes();
        if (attributes != null) {
            int length = attributes.getLength();
            for (int i = 0; i < length; i++) {
                element.setAttributeNode((Attr) importNode(document, attributes.item(i), recursive));
            }/*from  w  w w  .j av a  2 s  .c om*/
        }

        if (recursive) {
            NodeList childNodes = node.getChildNodes();
            if (childNodes != null) {
                int length = childNodes.getLength();
                for (int i = 0; i < length; i++) {
                    element.appendChild(importNode(document, childNodes.item(i), recursive));
                }
            }
        }

        return element;

    case org.w3c.dom.Node.ATTRIBUTE_NODE:
        Attr attr = document.createAttribute(node.getNodeName());
        attr.setNodeValue(node.getNodeValue());

        return attr;

    case org.w3c.dom.Node.TEXT_NODE:
        String charData = ((CharacterData) node).getData();

        return document.createTextNode(charData);

    case org.w3c.dom.Node.CDATA_SECTION_NODE:
        charData = ((CharacterData) node).getData();

        return document.createCDATASection(charData);
    case org.w3c.dom.Node.COMMENT_NODE:
        charData = ((CharacterData) node).getData();

        return document.createComment(charData);
    case org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE:
    case org.w3c.dom.Node.DOCUMENT_NODE:
    case org.w3c.dom.Node.ENTITY_NODE:
    case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
    case org.w3c.dom.Node.NOTATION_NODE:
    case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
    default:
        throw new IllegalArgumentException("Unsupported node type: " + node.getNodeType());
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

@SuppressWarnings("unchecked")
public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode,
        final Node newInstanceNode,

        final HashMap<String, String> schemaNamespaces) {
    final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode);
    prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);
    final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode);
    instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);

    for (final String prefix : schemaNamespaces.keySet()) {
        prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
        instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
    }//from w w  w  . j av a  2  s .  c  om

    // Evaluate non-recursive XPaths for all prototype elements at this level
    final Iterator<Pointer> it = prototypeContext.iteratePointers("*");
    while (it.hasNext()) {
        final Pointer p = it.next();
        Element proto = (Element) p.getNode();
        String path = p.asPath();
        // check if this is a prototype element with the attribute set
        boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")
                && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true");

        // We shouldn't locate a repeatable child with a fixed path
        if (isPrototype) {
            path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path);
            }
        }

        Document newInstanceDocument = newInstanceNode.getOwnerDocument();

        // Locate the corresponding nodes in the instance document
        List<Node> l = (List<Node>) instanceContext.selectNodes(path);

        // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node
        if (l.isEmpty()) {
            if (!isPrototype) {
                LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));

                // Clone the prototype node and all its children
                Element clone = (Element) proto.cloneNode(true);
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }
            }
        } else {
            // Otherwise, append the matches from the old instance document in order
            for (Node old : l) {
                Element oldEl = (Element) old;

                // Copy the old instance element rather than cloning it, so we don't copy over attributes
                Element clone = null;
                String nSUri = oldEl.getNamespaceURI();
                if (nSUri == null) {
                    clone = newInstanceDocument.createElement(oldEl.getTagName());
                } else {
                    clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName());
                }
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }

                // Copy over child text if this is not a complex type
                boolean isEmpty = true;
                for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) {
                    if (n instanceof Text) {
                        clone.appendChild(newInstanceDocument.importNode(n, false));
                        isEmpty = false;
                    } else if (n instanceof Element) {
                        break;
                    }
                }

                // Populate the nil attribute. It may be true or false
                if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) {
                    clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty));
                }

                // Copy over attributes present in the prototype
                NamedNodeMap attributes = proto.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attribute = (Attr) attributes.item(i);
                    String localName = attribute.getLocalName();
                    if (localName == null) {
                        String name = attribute.getName();
                        if (oldEl.hasAttribute(name)) {
                            clone.setAttributeNode(
                                    (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false));
                        } else {
                            LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                    + attribute.getNodeName() + " to "
                                    + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                            clone.setAttributeNode((Attr) attribute.cloneNode(false));
                        }
                    } else {
                        String namespace = attribute.getNamespaceURI();
                        if (!((!isEmpty
                                && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS)
                                        && localName.equals("nil"))
                                || (namespace.equals(NamespaceService.ALFRESCO_URI)
                                        && localName.equals("prototype"))))) {
                            if (oldEl.hasAttributeNS(namespace, localName)) {
                                clone.setAttributeNodeNS((Attr) newInstanceDocument
                                        .importNode(oldEl.getAttributeNodeNS(namespace, localName), false));
                            } else {
                                LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                        + attribute.getNodeName() + " to "
                                        + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                                clone.setAttributeNodeNS((Attr) attribute.cloneNode(false));
                            }
                        }
                    }
                }

                // recurse on children
                rebuildInstance(proto, oldEl, clone, schemaNamespaces);
            }
        }

        // Now add in a new copy of the prototype
        if (isPrototype) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));
            }
            newInstanceNode.appendChild(proto.cloneNode(true));
        }
    }
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java

private Attr bufferAttribute(Element element, Attribute attribute) {
    QName name = attribute.getName();
    String prefix = name.getPrefix();
    String uri = name.getNamespaceURI();
    Attr node;//ww w  .java2  s .co m
    if (uri == null || uri.isEmpty()) {
        node = document.createAttribute(name.getLocalPart());
        element.setAttributeNode(node);
    } else {
        node = document.createAttributeNS(uri, name.getLocalPart());
        if (prefix != null && !prefix.isEmpty()) {
            node.setPrefix(prefix);
        }
        element.setAttributeNodeNS(node);
    }
    node.setTextContent(attribute.getValue());
    return node;
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java

private void streamAttribute(Element element, Attribute attribute) throws XPathExpressionException {
    Attr node;//from ww w.j a  v  a2  s . c o m
    QName name = attribute.getName();
    String prefix = name.getPrefix();
    String uri = name.getNamespaceURI();
    if (uri == null || uri.isEmpty()) {
        node = document.createAttribute(name.getLocalPart());
        element.setAttributeNode(node);
    } else {
        node = document.createAttributeNS(uri, name.getLocalPart());
        if (prefix != null && !prefix.isEmpty()) {
            node.setPrefix(prefix);
        }
        element.setAttributeNodeNS(node);
    }

    String value = attribute.getValue();
    Level level = stack.peek();
    if ((level.scopeConfig) == null || (level.scopeConfig.getSelectors().isEmpty())) {
        value = filterAttribute(null, attribute.getName(), value, null);
        node.setValue(value);
    } else {
        UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath(level);
        if (path instanceof UrlRewriteFilterApplyDescriptor) {
            String rule = ((UrlRewriteFilterApplyDescriptor) path).rule();
            value = filterAttribute(null, attribute.getName(), value, rule);
            node.setValue(value);
        }
    }

    //dump( document );

    if (prefix == null || prefix.isEmpty()) {
        writer.write(" ");
        writer.write(name.getLocalPart());
    } else {
        writer.write(" ");
        writer.write(prefix);
        writer.write(":");
        writer.write(name.getLocalPart());
    }
    writer.write("=\"");
    writer.write(value);
    writer.write("\"");
    element.removeAttributeNode(node);
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter.java

private Element createElement(Document document, String name, Object bean) throws IntrospectionException,
        InvocationTargetException, NoSuchMethodException, IllegalAccessException {
    Element element = document.createElement(name);
    BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
    for (PropertyDescriptor propInfo : beanInfo.getPropertyDescriptors()) {
        String propName = propInfo.getName();
        if (propInfo.getReadMethod() != null && String.class.isAssignableFrom(propInfo.getPropertyType())) {
            String propValue = BeanUtils.getProperty(bean, propName);
            if (propValue != null && !propValue.isEmpty()) {
                // Doing it the hard way to avoid having the &'s in the query string escaped at &amp;
                Attr attr = document.createAttribute(propName);
                attr.setValue(propValue);
                element.setAttributeNode(attr);
                //element.setAttribute( propName, propValue );
            }/*from w ww.  j  a  va2s.com*/
        }
    }
    return element;
}

From source file:org.apache.ode.utils.DOMUtils.java

private static void parse(XMLStreamReader reader, Document doc, Node parent) throws XMLStreamException {
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            // create element
            Element e = doc.createElementNS(reader.getNamespaceURI(), reader.getLocalName());
            if (reader.getPrefix() != null && reader.getPrefix() != "") {
                e.setPrefix(reader.getPrefix());
            }//from w w  w .ja v a 2  s.c  o m
            parent.appendChild(e);

            // copy namespaces
            for (int ns = 0; ns < reader.getNamespaceCount(); ns++) {
                String uri = reader.getNamespaceURI(ns);
                String prefix = reader.getNamespacePrefix(ns);
                declare(e, uri, prefix);
            }

            // copy attributes
            for (int att = 0; att < reader.getAttributeCount(); att++) {
                String name = reader.getAttributeLocalName(att);
                String prefix = reader.getAttributePrefix(att);
                if (prefix != null && prefix.length() > 0) {
                    name = prefix + ":" + name;
                }
                Attr attr = doc.createAttributeNS(reader.getAttributeNamespace(att), name);
                attr.setValue(reader.getAttributeValue(att));
                e.setAttributeNode(attr);
            }
            // sub-nodes
            if (reader.hasNext()) {
                reader.next();
                parse(reader, doc, e);
            }
            if (parent instanceof Document) {
                while (reader.hasNext())
                    reader.next();
                return;
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            return;
        case XMLStreamConstants.CHARACTERS:
            if (parent != null) {
                parent.appendChild(doc.createTextNode(reader.getText()));
            }
            break;
        case XMLStreamConstants.COMMENT:
            if (parent != null) {
                parent.appendChild(doc.createComment(reader.getText()));
            }
            break;
        case XMLStreamConstants.CDATA:
            parent.appendChild(doc.createCDATASection(reader.getText()));
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            parent.appendChild(doc.createProcessingInstruction(reader.getPITarget(), reader.getPIData()));
            break;
        case XMLStreamConstants.NAMESPACE:
        case XMLStreamConstants.ATTRIBUTE:
            break;
        default:
            break;
        }

        if (reader.hasNext()) {
            event = reader.next();
        }
    }
}

From source file:org.apache.tuscany.sca.implementation.bpel.ode.TuscanyProcessConfImpl.java

/**
 * Gets the variable initializer DOM sequence for a given property, in the context of a supplied
 * DOM model of the BPEL process/*from w w w  .  ja  va  2s . co  m*/
 * @param bpelDOM - DOM representation of the BPEL process
 * @param property - SCA Property which relates to one of the variables in the BPEL process
 * @return - a DOM model representation of the XML statements required to initialize the
 * BPEL variable with the value of the SCA property.
 */
private Element getInitializerSequence(Document bpelDOM, ComponentProperty property) {
    // For an XML simple type (string, int, etc), the BPEL initializer sequence is:
    // <assign><copy><from><literal>value</literal></from><to variable="variableName"/></copy></assign>
    QName type = property.getXSDType();
    if (type != null) {
        if (mapper.isSimpleXSDType(type)) {
            // Simple types
            String NS_URI = bpelDOM.getDocumentElement().getNamespaceURI();
            String valueText = getPropertyValueText(property.getValue());
            Element literalElement = bpelDOM.createElementNS(NS_URI, "literal");
            literalElement.setTextContent(valueText);
            Element fromElement = bpelDOM.createElementNS(NS_URI, "from");
            fromElement.appendChild(literalElement);
            Element toElement = bpelDOM.createElementNS(NS_URI, "to");
            Attr variableAttribute = bpelDOM.createAttribute("variable");
            variableAttribute.setValue(property.getName());
            toElement.setAttributeNode(variableAttribute);
            Element copyElement = bpelDOM.createElementNS(NS_URI, "copy");
            copyElement.appendChild(fromElement);
            copyElement.appendChild(toElement);
            Element assignElement = bpelDOM.createElementNS(NS_URI, "assign");
            assignElement.appendChild(copyElement);
            return assignElement;
        } // end if
          // TODO Deal with Properties which have a non-simple type
    } else {
        // TODO Deal with Properties which have an element as the type
    } // end if

    return null;
}

From source file:org.apereo.portal.layout.dlm.EditManager.java

/**
   Evaluate whether attribute changes exist in the ilfChild and if so
   apply them. Returns true if some changes existed. If changes existed
   but matched those in the original node then they are not applicable,
   are removed from the editSet, and false is returned.
*//*from  w ww  . j a v  a2s  .  com*/
public static boolean applyEditSet(Element plfChild, Element original) {
    // first get edit set if it exists
    Element editSet = null;
    try {
        editSet = getEditSet(plfChild, null, null, false);
    } catch (Exception e) {
        // should never occur unless problem during create in getEditSet
        // and we are telling it not to create.
        return false;
    }

    if (editSet == null || editSet.getChildNodes().getLength() == 0)
        return false;

    if (original.getAttribute(Constants.ATT_EDIT_ALLOWED).equals("false")) {
        // can't change anymore so discard changes
        plfChild.removeChild(editSet);
        return false;
    }

    Document ilf = original.getOwnerDocument();
    boolean attributeChanged = false;
    Element edit = (Element) editSet.getFirstChild();

    while (edit != null) {
        String attribName = edit.getAttribute(Constants.ATT_NAME);
        Attr attr = plfChild.getAttributeNode(attribName);

        // preferences are only updated at preference storage time so
        // if a preference change exists in the edit set assume it is
        // still valid so that the node being edited will persist in
        // the PLF.
        if (edit.getNodeName().equals(Constants.ELM_PREF))
            attributeChanged = true;
        else if (attr == null) {
            // attribute removed. See if needs removing in original.
            attr = original.getAttributeNode(attribName);
            if (attr == null) // edit irrelevant,
                editSet.removeChild(edit);
            else {
                // edit differs, apply to original
                original.removeAttribute(attribName);
                attributeChanged = true;
            }
        } else {
            // attribute there, see if original is also there
            Attr origAttr = original.getAttributeNode(attribName);
            if (origAttr == null) {
                // original attribute isn't defined so need to add
                origAttr = (Attr) ilf.importNode(attr, true);
                original.setAttributeNode(origAttr);
                attributeChanged = true;
            } else {
                // original attrib found, see if different
                if (attr.getValue().equals(origAttr.getValue())) {
                    // they are the same, edit irrelevant
                    editSet.removeChild(edit);
                } else {
                    // edit differs, apply to original
                    origAttr.setValue(attr.getValue());
                    attributeChanged = true;
                }
            }
        }
        edit = (Element) edit.getNextSibling();
    }
    return attributeChanged;
}