Example usage for org.w3c.dom Node getNamespaceURI

List of usage examples for org.w3c.dom Node getNamespaceURI

Introduction

In this page you can find the example usage for org.w3c.dom Node getNamespaceURI.

Prototype

public String getNamespaceURI();

Source Link

Document

The namespace URI of this node, or null if it is unspecified (see ).

Usage

From source file:Main.java

/**
 * Access an immediate child element inside the given Element
 *
 * @param element the starting element, cannot be null.
 * @param namespaceURI name space of the child element to look for,
 * cannot be null. Use "*" to match all namespaces.
 * @param elemName the name of the child element to look for, cannot be
 * null./*from  w  w  w  .  j a v a2 s . c o  m*/
 * @return the first immediate child element inside element, or
 * <code>null</code> if the child element is not found.
 */
public static Element getChildElement(Element element, String namespaceURI, String elemName) {
    NodeList list = element.getChildNodes();
    int len = list.getLength();

    for (int i = 0; i < len; i++) {
        Node n = list.item(i);

        if (n.getNodeType() == Node.ELEMENT_NODE) {
            if (elemName.equals(n.getLocalName())
                    && ("*".equals(namespaceURI) || namespaceURI.equals(n.getNamespaceURI()))) {
                return (Element) n;
            }
        }
    }
    return null;
}

From source file:be.fedict.eid.dss.spi.utils.XAdESSigAndRefsTimeStampValidation.java

public static List<TimeStampToken> verify(XAdESTimeStampType sigAndRefsTimeStamp, Element signatureElement)
        throws XAdESValidationException {

    LOG.debug("validate SigAndRefsTimeStamp...");

    List<TimeStampToken> timeStampTokens = XAdESUtils.getTimeStampTokens(sigAndRefsTimeStamp);
    if (timeStampTokens.isEmpty()) {
        LOG.error("No timestamp tokens present in SigAndRefsTimeStamp");
        throw new XAdESValidationException("No timestamp tokens present in SigAndRefsTimeStamp");
    }/* www .  j a v  a 2s.  c  o  m*/

    TimeStampDigestInput digestInput = new TimeStampDigestInput(
            sigAndRefsTimeStamp.getCanonicalizationMethod().getAlgorithm());

    /*
     * 2. check ds:SignatureValue present 3. take ds:SignatureValue,
     * cannonicalize and concatenate bytes.
     */
    NodeList signatureValueNodeList = signatureElement.getElementsByTagNameNS(XMLSignature.XMLNS,
            "SignatureValue");
    if (0 == signatureValueNodeList.getLength()) {
        LOG.error("no XML signature valuefound");
        throw new XAdESValidationException("no XML signature valuefound");
    }
    digestInput.addNode(signatureValueNodeList.item(0));

    /*
     * 4. check SignatureTimeStamp(s), CompleteCertificateRefs,
     * CompleteRevocationRefs, AttributeCertificateRefs,
     * AttributeRevocationRefs 5. canonicalize these and concatenate to
     * bytestream from step 3 These nodes should be added in their order of
     * appearance.
     */

    NodeList unsignedSignaturePropertiesNodeList = signatureElement
            .getElementsByTagNameNS(XAdESUtils.XADES_132_NS_URI, "UnsignedSignatureProperties");
    if (unsignedSignaturePropertiesNodeList.getLength() == 0) {
        throw new XAdESValidationException("UnsignedSignatureProperties node not present");
    }
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    NodeList childNodes = unsignedSignaturePropertiesNode.getChildNodes();
    int childNodesCount = childNodes.getLength();
    for (int idx = 0; idx < childNodesCount; idx++) {
        Node childNode = childNodes.item(idx);
        if (Node.ELEMENT_NODE != childNode.getNodeType()) {
            continue;
        }
        if (!XAdESUtils.XADES_132_NS_URI.equals(childNode.getNamespaceURI())) {
            continue;
        }
        String localName = childNode.getLocalName();
        if ("SignatureTimeStamp".equals(localName)) {
            digestInput.addNode(childNode);
            continue;
        }
        if ("CompleteCertificateRefs".equals(localName)) {
            digestInput.addNode(childNode);
            continue;
        }
        if ("CompleteRevocationRefs".equals(localName)) {
            digestInput.addNode(childNode);
            continue;
        }
        if ("AttributeCertificateRefs".equals(localName)) {
            digestInput.addNode(childNode);
            continue;
        }
        if ("AttributeRevocationRefs".equals(localName)) {
            digestInput.addNode(childNode);
            continue;
        }
    }

    for (TimeStampToken timeStampToken : timeStampTokens) {

        // 1. verify signature in timestamp token
        XAdESUtils.verifyTimeStampTokenSignature(timeStampToken);

        // 6. compute digest and compare with token
        XAdESUtils.verifyTimeStampTokenDigest(timeStampToken, digestInput);
    }

    return timeStampTokens;
}

From source file:Main.java

public static void spreadNamespaces(Node node, String tns, boolean overwrite) {
    Document doc = node instanceof Document ? (Document) node : node.getOwnerDocument();
    boolean isParent = false;
    while (node != null) {
        Node next = null;//  w w w.  j  a  v  a 2s .c  om
        if (!isParent && node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getNamespaceURI() == null) {
                node = doc.renameNode(node, tns, node.getNodeName());
            } else {
                if (overwrite) {
                    tns = node.getNamespaceURI();
                }
            }
            NamedNodeMap nodeMap = node.getAttributes();
            int nodeMapLengthl = nodeMap.getLength();
            for (int i = 0; i < nodeMapLengthl; i++) {
                Node attr = nodeMap.item(i);
                if (attr.getNamespaceURI() == null) {
                    doc.renameNode(attr, tns, attr.getNodeName());
                }
            }
        }
        isParent = (isParent || (next = node.getFirstChild()) == null)
                && (next = node.getNextSibling()) == null;
        node = isParent ? node.getParentNode() : next;
        if (isParent && node != null) {
            if (overwrite) {
                tns = node.getNamespaceURI();
            }
        }
    }
}

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

private static Attributes namedNodeMapToSaxAttributes(final NamedNodeMap attributesMap) {
    final AttributesImpl attributes = new AttributesImpl();
    final int length = attributesMap.getLength();
    for (int i = 0; i < length; i++) {
        final Node attr = attributesMap.item(i);
        attributes.addAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getNodeName(), null,
                attr.getNodeValue());//from  w  w w .j  ava2s.  c  om
    }

    return attributes;
}

From source file:Main.java

private static void collectCDATASections(Node node, Set<String> cdataQNames) {
    if (node instanceof CDATASection) {
        Node parent = node.getParentNode();
        if (parent != null) {
            String uri = parent.getNamespaceURI();
            if (uri != null) {
                cdataQNames.add("{" + uri + "}" + parent.getNodeName()); //NOI18N
            } else {
                cdataQNames.add(parent.getNodeName());
            }/*  ww w.jav a  2s  .com*/
        }
    }

    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        collectCDATASections(children.item(i), cdataQNames);
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.OAuthTests.java

public static Collection<Object[]> getReferencedUrls(ArrayList<Node> capabilityDOMNodesUsingXML, String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    //ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    String requestTokenUri = "";
    String authorizationUri = "";
    String accessTokenUri = "";
    for (Node node : capabilityDOMNodesUsingXML) {
        NodeList oAuthChildren = node.getChildNodes();
        requestTokenUri = null;//from w  w w  . j  a  v  a 2 s  . co m
        authorizationUri = null;
        accessTokenUri = null;
        for (int j = 0; j < oAuthChildren.getLength(); j++) {
            Node oAuthNode = oAuthChildren.item(j);
            if (oAuthNode.getLocalName() == null)
                continue;
            NamedNodeMap attribs = oAuthNode.getAttributes();
            if (oAuthNode.getNamespaceURI().equals(OSLCConstants.OSLC_V2)) {
                if (oAuthNode.getLocalName().equals("oauthRequestTokenURI")) {
                    requestTokenUri = attribs.getNamedItemNS(OSLCConstants.RDF, "resource").getNodeValue();
                } else if (oAuthNode.getLocalName().equals("authorizationURI")) {
                    authorizationUri = attribs.getNamedItemNS(OSLCConstants.RDF, "resource").getNodeValue();
                } else if (oAuthNode.getLocalName().equals("oauthAccessTokenURI")) {
                    accessTokenUri = attribs.getNamedItemNS(OSLCConstants.RDF, "resource").getNodeValue();
                }
            }
        }
        if (requestTokenUri != null && authorizationUri != null && accessTokenUri != null)
            data.add(new Object[] { base, requestTokenUri, authorizationUri, accessTokenUri });
    }

    // If service provider didn't provide OAuth parameters, see if they
    // were provided in test configuration parameters.
    if (data.isEmpty()) {
        requestTokenUri = setupProps.getProperty("OAuthRequestTokenUrl");
        authorizationUri = setupProps.getProperty("OAuthAuthorizationUrl");
        accessTokenUri = setupProps.getProperty("OAuthAccessTokenUrl");
        if (requestTokenUri != null && authorizationUri != null && accessTokenUri != null)
            data.add(new Object[] { base, requestTokenUri, authorizationUri, accessTokenUri });
    }
    return data;
}

From source file:de.ingrid.portal.global.UtilsMapServiceManager.java

private static void evaluateKmlNode(HashMap data, Node node) {

    if (node.getNamespaceURI().equals(IDFNamespaceContext.NAMESPACE_URI_KML)) {
        Node documentNode = XPathUtils.getNode(node, "./kml:Document");
        if (documentNode != null) {
            Node titleNode = XPathUtils.getNode(documentNode, "./kml:name");
            String title = "";
            // Titel
            if (titleNode != null) {
                title = titleNode.getTextContent().trim();
                data.put("coord_class", title);
            }//from w w  w  .  j  a  v  a 2  s .c  om

            //Placemark
            NodeList placemarkNodeList = XPathUtils.getNodeList(documentNode, "./kml:Placemark");
            if (placemarkNodeList != null) {
                ArrayList<HashMap<String, String>> placemarks = new ArrayList<HashMap<String, String>>();
                for (int i = 0; i < placemarkNodeList.getLength(); i++) {
                    Node pmNode = placemarkNodeList.item(i);
                    HashMap<String, String> placemark = new HashMap<String, String>();
                    placemark.put("coord_class", title);

                    // Name
                    Node pmNameNode = XPathUtils.getNode(pmNode, "./kml:name");
                    if (pmNameNode != null) {
                        String name = pmNameNode.getTextContent().trim();
                        if (name != null) {
                            placemark.put("coord_title", name);
                        }
                    }

                    // Description
                    Node pmDescrNode = XPathUtils.getNode(pmNode, "./kml:description");
                    if (pmDescrNode != null) {
                        String description = pmDescrNode.getTextContent().trim();
                        if (description != null) {
                            placemark.put("coord_descr", description);
                        }
                    }

                    // Point
                    Node pmPointNode = XPathUtils.getNode(pmNode, "./kml:Point");
                    if (pmPointNode != null) {
                        if (pmPointNode.hasChildNodes()) {
                            Node coordinatesNode = XPathUtils.getNode(pmPointNode, "./kml:coordinates");
                            if (coordinatesNode != null) {
                                String coordinates = coordinatesNode.getTextContent().trim();
                                if (coordinates != null) {
                                    String[] coords = coordinates.split(",");
                                    placemark.put("coord_x", coords[0]);
                                    placemark.put("coord_y", coords[1]);
                                }
                            }
                        }
                    }
                    placemarks.add(placemark);
                }
                data.put("placemarks", placemarks);
            }
        }
    }
}

From source file:edu.duke.cabig.c3pr.webservice.integration.XMLUtils.java

/**
 * Does deep comparison of two DOM trees represented by the given
 * {@link Element}s. Elements are considered root nodes of the trees. <br>
 * <br>//  w w  w.  java  2 s . co m
 * This version of the method will <b>only</b> process elements of types
 * {@link Node#ELEMENT_NODE},{@link Node#TEXT_NODE},
 * {@link Node#CDATA_SECTION_NODE}; others will be ignored. Content of text
 * nodes is normalized before comparison. <br>
 * <br>
 * When comparing two elements, their local names, namespaces, and
 * attributes (except <code>xmlns* and xsi:type</code>) are accounted for. <br>
 * <br>
 * Due to issues with using
 * <code>setIgnoringElementContentWhitespace(true)</code>, which does not
 * seem to work, this method will throw out empty text nodes when comparing
 * children.
 * 
 * @since 1.0
 * @param e1
 * @param e2
 * @return
 */
public static boolean isDeepEqual(Node n1, Node n2) {
    if (!StringUtils.equals(n1.getLocalName(), n2.getLocalName())) {
        log.info("Node local names are not equal: " + n1.getLocalName() + " " + n2.getLocalName());
        return false;
    }
    if (!StringUtils.equals(n1.getNamespaceURI(), n2.getNamespaceURI())) {
        log.info("Node namespaces are not equal: " + n1.getNamespaceURI() + " " + n2.getNamespaceURI());
        return false;
    }
    if (n1.getNodeType() != n2.getNodeType()) {
        log.info("Node types are not equal: " + n1.getNodeType() + " " + n2.getNodeType());
        return false;
    }
    // check attributes equality.
    NamedNodeMap attrs1 = n1.getAttributes();
    NamedNodeMap attrs2 = n2.getAttributes();
    if (!isEqual(attrs1, attrs2)) {
        return false;
    }

    short nodeType = n1.getNodeType();
    switch (nodeType) {
    case Node.ELEMENT_NODE:
        return isDeepEqual(filterOutEmptyTextNodes(n1.getChildNodes()),
                filterOutEmptyTextNodes(n2.getChildNodes()));
    case Node.TEXT_NODE:
        return isTextNodeEqual(n1, n2);
    case Node.CDATA_SECTION_NODE:
        return isTextNodeEqual(n1, n2);
    default:
        break;
    }
    return true;
}

From source file:kenh.xscript.ScriptUtils.java

/**
 * Use <code>Node</code> to initial an <code>Element</code>.
 * @param node/*w  w  w  . j  a v  a2  s .co  m*/
 * @param env
 * @return
 */
private static final Element getElement(Node node, Environment env) throws UnsupportedScriptException {
    if (env == null)
        return null;

    String ns = node.getNamespaceURI(); // name space
    String name = node.getLocalName(); // name
    //String prefix = node.getPrefix(); // prefix

    Element element = env.getElement(ns, name);
    if (element == null) {
        throw new UnsupportedScriptException(null,
                "Could't find the element.[" + (StringUtils.isBlank(ns) ? name : ns + ":" + name) + "]");
    }
    element.setEnvironment(env);

    NamedNodeMap attributes = node.getAttributes();
    if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attr = attributes.item(i);
            String attrName = attr.getNodeName();
            String attrValue = attr.getNodeValue();

            if (attrName.equals("xmlns") || attrName.startsWith("xmlns:")) {
                if (attrName.startsWith("xmlns:")) {
                    // to add function package
                    String abbr = StringUtils.substringAfter(attrName, "xmlns:");
                    if (StringUtils.startsWithAny(abbr, "f.", "func.", "function.")) {
                        abbr = StringUtils.substringAfter(abbr, ".");
                        env.setFunctionPackage(abbr, attrValue);
                    }
                }
            } else {
                element.setAttribute(attrName, attrValue);
            }
        }
    }

    if (includeTextNode(node)) {
        String text = node.getTextContent();
        element.setText(text);
    }

    NodeList nodes = node.getChildNodes();
    if (nodes != null) {
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                Element child = getElement(n, env);
                element.addChild(child);
            }
        }
    }

    return element;
}

From source file:Main.java

/**
 * Builds an XPointer that refers to the given node. If a shorthand pointer
 * (using a schema-determined identifier) cannot be constructed, then a
 * scheme-based pointer is derived that indicates the absolute location path
 * of a node in a DOM document. The location is specified as a scheme-based
 * XPointer having two parts://from  w  ww.  jav a  2  s  .  co  m
 * <ul>
 * <li>an xmlns() part that declares a namespace binding context;</li>
 * <li>an xpointer() part that includes an XPath expression using the
 * abbreviated '//' syntax for selecting a descendant node.</li>
 * </ul>
 * 
 * @param node
 *            A node in a DOM document.
 * @return A String containing either a shorthand or a scheme-based pointer
 *         that refers to the node.
 * 
 * @see <a href="http://www.w3.org/TR/xptr-framework/"target="_blank">
 *      XPointer Framework</a>
 * @see <a href="http://www.w3.org/TR/xptr-xmlns/" target="_blank">XPointer
 *      xmlns() Scheme</a>
 * @see <a href="http://www.w3.org/TR/xptr-xpointer/"
 *      target="_blank">XPointer xpointer() Scheme</a>
 */
public static String buildXPointer(Node node) {
    if (null == node) {
        return "";
    }
    StringBuilder xpointer = new StringBuilder();
    if (null != node.getAttributes() && null != node.getAttributes().getNamedItem("id")) {
        String id = node.getAttributes().getNamedItem("id").getNodeValue();
        xpointer.append(node.getLocalName()).append("[@id='").append(id).append("']");
        return xpointer.toString();
    }
    String nsURI = node.getNamespaceURI();
    String nsPrefix = node.getPrefix();
    if (null == nsPrefix)
        nsPrefix = "tns";
    // WARNING: Escaping rules are currently ignored.
    xpointer.append("xmlns(").append(nsPrefix).append("=").append(nsURI).append(")");
    xpointer.append("xpointer((");
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        // Find the element in the list of all similarly named descendants
        // of the document root.
        NodeList elementsByName = node.getOwnerDocument().getElementsByTagNameNS(nsURI, node.getLocalName());
        for (int i = 0; i < elementsByName.getLength(); i++) {
            if (elementsByName.item(i).isSameNode(node)) {
                xpointer.append("//");
                xpointer.append(nsPrefix).append(':').append(node.getLocalName()).append(")[").append(i + 1)
                        .append("])");
                break;
            }
        }
        break;
    case Node.DOCUMENT_NODE:
        xpointer.append("/");
        break;
    case Node.ATTRIBUTE_NODE:
        Attr attrNode = (Attr) node;
        xpointer = new StringBuilder(buildXPointer(attrNode.getOwnerElement()));
        xpointer.insert(xpointer.lastIndexOf(")"), "/@" + attrNode.getName());
        break;
    default:
        xpointer.setLength(0);
        break;
    }
    return xpointer.toString();
}