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:eu.semaine.util.XMLTool.java

/**
 * Same as {@link #getChildElementByTagNameNS(Node, String, String)}, but
 * throw a MessageFormatException if there is no such child element.
 * @param node//from   w  w w .  j  a  va  2 s .  c  o  m
 * @param childName
 * @param childNamespace
 * @return a non-null child element
 * @throws MessageFormatException if there is no such child, 
 * i.e. when getChildElementByTagNameNS() would return null.
 */
public static Element needChildElementByTagNameNS(Node node, String childName, String childNamespace)
        throws MessageFormatException {
    Element e = getChildElementByTagNameNS(node, childName, childNamespace);
    if (e == null) {
        String nodeNamespace = node.getNamespaceURI();
        boolean sameNamespace = childNamespace != null && childNamespace.equals(nodeNamespace)
                || childNamespace == null && nodeNamespace == null;
        throw new MessageFormatException("Node '" + node.getNodeName() + "' in namespace '" + nodeNamespace
                + " needs to have a child '" + childName + "' in "
                + (sameNamespace ? "the same namespace" : "namespace '" + childNamespace + "'"));
    }
    return e;
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Same as {@link #getChildElementByLocalNameNS(Node, String, String)}, but
 * throw a MessageFormatException if there is no such child element.
 * @param node//from  ww w  . j  a  v  a2  s.c  o  m
 * @param childName
 * @param childNamespace
 * @return a non-null child element
 * @throws MessageFormatException if there is no such child, 
 * i.e. when getChildElementByTagNameNS() would return null.
 */
public static Element needChildElementByLocalNameNS(Node node, String childName, String childNamespace)
        throws MessageFormatException {
    Element e = getChildElementByLocalNameNS(node, childName, childNamespace);
    if (e == null) {
        String nodeNamespace = node.getNamespaceURI();
        boolean sameNamespace = childNamespace != null && childNamespace.equals(nodeNamespace)
                || childNamespace == null && nodeNamespace == null;
        throw new MessageFormatException("Node '" + node.getNodeName() + "' in namespace '" + nodeNamespace
                + " needs to have a child '" + childName + "' in "
                + (sameNamespace ? "the same namespace" : "namespace '" + childNamespace + "'"));
    }
    return e;
}

From source file:com.centeractive.ws.builder.soap.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the
 * specified wsdlUrl//w  ww  . ja  v  a 2s. com
 */

public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    // if( add )
    // existing.put( wsdlUrl, null );

    log.info("Getting schema " + wsdlUrl);

    ArrayList<?> errorList = new ArrayList<Object>();

    Map<String, XmlObject> result = new HashMap<String, XmlObject>();

    boolean common = false;

    try {
        XmlOptions options = new XmlOptions();
        options.setCompileNoValidation();
        options.setSaveUseOpenFrag();
        options.setErrorListener(errorList);
        options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema"));

        XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options);
        if (xmlObject == null)
            throw new Exception("Failed to load schema from [" + wsdlUrl + "]");

        Document dom = (Document) xmlObject.getDomNode();
        Node domNode = dom.getDocumentElement();

        // is this an xml schema?
        if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) {
            // set targetNamespace (this happens if we are following an include
            // statement)
            if (tns != null) {
                Element elm = ((Element) domNode);
                if (!elm.hasAttribute("targetNamespace")) {
                    common = true;
                    elm.setAttribute("targetNamespace", tns);
                }

                // check for namespace prefix for targetNamespace
                NamedNodeMap attributes = elm.getAttributes();
                int c = 0;
                for (; c < attributes.getLength(); c++) {
                    Node item = attributes.item(c);
                    if (item.getNodeName().equals("xmlns"))
                        break;

                    if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns"))
                        break;
                }

                if (c == attributes.getLength())
                    elm.setAttribute("xmlns", tns);
            }

            if (common && !existing.containsKey(wsdlUrl + "@" + tns))
                result.put(wsdlUrl + "@" + tns, xmlObject);
            else
                result.put(wsdlUrl, xmlObject);
        } else {
            existing.put(wsdlUrl, null);

            XmlObject[] schemas = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema");

            for (int i = 0; i < schemas.length; i++) {
                XmlCursor xmlCursor = schemas[i].newCursor();
                String xmlText = xmlCursor.getObject().xmlText(options);
                // schemas[i] = XmlObject.Factory.parse( xmlText, options );
                schemas[i] = XmlUtils.createXmlObject(xmlText, options);
                schemas[i].documentProperties().setSourceName(wsdlUrl);

                result.put(wsdlUrl + "@" + (i + 1), schemas[i]);
            }

            XmlObject[] wsdlImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location");
            for (int i = 0; i < wsdlImports.length; i++) {
                String location = ((SimpleValue) wsdlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadl10Imports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadl10Imports.length; i++) {
                String location = ((SimpleValue) wadl10Imports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadlImports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadlImports.length; i++) {
                String location = ((SimpleValue) wadlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

        }

        existing.putAll(result);

        XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]);

        for (int c = 0; c < schemas.length; c++) {
            xmlObject = schemas[c];

            XmlObject[] schemaImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation");
            for (int i = 0; i < schemaImports.length; i++) {
                String location = ((SimpleValue) schemaImports[i]).getStringValue();
                Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement();

                if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] schemaIncludes = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation");
            for (int i = 0; i < schemaIncludes.length; i++) {
                String location = ((SimpleValue) schemaIncludes[i]).getStringValue();
                if (location != null) {
                    String targetNS = getTargetNamespace(xmlObject);

                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, targetNS);
                }
            }
        }
    } catch (Exception e) {
        throw new SoapBuilderException(e);
    }
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Create a child element with the given name and append it below node.
 * The new element will have the same namespace as node.
 * If node has a namespace prefix, the new element will also use that namespace prefix.
 * @param node/*w ww .j  ava  2  s  . c om*/
 * @param childName
 * @return the child element
 */
public static Element appendChildElement(Node node, String childName) {
    if (node == null)
        throw new NullPointerException("Received null node");
    if (childName == null)
        throw new NullPointerException("Received null childName");
    Element child = (Element) node
            .appendChild(createElement(node.getOwnerDocument(), childName, node.getNamespaceURI()));
    String parentPrefix = node.getPrefix();
    if (parentPrefix != null) {
        child.setPrefix(parentPrefix);
    }
    return child;
}

From source file:com.wavemaker.tools.ws.WebServiceToolsManager.java

/**
 * Returns the XML qualified name of the root element type for the given XML.
 *///from w w  w.  j  a va2  s. com
public static String getXmlRootElementType(String xml)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Reader reader = new StringReader(xml);
    Document doc = db.parse(new InputSource(reader));
    Node node = doc.getFirstChild();
    if (node != null) {
        String namespaceURI = node.getNamespaceURI();
        String localName = node.getLocalName();
        if (localName != null) {
            return namespaceURI == null ? localName : namespaceURI + ":" + localName;
        }
    }
    return null;
}

From source file:de.betterform.xml.xforms.action.SetFocusAction.java

/**
 * Performs element init.//w  w w . j  a v a 2 s.  c om
 */
public void init() throws XFormsException {
    super.init();
    // check if setfocus elem has 
    NodeList childNodes = element.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (NamespaceConstants.XFORMS_NS.equals(node.getNamespaceURI()) && node.getLocalName().equals("control")
                && node.getNodeType() == Node.ELEMENT_NODE) {
            Element elementImpl = (Element) node;
            XFormsElement xfElem = (XFormsElement) this.element.getUserData("");
            if (elementImpl.hasAttributeNS(null, "value")) {
                String xpath = elementImpl.getAttributeNS(null, "value");
                this.referencedControl = XPathCache.getInstance().evaluateAsString(
                        xfElem.getModel().getDefaultInstance().getRootContext(), "string(" + xpath + ")");
            } else {
                this.referencedControl = elementImpl.getTextContent();
            }
        }
    }

    if (this.referencedControl == null) {
        this.referencedControl = getXFormsAttribute(CONTROL_ATTRIBUTE);
    }
    if (this.referencedControl == null) {
        throw new XFormsBindingException(
                "missing control attribute at " + DOMUtil.getCanonicalPath(this.getElement()), this.target,
                null);
    }
}

From source file:com.gargoylesoftware.htmlunit.svg.SvgPageTest.java

/**
 * Tests namespace./*w  ww . j ava  2s. c  om*/
 * @throws Exception if the test fails
 */
@Test
public void namespace() throws Exception {
    final String content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
            + "<svg xmlns=\"http://www.w3.org/2000/svg\">\n"
            + "  <rect id=\"rect\" width=\"50\" height=\"50\" fill=\"green\""
            + " onclick=\"alert(document.getElementById('rect'))\"/>\n" + "</svg>";

    final SgmlPage page = testDocument(content, "text/xml");
    final Node root = page.getDocumentElement();
    assertEquals("svg", root.getNodeName());
    assertEquals("http://www.w3.org/2000/svg", root.getNamespaceURI());
}

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());
    }// ww  w  .  j  a v  a 2s  . c om
    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:de.betterform.xml.dom.DOMUtil.java

/**
 * __UNDOCUMENTED__// w  ww.j a va 2  s. c  om
 *
 * @param nodeToCompare __UNDOCUMENTED__
 * @param nsuri         __UNDOCUMENTED__
 * @param tagName       __UNDOCUMENTED__
 * @return __UNDOCUMENTED__
 */
public static boolean isNodeInNS(Node nodeToCompare, String nsuri, String tagName) {
    String ntcnsuri = nodeToCompare.getNamespaceURI();

    if ((ntcnsuri != null) && (ntcnsuri.length() > 0)) {
        return (tagName.equals(nodeToCompare.getLocalName()) && ntcnsuri.equals(nsuri));
    } else {
        return (tagName.equals(nodeToCompare.getNodeName()));
    }
}

From source file:com.mtgi.analytics.aop.config.v11.BtPersisterChainBeanDefinitionParser.java

@Override
@SuppressWarnings("unchecked")
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    //propagate shared template factory into sub-components if necessary.  this would not be
    //necessary if parserContext gave us access to the entire component stack instead of just the
    //top.  In that case, deeply nested children could search up the stack until they found
    //the template.  perhaps a future version of the Spring API will support this.
    DefaultListableBeanFactory template = findEnclosingTemplateFactory(parserContext);
    if (template != null)
        parserContext.pushContainingComponent(new TemplateComponentDefinition(element.getNodeName(),
                parserContext.extractSource(element), template));

    try {//from w  w w  . j a v a2s .  c om
        //parse delegate persister definitions
        ManagedList persisters = new ManagedList();
        persisters.setSource(element);

        NodeList nodes = element.getChildNodes();
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                String namespaceUri = node.getNamespaceURI();
                NamespaceHandler handler = parserContext.getReaderContext().getNamespaceHandlerResolver()
                        .resolve(namespaceUri);
                Object def = handler == null
                        ? parserContext.getDelegate().parsePropertySubElement((Element) node,
                                builder.getRawBeanDefinition())
                        : handler.parse((Element) node, parserContext);
                persisters.add(def);
            }
        }
        builder.addPropertyValue("delegates", persisters);
    } finally {
        if (template != null)
            parserContext.popContainingComponent();
    }

    //register persister implementation with parent.
    if (parserContext.isNested()) {
        AbstractBeanDefinition def = builder.getBeanDefinition();
        String id = element.hasAttribute("id") ? element.getAttribute("id")
                : parserContext.getReaderContext().generateBeanName(def);
        BeanDefinitionHolder holder = new BeanDefinitionHolder(def, id);
        BtManagerBeanDefinitionParser.registerNestedBean(holder, "persister", parserContext);
    }
}