Example usage for org.w3c.dom Document createAttribute

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

Introduction

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

Prototype

public Attr createAttribute(String name) throws DOMException;

Source Link

Document

Creates an Attr of the given name.

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)/*  ww w  .j  a  va2 s . co m*/
*
* @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.amalto.core.storage.hibernate.DefaultStorageClassLoader.java

public Document generateHibernateConfiguration(RDBMSDataSource rdbmsDataSource)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*  ww w.j a v  a2s .com*/
    factory.setExpandEntityReferences(false);

    DocumentBuilder documentBuilder = factory.newDocumentBuilder();
    documentBuilder.setEntityResolver(HibernateStorage.ENTITY_RESOLVER);
    Document document = documentBuilder
            .parse(DefaultStorageClassLoader.class.getResourceAsStream(HIBERNATE_CONFIG_TEMPLATE));
    String connectionUrl = rdbmsDataSource.getConnectionURL();
    String userName = rdbmsDataSource.getUserName();
    String driverClass = rdbmsDataSource.getDriverClassName();
    RDBMSDataSource.DataSourceDialect dialectType = rdbmsDataSource.getDialectName();
    String dialect = getDialect(dialectType);
    String password = rdbmsDataSource.getPassword();
    String indexBase = rdbmsDataSource.getIndexDirectory();
    int connectionPoolMinSize = rdbmsDataSource.getConnectionPoolMinSize();
    int connectionPoolMaxSize = rdbmsDataSource.getConnectionPoolMaxSize();
    if (connectionPoolMaxSize == 0) {
        LOGGER.info("No value provided for property connectionPoolMaxSize of datasource " //$NON-NLS-1$
                + rdbmsDataSource.getName() + ". Using default value: " //$NON-NLS-1$
                + RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT);
        connectionPoolMaxSize = RDBMSDataSourceBuilder.CONNECTION_POOL_MAX_SIZE_DEFAULT;
    }

    setPropertyValue(document, "hibernate.connection.url", connectionUrl); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.connection.username", userName); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.connection.driver_class", driverClass); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dialect", dialect); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.connection.password", password); //$NON-NLS-1$
    // Sets up DBCP pool features
    setPropertyValue(document, "hibernate.dbcp.initialSize", String.valueOf(connectionPoolMinSize)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxActive", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxIdle", String.valueOf(10)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxTotal", String.valueOf(connectionPoolMaxSize)); //$NON-NLS-1$
    setPropertyValue(document, "hibernate.dbcp.maxWaitMillis", "60000"); //$NON-NLS-1$ //$NON-NLS-2$

    Node sessionFactoryElement = document.getElementsByTagName("session-factory").item(0); //$NON-NLS-1$
    if (rdbmsDataSource.supportFullText()) {
        /*
        <property name="hibernate.search.default.directory_provider" value="filesystem"/>
        <property name="hibernate.search.default.indexBase" value="/var/lucene/indexes"/>
         */
        addProperty(document, sessionFactoryElement, "hibernate.search.default.directory_provider", //$NON-NLS-1$
                "filesystem"); //$NON-NLS-1$
        addProperty(document, sessionFactoryElement, "hibernate.search.default.indexBase", //$NON-NLS-1$
                indexBase + '/' + storageName);
        addProperty(document, sessionFactoryElement, "hibernate.search.default.sourceBase", //$NON-NLS-1$
                indexBase + '/' + storageName);
        addProperty(document, sessionFactoryElement, "hibernate.search.default.source", ""); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "hibernate.search.default.exclusive_index_use", "false"); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "hibernate.search.lucene_version", "LUCENE_CURRENT"); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        addProperty(document, sessionFactoryElement, "hibernate.search.autoregister_listeners", "false"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (dataSource.getCacheDirectory() != null && !dataSource.getCacheDirectory().isEmpty()) {
        /*
        <!-- Second level cache -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
        <property name="hibernate.cache.use_query_cache">true</property>
        <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
         */
        addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "hibernate.cache.provider_class", //$NON-NLS-1$
                "net.sf.ehcache.hibernate.EhCacheProvider"); //$NON-NLS-1$
        addProperty(document, sessionFactoryElement, "hibernate.cache.use_query_cache", "true"); //$NON-NLS-1$ //$NON-NLS-2$
        addProperty(document, sessionFactoryElement, "net.sf.ehcache.configurationResourceName", "ehcache.xml"); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(
                    "Hibernate configuration does not define second level cache extensions due to datasource configuration."); //$NON-NLS-1$
        }
        addProperty(document, sessionFactoryElement, "hibernate.cache.use_second_level_cache", "false"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    // Override default configuration with values from configuration
    Map<String, String> advancedProperties = rdbmsDataSource.getAdvancedProperties();
    for (Map.Entry<String, String> currentAdvancedProperty : advancedProperties.entrySet()) {
        setPropertyValue(document, currentAdvancedProperty.getKey(), currentAdvancedProperty.getValue());
    }
    // Order of elements highly matters and mapping shall be declared after <property/> and before <event/>.
    Element mapping = document.createElement("mapping"); //$NON-NLS-1$
    Attr resource = document.createAttribute("resource"); //$NON-NLS-1$
    resource.setValue(HIBERNATE_MAPPING);
    mapping.getAttributes().setNamedItem(resource);
    sessionFactoryElement.appendChild(mapping);

    if (rdbmsDataSource.supportFullText()) {
        addEvent(document, sessionFactoryElement, "post-update", //$NON-NLS-1$
                "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$
        addEvent(document, sessionFactoryElement, "post-insert", //$NON-NLS-1$
                "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$
        addEvent(document, sessionFactoryElement, "post-delete", //$NON-NLS-1$
                "org.hibernate.search.event.FullTextIndexEventListener"); //$NON-NLS-1$
    } else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Hibernate configuration does not define full text extensions due to datasource configuration."); //$NON-NLS-1$
    }

    return document;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * Action categories are defined on the Main class by implementing the PushActionsProvider, however
 * the main class may not be available to the push receiver, so we need to save these categories
 * to the file system when the app is installed, then the push receiver can load these actions
 * when it sends a push while the app isn't running.
 * @param provider A reference to the App's main class 
 * @throws IOException /*from   w  w w  . java 2  s  . c om*/
 */
public static void installNotificationActionCategories(PushActionsProvider provider) throws IOException {
    // Assume that CN1 is running... this will run when the app starts
    // up
    Context context = getContext();
    boolean requiresUpdate = false;

    File categoriesFile = new File(
            activity.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
    if (!categoriesFile.exists()) {
        requiresUpdate = true;
    }
    if (!requiresUpdate) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                    context.getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
            if (packageInfo.lastUpdateTime > categoriesFile.lastModified()) {
                requiresUpdate = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    if (!requiresUpdate) {
        return;
    }

    OutputStream os = getContext().openFileOutput(FILE_NAME_NOTIFICATION_CATEGORIES, 0);
    PushActionCategory[] categories = provider.getPushActionCategories();
    javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory
            .newInstance();
    javax.xml.parsers.DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException(
                "Faield to create document builder for creating notification categories XML document", ex);
    }

    // root elements
    org.w3c.dom.Document doc = docBuilder.newDocument();
    org.w3c.dom.Element root = (org.w3c.dom.Element) doc.createElement("categories");
    doc.appendChild(root);
    for (PushActionCategory category : categories) {
        org.w3c.dom.Element categoryEl = (org.w3c.dom.Element) doc.createElement("category");
        org.w3c.dom.Attr idAttr = doc.createAttribute("id");
        idAttr.setValue(category.getId());
        categoryEl.setAttributeNode(idAttr);

        for (PushAction action : category.getActions()) {
            org.w3c.dom.Element actionEl = (org.w3c.dom.Element) doc.createElement("action");
            org.w3c.dom.Attr actionIdAttr = doc.createAttribute("id");
            actionIdAttr.setValue(action.getId());
            actionEl.setAttributeNode(actionIdAttr);

            org.w3c.dom.Attr actionTitleAttr = doc.createAttribute("title");
            if (action.getTitle() != null) {
                actionTitleAttr.setValue(action.getTitle());
            } else {
                actionTitleAttr.setValue(action.getId());
            }
            actionEl.setAttributeNode(actionTitleAttr);

            if (action.getIcon() != null) {
                org.w3c.dom.Attr actionIconAttr = doc.createAttribute("icon");
                String iconVal = action.getIcon();
                try {
                    // We'll store the resource IDs for the icon
                    // rather than the icon name because that is what
                    // the push notifications require.
                    iconVal = "" + context.getResources().getIdentifier(iconVal, "drawable",
                            context.getPackageName());
                    actionIconAttr.setValue(iconVal);
                    actionEl.setAttributeNode(actionIconAttr);
                } catch (Exception ex) {
                    ex.printStackTrace();

                }

            }

            if (action.getTextInputPlaceholder() != null) {
                org.w3c.dom.Attr textInputPlaceholderAttr = doc.createAttribute("textInputPlaceholder");
                textInputPlaceholderAttr.setValue(action.getTextInputPlaceholder());
                actionEl.setAttributeNode(textInputPlaceholderAttr);
            }
            if (action.getTextInputButtonText() != null) {
                org.w3c.dom.Attr textInputButtonTextAttr = doc.createAttribute("textInputButtonText");
                textInputButtonTextAttr.setValue(action.getTextInputButtonText());
                actionEl.setAttributeNode(textInputButtonTextAttr);
            }
            categoryEl.appendChild(actionEl);
        }
        root.appendChild(categoryEl);

    }
    try {
        javax.xml.transform.TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory
                .newInstance();
        javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
        javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
        javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
        transformer.transform(source, result);

    } catch (Exception ex) {
        throw new IOException("Failed to save notification categories as XML.", ex);
    }

}

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));
            }//  ww  w . j  a  v a 2 s . c o m
        }

        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.alternativevision.gpx.GPXParser.java

private void addGenericWaypointToGPXNode(String tagName, Waypoint wpt, Node gpxNode, Document doc) {
    Node wptNode = doc.createElement(tagName);
    NamedNodeMap attrs = wptNode.getAttributes();
    if (wpt.getLatitude() != null) {
        Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR);
        latNode.setNodeValue(wpt.getLatitude().toString());
        attrs.setNamedItem(latNode);/*from w ww .  j av a 2  s. c  om*/
    }
    if (wpt.getLongitude() != null) {
        Node longNode = doc.createAttribute(GPXConstants.LON_ATTR);
        longNode.setNodeValue(wpt.getLongitude().toString());
        attrs.setNamedItem(longNode);
    }
    if (wpt.getElevation() != null) {
        Node node = doc.createElement(GPXConstants.ELE_NODE);
        node.appendChild(doc.createTextNode(wpt.getElevation().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getTime() != null) {
        Node node = doc.createElement(GPXConstants.TIME_NODE);
        node.appendChild(doc.createTextNode(sdfZ.format(wpt.getTime())));
        wptNode.appendChild(node);
    }
    if (wpt.getMagneticDeclination() != null) {
        Node node = doc.createElement(GPXConstants.MAGVAR_NODE);
        node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getGeoidHeight() != null) {
        Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE);
        node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getName() != null) {
        Node node = doc.createElement(GPXConstants.NAME_NODE);
        node.appendChild(doc.createTextNode(wpt.getName()));
        wptNode.appendChild(node);
    }
    if (wpt.getComment() != null) {
        Node node = doc.createElement(GPXConstants.CMT_NODE);
        node.appendChild(doc.createTextNode(wpt.getComment()));
        wptNode.appendChild(node);
    }
    if (wpt.getDescription() != null) {
        Node node = doc.createElement(GPXConstants.DESC_NODE);
        node.appendChild(doc.createTextNode(wpt.getDescription()));
        wptNode.appendChild(node);
    }
    if (wpt.getSrc() != null) {
        Node node = doc.createElement(GPXConstants.SRC_NODE);
        node.appendChild(doc.createTextNode(wpt.getSrc()));
        wptNode.appendChild(node);
    }
    //TODO: write link node
    if (wpt.getSym() != null) {
        Node node = doc.createElement(GPXConstants.SYM_NODE);
        node.appendChild(doc.createTextNode(wpt.getSym()));
        wptNode.appendChild(node);
    }
    if (wpt.getType() != null) {
        Node node = doc.createElement(GPXConstants.TYPE_NODE);
        node.appendChild(doc.createTextNode(wpt.getType()));
        wptNode.appendChild(node);
    }
    if (wpt.getFix() != null) {
        Node node = doc.createElement(GPXConstants.FIX_NODE);
        node.appendChild(doc.createTextNode(wpt.getFix().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getSat() != null) {
        Node node = doc.createElement(GPXConstants.SAT_NODE);
        node.appendChild(doc.createTextNode(wpt.getSat().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getHdop() != null) {
        Node node = doc.createElement(GPXConstants.HDOP_NODE);
        node.appendChild(doc.createTextNode(wpt.getHdop().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getVdop() != null) {
        Node node = doc.createElement(GPXConstants.VDOP_NODE);
        node.appendChild(doc.createTextNode(wpt.getVdop().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getPdop() != null) {
        Node node = doc.createElement(GPXConstants.PDOP_NODE);
        node.appendChild(doc.createTextNode(wpt.getPdop().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getAgeOfGPSData() != null) {
        Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE);
        node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getDgpsid() != null) {
        Node node = doc.createElement(GPXConstants.DGPSID_NODE);
        node.appendChild(doc.createTextNode(wpt.getDgpsid().toString()));
        wptNode.appendChild(node);
    }
    if (wpt.getExtensionsParsed() > 0) {
        Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
        Iterator<IExtensionParser> it = extensionParsers.iterator();
        while (it.hasNext()) {
            it.next().writeWaypointExtensionData(node, wpt, doc);
        }
        wptNode.appendChild(node);
    }
    gpxNode.appendChild(wptNode);
}

From source file:org.alternativevision.gpx.GPXParser.java

private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) {
    NamedNodeMap attrs = gpxNode.getAttributes();
    if (gpx.getVersion() != null) {
        Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR);
        verNode.setNodeValue(gpx.getVersion());
        attrs.setNamedItem(verNode);//  w  w  w .  jav  a2s .  c  o m
    }
    if (gpx.getCreator() != null) {
        Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR);
        creatorNode.setNodeValue(gpx.getCreator());
        attrs.setNamedItem(creatorNode);
    }

    if (gpx.getExtensionsParsed() > 0) {
        Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
        Iterator<IExtensionParser> it = extensionParsers.iterator();
        while (it.hasNext()) {
            it.next().writeGPXExtensionData(node, gpx, doc);
        }
        gpxNode.appendChild(node);
    }
}

From source file:org.apache.axis.message.NodeImpl.java

/**
 * The internal representation of Attributes cannot help being changed
 * It is because Attribute is not immutible Type, so if we keep out value and
 * just return it in another form, the application may chnae it, which we cannot
 * detect without some kind back track method (call back notifying the chnage.)
 * I am not sure which approach is better.
 *//*from   w  w w  . java2 s .  c  om*/
protected NamedNodeMap convertAttrSAXtoDOM(Attributes saxAttr) {
    try {
        org.w3c.dom.Document doc = org.apache.axis.utils.XMLUtils.newDocument();
        AttributesImpl saxAttrs = (AttributesImpl) saxAttr;
        NamedNodeMap domAttributes = new NamedNodeMapImpl();
        for (int i = 0; i < saxAttrs.getLength(); i++) {
            String uri = saxAttrs.getURI(i);
            String qname = saxAttrs.getQName(i);
            String value = saxAttrs.getValue(i);
            if (uri != null && uri.trim().length() > 0) {
                // filterring out the tricky method to differentiate the null namespace
                // -ware case
                if (NULL_URI_NAME.equals(uri)) {
                    uri = null;
                }
                Attr attr = doc.createAttributeNS(uri, qname);
                attr.setValue(value);
                domAttributes.setNamedItemNS(attr);
            } else {
                Attr attr = doc.createAttribute(qname);
                attr.setValue(value);
                domAttributes.setNamedItem(attr);
            }
        }
        return domAttributes;
    } catch (Exception ex) {
        log.error(Messages.getMessage("saxToDomFailed00"), ex);

        return null;
    }
}

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 );
            }//w w w  . j a va2 s  .  co m
        }
    }
    return element;
}

From source file:org.apache.nutch.searcher.response.xml.XMLResponseWriter.java

/**
 * Adds an attribute name and value to a node Element in the XML document.
 * /*from   w w  w  .  ja  v a 2s .  c o m*/
 * @param doc The XML document.
 * @param node The node Element on which to attach the attribute.
 * @param name The name of the attribute.
 * @param value The value of the attribute.
 */
private static void addAttribute(Document doc, Element node, String name, String value) {
    Attr attribute = doc.createAttribute(name);
    attribute.setValue(getLegalXml(value));
    node.getAttributes().setNamedItem(attribute);
}

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

/**
 * Deep clone, but don't fry, the given node in the context of the given document.
 * For all intents and purposes, the clone is the exact same copy of the node,
 * except that it might have a different owner document.
 *
 * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
 * in that it doesn't assume that the given node has a parent or a owner document.
 *
 * @param document/* w  w w . j a v a2s.com*/
 * @param sourceNode
 * @return a clone of node
 */
public static Node cloneNode(Document document, Node sourceNode) {
    Node clonedNode = null;

    // what is my name?
    QName sourceQName = getNodeQName(sourceNode);
    String nodeName = sourceQName.getLocalPart();
    String namespaceURI = sourceQName.getNamespaceURI();

    // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
    if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
        namespaceURI = null;
    }

    switch (sourceNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        if (namespaceURI == null) {
            clonedNode = document.createAttribute(nodeName);
        } else {
            String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
            // the prefix for the XML namespace can't be looked up, hence this...
            if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
                prefix = "xmlns";
            }
            // if a prefix exists, qualify the name with it
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
            }
            // create the appropriate type of attribute
            if (prefix != null) {
                clonedNode = document.createAttributeNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createAttribute(nodeName);
            }
        }
        break;
    case Node.CDATA_SECTION_NODE:
        clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
        break;
    case Node.COMMENT_NODE:
        clonedNode = document.createComment(((Comment) sourceNode).getData());
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        clonedNode = document.createDocumentFragment();
        break;
    case Node.DOCUMENT_NODE:
        clonedNode = document;
        break;
    case Node.ELEMENT_NODE:
        // create the appropriate type of element
        if (namespaceURI == null) {
            clonedNode = document.createElement(nodeName);
        } else {
            String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns"
                    : ((Element) sourceNode).lookupPrefix(namespaceURI);
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
                clonedNode = document.createElementNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createElement(nodeName);
            }
        }
        // attributes are not treated as child nodes, so copy them explicitly
        NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
            if (attributeClone.getNamespaceURI() == null) {
                ((Element) clonedNode).setAttributeNode(attributeClone);
            } else {
                ((Element) clonedNode).setAttributeNodeNS(attributeClone);
            }
        }
        break;
    case Node.ENTITY_NODE:
        // TODO
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clonedNode = document.createEntityReference(nodeName);
        // TODO
        break;
    case Node.NOTATION_NODE:
        // TODO
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(),
                nodeName);
        break;
    case Node.TEXT_NODE:
        clonedNode = document.createTextNode(((Text) sourceNode).getData());
        break;
    default:
        break;
    }

    // clone children of element and attribute nodes
    NodeList sourceChildren = sourceNode.getChildNodes();
    if (sourceChildren != null) {
        for (int i = 0; i < sourceChildren.getLength(); i++) {
            Node sourceChild = sourceChildren.item(i);
            Node clonedChild = cloneNode(document, sourceChild);
            clonedNode.appendChild(clonedChild);
            // if the child has a textual value, parse it for any embedded prefixes
            if (clonedChild.getNodeType() == Node.TEXT_NODE
                    || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
                parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
            }
        }
    }
    return clonedNode;
}