Example usage for org.w3c.dom Attr getNodeName

List of usage examples for org.w3c.dom Attr getNodeName

Introduction

In this page you can find the example usage for org.w3c.dom Attr getNodeName.

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:eu.elf.license.LicenseParser.java

public static UserLicenses parseUserLicensesAsLicenseModelGroupList(String xml, String userid)
        throws Exception {
    UserLicenses userLicenses = new UserLicenses();

    try {//from  ww w  .  j av a2  s.c  o m
        Document xmlDoc = createXMLDocumentFromString(xml);

        Element ordersElement = (Element) xmlDoc
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orders").item(0);
        NodeList orderList = ordersElement.getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "order");

        for (int i = 0; i < orderList.getLength(); i++) {
            UserLicense userLicense = new UserLicense();
            try {
                Element orderElement = (Element) orderList.item(i);
                Element productionElement = (Element) orderElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "production").item(0);
                Element productionItemElement = (Element) productionElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productionItem").item(0);
                Element LicenseReferenceElement = (Element) productionItemElement
                        .getElementsByTagNameNS("http://www.52north.org/license/0.3.2", "LicenseReference")
                        .item(0);
                Element attributeStatementElement = (Element) LicenseReferenceElement
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeStatement")
                        .item(0);

                NodeList attributeElementList = attributeStatementElement
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute");

                for (int j = 0; j < attributeElementList.getLength(); j++) {
                    Element attributeElement = (Element) attributeElementList.item(j);
                    Element AttributeValueElement = (Element) attributeElement
                            .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeValue")
                            .item(0);

                    NamedNodeMap attributeMap = attributeElement.getAttributes();
                    for (int k = 0; k < attributeMap.getLength(); k++) {
                        Attr attrs = (Attr) attributeMap.item(k);
                        if ("Name".equals(attrs.getNodeName())) {

                            if ("urn:opengeospatial:ows4:geodrm:NotOnOrAfter".equals(attrs.getNodeValue())) {
                                userLicense.setValidTo(AttributeValueElement.getTextContent());
                            }
                            if ("urn:opengeospatial:ows4:geodrm:LicenseID".equals(attrs.getNodeValue())) {
                                userLicense.setLicenseId(AttributeValueElement.getTextContent());
                            }
                        }
                    }
                    userLicense.setSecureServiceURL("/httpauth/licid-" + userLicense.getLicenseId());
                }

                Element orderContentElement = (Element) orderElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orderContent").item(0);
                Element catalogElement = (Element) orderContentElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "catalog").item(0);
                NodeList productGroupElementList = catalogElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup");

                // setup user license flags in models
                List<LicenseModelGroup> list = createLicenseModelGroupList(productGroupElementList);
                for (LicenseModelGroup group : list) {
                    group.setUserLicense(true);
                }
                userLicense.setLmgList(list);

                String WSS_URL = findWssUrlFromUserLicenseParamList(userLicense.getLmgList());

                //Remove WSS from the WSS-url string
                WSS_URL = WSS_URL.substring(0, WSS_URL.lastIndexOf("/"));

                userLicense.setSecureServiceURL(WSS_URL + userLicense.getSecureServiceURL());

                userLicenses.addUserLicense(userLicense);
            } catch (Exception e) {
                // Sometimes we get results without LicenseReference element: order/production/productionItem/LicenseReference
                // there might be valid results in the same response. Skipping the invalid ones.
                LOG.warn("Error while parsing user licenses");
            }

        }

        return userLicenses;

    } catch (Exception e) {
        throw e;
    }
}

From source file:eu.elf.license.LicenseParser.java

/**
 * Creates list of license model parameters
 *
 * @param declarationListElement - XML element <x:declarationList>
 * @return List of LicenseParam objects/*from  w ww  .j  a  va2s.  c om*/
 */
private static List<LicenseParam> createLicenseModelParamList(Element declarationListElement) {
    List<LicenseParam> paramList = new ArrayList<LicenseParam>();

    // Predefined Parameters - create as LicenseParamDisplay objects
    Element predefinedParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "predefinedParameters").item(0);

    if (predefinedParametersElement != null) {
        NodeList predefinedParametersParameterElementList = predefinedParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < predefinedParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) predefinedParametersParameterElementList.item(n);

            LicenseParamDisplay displayParam = createLicenseParamDisplay(parameterElement,
                    "predefinedParameter");
            paramList.add(displayParam);

        }
    }

    // Configuration Parameters - might be LicenseParamDisplay || LicenseParamBln || LicenseParamEnum || LicenseParamInt || LicenseParamText
    Element configurationParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "configurationParameters").item(0);

    if (configurationParametersElement != null) {
        NodeList configurationParametersParameterElementList = configurationParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < configurationParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) configurationParametersParameterElementList.item(n);

            LicenseParam lp = null;
            Boolean isStringType = false;
            Boolean multiAttributeExists = false; // true for enumration type parameters
            //Boolean multiAttributeValue = false; // value of the multi attribute 
            //Boolean optionalAttribute = false;  // What does optional attribute signify???

            NamedNodeMap parameterElementAttributeMap = parameterElement.getAttributes();

            // Create appropriate subclass object based on the "type" and "multi" attributes
            for (int o = 0; o < parameterElementAttributeMap.getLength(); o++) {
                Attr attrs = (Attr) parameterElementAttributeMap.item(o);

                if (attrs.getNodeName().equals("type")) {
                    if (attrs.getNodeValue().equals("real")) {
                        lp = createLicenseParamInt(parameterElement, "configurationParameter");
                        paramList.add(lp);
                        //System.out.println("lp - name "+lpInt.getName());
                    } else if (attrs.getNodeValue().equals("string")) {
                        isStringType = true;
                    } else if (attrs.getNodeValue().equals("boolean")) {
                        lp = createLicenseParamBln(parameterElement, "configurationParameter");
                        paramList.add(lp);
                    }

                }
                if (attrs.getNodeName().equals("multi")) {
                    multiAttributeExists = true;
                    //if (attrs.getNodeValue().equals("true")) {

                    //multiAttributeValue = true;
                    //}
                    //else {
                    //multiAttributeExists = false;
                    //multiAttributeValue = false;
                    //}
                }
                // if (attrs.getNodeName().equals("optional")) {
                //    if (attrs.getNodeName().equals("true")) {
                //       optionalAttribute = true;
                //    }
                //    else {
                //       optionalAttribute = false;
                //    }
                // }

            }

            if (isStringType == true) {
                if (multiAttributeExists == true) {
                    lp = createLicenseParamEnum(parameterElement, "configurationParameter");
                    paramList.add(lp);

                    //if (optionalAttribute == true) {
                    //   
                    //    lp = createLicenseParamEnum(parameterElement, "configurationParameter");
                    //     paramList.add(lp);
                    //} 
                } else {
                    lp = createLicenseParamText(parameterElement, "configurationParameter");
                    paramList.add(lp);
                }
            }

        }
    }

    // Precalculated Parameters - create as LicenseParamDisplay objects
    Element precalculatedParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "precalculatedParameters").item(0);

    if (precalculatedParametersElement != null) {
        NodeList precalculatedParametersParameterElementList = precalculatedParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < precalculatedParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) precalculatedParametersParameterElementList.item(n);

            LicenseParamDisplay displayParam = createLicenseParamDisplay(parameterElement,
                    "precalculatedParameter");
            paramList.add(displayParam);

        }
    }

    // Result Parameters - create as LicenseParamDisplay objects
    Element resultParametersElement = (Element) declarationListElement
            .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "resultParameters").item(0);

    if (resultParametersElement != null) {
        NodeList resultParametersParameterElementList = resultParametersElement
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "parameter");

        for (int n = 0; n < resultParametersParameterElementList.getLength(); n++) {
            Element parameterElement = (Element) resultParametersParameterElementList.item(n);

            LicenseParamDisplay displayParam = createLicenseParamDisplay(parameterElement, "resultParameter");
            paramList.add(displayParam);

        }
    }

    return paramList;
}

From source file:com.gargoylesoftware.htmlunit.xml.XmlUtil.java

private static DomNode createFrom(final SgmlPage page, final Node source, final boolean handleXHTMLAsHTML) {
    if (source.getNodeType() == Node.TEXT_NODE) {
        return new DomText(page, source.getNodeValue());
    }/*from  w  w w.j a va 2s. c  o m*/
    if (source.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        return new DomProcessingInstruction(page, source.getNodeName(), source.getNodeValue());
    }
    if (source.getNodeType() == Node.COMMENT_NODE) {
        return new DomComment(page, source.getNodeValue());
    }
    if (source.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
        final DocumentType documentType = (DocumentType) source;
        return new DomDocumentType(page, documentType.getName(), documentType.getPublicId(),
                documentType.getSystemId());
    }
    final String ns = source.getNamespaceURI();
    String localName = source.getLocalName();
    if (handleXHTMLAsHTML && HTMLParser.XHTML_NAMESPACE.equals(ns)) {
        final ElementFactory factory = HTMLParser.getFactory(localName);
        return factory.createElementNS(page, ns, localName,
                namedNodeMapToSaxAttributes(source.getAttributes()));
    }
    final NamedNodeMap nodeAttributes = source.getAttributes();
    if (page != null && page.isHtmlPage()) {
        localName = localName.toUpperCase(Locale.ROOT);
    }
    final String qualifiedName;
    if (source.getPrefix() == null) {
        qualifiedName = localName;
    } else {
        qualifiedName = source.getPrefix() + ':' + localName;
    }

    final String namespaceURI = source.getNamespaceURI();
    if (HTMLParser.SVG_NAMESPACE.equals(namespaceURI)) {
        return HTMLParser.SVG_FACTORY.createElementNS(page, namespaceURI, qualifiedName,
                namedNodeMapToSaxAttributes(nodeAttributes));
    }

    final Map<String, DomAttr> attributes = new LinkedHashMap<>();
    for (int i = 0; i < nodeAttributes.getLength(); i++) {
        final Attr attribute = (Attr) nodeAttributes.item(i);
        final String attributeNamespaceURI = attribute.getNamespaceURI();
        final String attributeQualifiedName;
        if (attribute.getPrefix() != null) {
            attributeQualifiedName = attribute.getPrefix() + ':' + attribute.getLocalName();
        } else {
            attributeQualifiedName = attribute.getLocalName();
        }
        final String value = attribute.getNodeValue();
        final boolean specified = attribute.getSpecified();
        final DomAttr xmlAttribute = new DomAttr(page, attributeNamespaceURI, attributeQualifiedName, value,
                specified);
        attributes.put(attribute.getNodeName(), xmlAttribute);
    }
    return new DomElement(namespaceURI, qualifiedName, page, attributes);
}

From source file:ar.com.zauber.commons.web.transformation.sanitizing.impl.AbstractElementNodeSanitizer.java

/**
 * Recursive tree traversal//from  w  ww .ja  v  a2s  .co m
 * @param node
 * @param invalidElements
 */
private void sanitizeNode(final Node node, final List<Element> invalidElements) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        final Element element = (Element) node;
        if (!tagSecurityStrategy.isTagAllowed(element.getNodeName())) {
            invalidElements.add(element);
            return;
        } else {
            final NamedNodeMap attributes = node.getAttributes();

            if (attributes.getLength() > 0) {

                final List<Attr> invalidAttributes = new ArrayList<Attr>();

                for (int i = 0; i < attributes.getLength(); ++i) {

                    final Attr attribute = (Attr) attributes.item(i);

                    if (!tagSecurityStrategy.isAttributeAllowedForTag(attribute.getNodeName(),
                            element.getNodeName())
                            || !tagSecurityStrategy.isAttributeValueValidForTag(attribute.getNodeValue(),
                                    attribute.getNodeName(), element.getNodeName())) {

                        invalidAttributes.add(attribute);
                    }
                }
                processInvalidElementAttributes(element, invalidAttributes);
            }
        }
    }
    final NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); ++i) {
        sanitizeNode(children.item(i), invalidElements);
    }
}

From source file:DOMWriter.java

/** Writes the specified node, recursively. */
public void write(Node node) {

    // is there anything to do?
    if (node == null) {
        return;//from w  w w .j a  v  a 2  s. co m
    }

    short type = node.getNodeType();
    switch (type) {
    case Node.DOCUMENT_NODE: {
        Document document = (Document) node;
        fXML11 = "1.1".equals(getVersion(document));
        if (!fCanonical) {
            if (fXML11) {
                fOut.println("<?xml version=\"1.1\" encoding=\"UTF-8\"?>");
            } else {
                fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            }
            fOut.flush();
            write(document.getDoctype());
        }
        write(document.getDocumentElement());
        break;
    }

    case Node.DOCUMENT_TYPE_NODE: {
        DocumentType doctype = (DocumentType) node;
        fOut.print("<!DOCTYPE ");
        fOut.print(doctype.getName());
        String publicId = doctype.getPublicId();
        String systemId = doctype.getSystemId();
        if (publicId != null) {
            fOut.print(" PUBLIC '");
            fOut.print(publicId);
            fOut.print("' '");
            fOut.print(systemId);
            fOut.print('\'');
        } else if (systemId != null) {
            fOut.print(" SYSTEM '");
            fOut.print(systemId);
            fOut.print('\'');
        }
        String internalSubset = doctype.getInternalSubset();
        if (internalSubset != null) {
            fOut.println(" [");
            fOut.print(internalSubset);
            fOut.print(']');
        }
        fOut.println('>');
        break;
    }

    case Node.ELEMENT_NODE: {
        fOut.print('<');
        fOut.print(node.getNodeName());
        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            fOut.print(' ');
            fOut.print(attr.getNodeName());
            fOut.print("=\"");
            normalizeAndPrint(attr.getNodeValue(), true);
            fOut.print('"');
        }
        fOut.print('>');
        fOut.flush();

        Node child = node.getFirstChild();
        while (child != null) {
            write(child);
            child = child.getNextSibling();
        }
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: {
        if (fCanonical) {
            Node child = node.getFirstChild();
            while (child != null) {
                write(child);
                child = child.getNextSibling();
            }
        } else {
            fOut.print('&');
            fOut.print(node.getNodeName());
            fOut.print(';');
            fOut.flush();
        }
        break;
    }

    case Node.CDATA_SECTION_NODE: {
        if (fCanonical) {
            normalizeAndPrint(node.getNodeValue(), false);
        } else {
            fOut.print("<![CDATA[");
            fOut.print(node.getNodeValue());
            fOut.print("]]&gt;");
        }
        fOut.flush();
        break;
    }

    case Node.TEXT_NODE: {
        normalizeAndPrint(node.getNodeValue(), false);
        fOut.flush();
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: {
        fOut.print("<?");
        fOut.print(node.getNodeName());
        String data = node.getNodeValue();
        if (data != null && data.length() > 0) {
            fOut.print(' ');
            fOut.print(data);
        }
        fOut.print("?>");
        fOut.flush();
        break;
    }

    case Node.COMMENT_NODE: {
        if (!fCanonical) {
            fOut.print("<!--");
            String comment = node.getNodeValue();
            if (comment != null && comment.length() > 0) {
                fOut.print(comment);
            }
            fOut.print("-->");
            fOut.flush();
        }
    }
    }

    if (type == Node.ELEMENT_NODE) {
        fOut.print("</");
        fOut.print(node.getNodeName());
        fOut.print('>');
        fOut.flush();
    }

}

From source file:DOMWriter.java

private void printInternal(Node node, boolean indentEndMarker) {
    // is there anything to do?
    if (node == null) {
        return;//from www  . ja  v  a 2  s.c o m
    }

    // JBAS-2117 - Don't skip the DOCUMENT_NODE
    // if (node instanceof Document) node = ((Document)node).getDocumentElement();

    if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) {
        out.print("<?xml version='1.0'");
        if (charsetName != null)
            out.print(" encoding='" + charsetName + "'");

        out.print("?>");
        if (prettyprint)
            out.println();

        wroteXMLDeclaration = true;
    }

    int type = node.getNodeType();
    boolean hasChildNodes = node.getChildNodes().getLength() > 0;

    String nodeName = node.getNodeName();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            printInternal(children.item(iChild), false);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        Element element = (Element) node;
        if (prettyprint) {
            for (int i = 0; i < prettyIndent; i++) {
                out.print(' ');
            }
            prettyIndent++;
        }

        out.print('<');
        out.print(nodeName);

        Map nsMap = new HashMap();
        String elPrefix = node.getPrefix();
        String elNamespaceURI = node.getNamespaceURI();
        if (elPrefix != null) {
            String nsURI = getNamespaceURI(elPrefix, element, rootNode);
            nsMap.put(elPrefix, nsURI);
        }

        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            String atPrefix = attr.getPrefix();
            String atName = attr.getNodeName();
            String atValue = normalize(attr.getNodeValue(), canonical);

            if (atName.equals("xmlns"))
                currentDefaultNamespace = atValue;

            if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) {
                String nsURI = getNamespaceURI(atPrefix, element, rootNode);
                nsMap.put(atPrefix, nsURI);
                // xsi:type='ns1:SubType', xsi:type='xsd:string'
                if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) {
                    // xsi defined on the envelope
                    if (nsURI == null)
                        nsURI = getNamespaceURI(atPrefix, element, null);

                    if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) {
                        String typePrefix = atValue.substring(0, atValue.indexOf(":"));
                        String typeURI = getNamespaceURI(typePrefix, element, rootNode);
                        nsMap.put(typePrefix, typeURI);
                    }
                }
            }

            out.print(" " + atName + "='" + atValue + "'");
        }

        // Add namespace declaration for prefixes
        // that are defined further up the tree
        if (completeNamespaces) {
            Iterator itPrefix = nsMap.keySet().iterator();
            while (itPrefix.hasNext()) {
                String prefix = (String) itPrefix.next();
                String nsURI = (String) nsMap.get(prefix);
                if (nsURI == null) {
                    nsURI = getNamespaceURI(prefix, element, null);
                    out.print(" xmlns:" + prefix + "='" + nsURI + "'");
                }
            }
        }

        // The SAX ContentHandler will by default not add the namespace declaration
        // <Hello xmlns='http://somens'>World</Hello>
        if (elPrefix == null && elNamespaceURI != null) {
            String defaultNamespace = element.getAttribute("xmlns");
            if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) {
                out.print(" xmlns='" + elNamespaceURI + "'");
                currentDefaultNamespace = elNamespaceURI;
            }
        }

        if (hasChildNodes) {
            out.print('>');
        }

        // Find out if the end marker is indented
        indentEndMarker = isEndMarkerIndented(node);

        if (indentEndMarker) {
            out.print('\n');
        }

        NodeList childNodes = node.getChildNodes();
        int len = childNodes.getLength();
        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            printInternal(childNode, false);
        }
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    printInternal(children.item(i), false);
                }
            }
        } else {
            out.print('&');
            out.print(nodeName);
            out.print(';');
        }
        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        if (canonical) {
            out.print(normalize(node.getNodeValue(), canonical));
        } else {
            out.print("<![CDATA[");
            out.print(node.getNodeValue());
            out.print("]]&gt;");
        }
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        String text = normalize(node.getNodeValue(), canonical);
        if (text.trim().length() > 0) {
            out.print(text);
        } else if (prettyprint == false && ignoreWhitespace == false) {
            out.print(text);
        }
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(nodeName);
        String data = node.getNodeValue();
        if (data != null && data.length() > 0) {
            out.print(' ');
            out.print(data);
        }
        out.print("?>");
        break;
    }

    // print comment
    case Node.COMMENT_NODE: {
        for (int i = 0; i < prettyIndent; i++) {
            out.print(' ');
        }

        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");

        if (prettyprint) {
            out.print('\n');
        }

        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if (prettyprint)
            prettyIndent--;

        if (hasChildNodes == false) {
            out.print("/>");
        } else {
            if (indentEndMarker) {
                for (int i = 0; i < prettyIndent; i++) {
                    out.print(' ');
                }
            }

            out.print("</");
            out.print(nodeName);
            out.print('>');
        }

        if (prettyIndent > 0) {
            out.print('\n');
        }
    }
    out.flush();
}

From source file:DOMWriter.java

private void printInternal(Node node, boolean indentEndMarker) {
    // is there anything to do?
    if (node == null) {
        return;//from w ww  . j  ava 2 s.c o m
    }

    // JBAS-2117 - Don't skip the DOCUMENT_NODE
    // if (node instanceof Document) node =
    // ((Document)node).getDocumentElement();

    if (wroteXMLDeclaration == false && writeXMLDeclaration == true && canonical == false) {
        out.print("<?xml version='1.0'");
        if (charsetName != null)
            out.print(" encoding='" + charsetName + "'");

        out.print("?>");
        if (prettyprint)
            out.println();

        wroteXMLDeclaration = true;
    }

    int type = node.getNodeType();
    boolean hasChildNodes = node.getChildNodes().getLength() > 0;

    String nodeName = node.getNodeName();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            printInternal(children.item(iChild), false);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        Element element = (Element) node;
        if (prettyprint) {
            for (int i = 0; i < prettyIndent; i++) {
                out.print(' ');
            }
            prettyIndent++;
        }

        out.print('<');
        out.print(nodeName);

        Map nsMap = new HashMap();
        String elPrefix = node.getPrefix();
        String elNamespaceURI = node.getNamespaceURI();
        if (elPrefix != null) {
            String nsURI = getNamespaceURI(elPrefix, element, rootNode);
            nsMap.put(elPrefix, nsURI);
        }

        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            String atPrefix = attr.getPrefix();
            String atName = attr.getNodeName();
            String atValue = normalize(attr.getNodeValue(), canonical);

            if (atName.equals("xmlns"))
                currentDefaultNamespace = atValue;

            if (atPrefix != null && !atPrefix.equals("xmlns") && !atPrefix.equals("xml")) {
                String nsURI = getNamespaceURI(atPrefix, element, rootNode);
                nsMap.put(atPrefix, nsURI);
                // xsi:type='ns1:SubType', xsi:type='xsd:string'
                if (atName.equals(atPrefix + ":type") && atValue.indexOf(":") > 0) {
                    // xsi defined on the envelope
                    if (nsURI == null)
                        nsURI = getNamespaceURI(atPrefix, element, null);

                    if ("http://www.w3.org/2001/XMLSchema-instance".equals(nsURI)) {
                        String typePrefix = atValue.substring(0, atValue.indexOf(":"));
                        String typeURI = getNamespaceURI(typePrefix, element, rootNode);
                        nsMap.put(typePrefix, typeURI);
                    }
                }
            }

            out.print(" " + atName + "='" + atValue + "'");
        }

        // Add namespace declaration for prefixes
        // that are defined further up the tree
        if (completeNamespaces) {
            Iterator itPrefix = nsMap.keySet().iterator();
            while (itPrefix.hasNext()) {
                String prefix = (String) itPrefix.next();
                String nsURI = (String) nsMap.get(prefix);
                if (nsURI == null) {
                    nsURI = getNamespaceURI(prefix, element, null);
                    out.print(" xmlns:" + prefix + "='" + nsURI + "'");
                }
            }
        }

        // The SAX ContentHandler will by default not add the namespace
        // declaration
        // <Hello xmlns='http://somens'>World</Hello>
        if (elPrefix == null && elNamespaceURI != null) {
            String defaultNamespace = element.getAttribute("xmlns");
            if (defaultNamespace.length() == 0 && !elNamespaceURI.equals(currentDefaultNamespace)) {
                out.print(" xmlns='" + elNamespaceURI + "'");
                currentDefaultNamespace = elNamespaceURI;
            }
        }

        if (hasChildNodes) {
            out.print('>');
        }

        // Find out if the end marker is indented
        indentEndMarker = isEndMarkerIndented(node);

        if (indentEndMarker) {
            out.print('\n');
        }

        NodeList childNodes = node.getChildNodes();
        int len = childNodes.getLength();
        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            printInternal(childNode, false);
        }
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    printInternal(children.item(i), false);
                }
            }
        } else {
            out.print('&');
            out.print(nodeName);
            out.print(';');
        }
        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        if (canonical) {
            out.print(normalize(node.getNodeValue(), canonical));
        } else {
            out.print("<![CDATA[");
            out.print(node.getNodeValue());
            out.print("]]&gt;");
        }
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        String text = normalize(node.getNodeValue(), canonical);
        if (text.trim().length() > 0) {
            out.print(text);
        } else if (prettyprint == false && ignoreWhitespace == false) {
            out.print(text);
        }
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(nodeName);
        String data = node.getNodeValue();
        if (data != null && data.length() > 0) {
            out.print(' ');
            out.print(data);
        }
        out.print("?>");
        break;
    }

    // print comment
    case Node.COMMENT_NODE: {
        for (int i = 0; i < prettyIndent; i++) {
            out.print(' ');
        }

        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");

        if (prettyprint) {
            out.print('\n');
        }

        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if (prettyprint)
            prettyIndent--;

        if (hasChildNodes == false) {
            out.print("/>");
        } else {
            if (indentEndMarker) {
                for (int i = 0; i < prettyIndent; i++) {
                    out.print(' ');
                }
            }

            out.print("</");
            out.print(nodeName);
            out.print('>');
        }

        if (prettyIndent > 0) {
            out.print('\n');
        }
    }
    out.flush();
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

public static final List<Element> createEntityFromBusinessObject(final BusinessEntity businessEntity)
        throws Exception {

    /* Create list of elements */
    final List<Element> elementList = new ArrayList<Element>();

    if (businessEntity != null) {
        final Node node = businessEntity.getDomNode();
        if (node.hasChildNodes()) {
            final NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {

                /* To avoid : 'DOM Level 3 Not implemented' error */
                final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                final Document document = builder.newDocument();
                final Element element = (Element) document.importNode(nodeList.item(i), true);

                if (element.getNodeName() != null && element.getNodeName().contains(":")) {
                    final String nodeName = element.getNodeName().split(":")[1];

                    /* Check for attributes */
                    final NamedNodeMap attributes = element.getAttributes();

                    if (attributes != null && attributes.getLength() != 0) {

                        /* Create new map for attributes */
                        final Map<String, String> attributeMap = new HashMap<String, String>();

                        for (int j = 0; j < attributes.getLength(); j++) {
                            final Attr attr = (Attr) attributes.item(j);

                            /* Set node name and value in map */
                            attributeMap.put(attr.getNodeName(), attr.getNodeValue());
                        }// w w  w . j a  va2s . co  m

                        /* Create node with attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent(), attributeMap));
                    } else {

                        /* Create node without attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent()));
                    }
                }
            }
        }
        return elementList;
    } else {
        return null;
    }
}

From source file:com.nridge.core.base.io.xml.DataTableXML.java

/**
 * Parses an XML DOM element and loads it into a bag/table.
 *
 * @param anElement DOM element.//from  w  ww .j a  va2 s. c o  m
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    Attr nodeAttr;
    Element nodeElement;
    String nodeName, nodeValue, attrValue;

    attrValue = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(attrValue))
        mDataTable.setName(attrValue);

    NamedNodeMap namedNodeMap = anElement.getAttributes();
    int attrCount = namedNodeMap.getLength();
    for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
        nodeAttr = (Attr) namedNodeMap.item(attrOffset);
        nodeName = nodeAttr.getNodeName();
        nodeValue = nodeAttr.getNodeValue();

        if (StringUtils.isNotEmpty(nodeValue)) {
            if (!StringUtils.equalsIgnoreCase(nodeName, "name"))
                mDataTable.addFeature(nodeName, nodeValue);
        }
    }

    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase("Context")) {
            nodeElement = (Element) nodeItem;
            attrValue = nodeElement.getAttribute("start");
            if (StringUtils.isNumeric(attrValue))
                mContextStart = Integer.parseInt(attrValue);
            attrValue = nodeElement.getAttribute("limit");
            if (StringUtils.isNumeric(attrValue))
                mContextLimit = Integer.parseInt(attrValue);
            attrValue = nodeElement.getAttribute("total");
            if (StringUtils.isNumeric(attrValue))
                mContextTotal = Integer.parseInt(attrValue);
        } else if (nodeName.equalsIgnoreCase("Columns")) {
            nodeElement = (Element) nodeItem;
            DataBagXML dataBagXML = new DataBagXML();
            dataBagXML.load(nodeElement);
            DataBag dataBag = dataBagXML.getBag();
            dataBag.setName(mDataTable.getName());
            mDataTable = new DataTable(dataBag);
        } else if (nodeName.equalsIgnoreCase("Rows")) {
            nodeElement = (Element) nodeItem;
            loadRows(nodeElement);
        }
    }
}

From source file:com.nridge.core.base.io.xml.RelationshipXML.java

/**
 * Parses an XML DOM element and loads it into a relationship.
 *
 * @param anElement DOM element./*  ww  w  . ja  v  a  2  s  .  c  om*/
 *
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    Attr nodeAttr;
    Element nodeElement;
    DataBagXML dataBagXML;
    DocumentXML documentXML;
    String nodeName, nodeValue;

    mRelationship.reset();
    String attrValue = anElement.getAttribute("type");
    if (StringUtils.isEmpty(attrValue))
        throw new IOException("Relationship is missing type attribute.");
    mRelationship.setType(attrValue);

    NamedNodeMap namedNodeMap = anElement.getAttributes();
    int attrCount = namedNodeMap.getLength();
    for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
        nodeAttr = (Attr) namedNodeMap.item(attrOffset);
        nodeName = nodeAttr.getNodeName();
        nodeValue = nodeAttr.getNodeValue();

        if (StringUtils.isNotEmpty(nodeValue)) {
            if ((!StringUtils.equalsIgnoreCase(nodeName, "type")))
                mRelationship.addFeature(nodeName, nodeValue);
        }
    }
    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase(IO.XML_PROPERTIES_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            dataBagXML = new DataBagXML();
            dataBagXML.load(nodeElement);
            mRelationship.setBag(dataBagXML.getBag());
        } else {
            nodeElement = (Element) nodeItem;
            documentXML = new DocumentXML();
            documentXML.load(nodeElement);
            mRelationship.add(documentXML.getDocument());
        }
    }
}