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:org.n52.wps.server.handler.RequestHandler.java

/**
 * Handles requests of type HTTP_POST (currently executeProcess). A Document
 * is used to represent the client input. This Document must first be parsed
 * from an InputStream./*from  w  ww.  j a v  a 2 s.c om*/
 * 
 * @param is
 *            The client input
 * @param os
 *            The OutputStream to write the response to.
 * @throws ExceptionReport
 */
public RequestHandler(InputStream is, OutputStream os) throws ExceptionReport {
    String nodeName, localName, nodeURI, version = null;
    Document doc;
    this.os = os;

    boolean isCapabilitiesNode = false;

    try {
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);

        // parse the InputStream to create a Document
        doc = fac.newDocumentBuilder().parse(is);

        // Get the first non-comment child.
        Node child = doc.getFirstChild();
        while (child.getNodeName().compareTo("#comment") == 0) {
            child = child.getNextSibling();
        }
        nodeName = child.getNodeName();
        localName = child.getLocalName();
        nodeURI = child.getNamespaceURI();
        Node versionNode = child.getAttributes().getNamedItem("version");

        /*
         * check for service parameter. this has to be present for all requests
         */
        Node serviceNode = child.getAttributes().getNamedItem("service");

        if (serviceNode == null) {
            throw new ExceptionReport("Parameter <service> not specified.",
                    ExceptionReport.MISSING_PARAMETER_VALUE, "service");
        } else {
            if (!serviceNode.getNodeValue().equalsIgnoreCase("WPS")) {
                throw new ExceptionReport("Parameter <service> not specified.",
                        ExceptionReport.INVALID_PARAMETER_VALUE, "service");
            }
        }

        isCapabilitiesNode = nodeName.toLowerCase().contains("capabilities");
        if (versionNode == null && !isCapabilitiesNode) {
            throw new ExceptionReport("Parameter <version> not specified.",
                    ExceptionReport.MISSING_PARAMETER_VALUE, "version");
        }
        //TODO: I think this can be removed, as capabilities requests do not have a version parameter (BenjaminPross)
        if (!isCapabilitiesNode) {
            //            version = child.getFirstChild().getTextContent();//.getNextSibling().getFirstChild().getNextSibling().getFirstChild().getNodeValue();
            version = child.getAttributes().getNamedItem("version").getNodeValue();
        }
        /*
         * check language, if not supported, return ExceptionReport
         * Fix for https://bugzilla.52north.org/show_bug.cgi?id=905
         */
        Node languageNode = child.getAttributes().getNamedItem("language");
        if (languageNode != null) {
            String language = languageNode.getNodeValue();
            Request.checkLanguageSupported(language);
        }
    } catch (SAXException e) {
        throw new ExceptionReport("There went something wrong with parsing the POST data: " + e.getMessage(),
                ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (IOException e) {
        throw new ExceptionReport("There went something wrong with the network connection.",
                ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (ParserConfigurationException e) {
        throw new ExceptionReport("There is a internal parser configuration error",
                ExceptionReport.NO_APPLICABLE_CODE, e);
    }
    //Fix for Bug 904 https://bugzilla.52north.org/show_bug.cgi?id=904
    if (!isCapabilitiesNode && version == null) {
        throw new ExceptionReport("Parameter <version> not specified.", ExceptionReport.MISSING_PARAMETER_VALUE,
                "version");
    }
    if (!isCapabilitiesNode && !version.equals(Request.SUPPORTED_VERSION)) {
        throw new ExceptionReport("Version not supported.", ExceptionReport.INVALID_PARAMETER_VALUE, "version");
    }
    // get the request type
    if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("Execute")) {
        req = new ExecuteRequest(doc);
        setResponseMimeType((ExecuteRequest) req);
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("GetCapabilities")) {
        req = new CapabilitiesRequest(doc);
        this.responseMimeType = "text/xml";
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE) && localName.equals("DescribeProcess")) {
        req = new DescribeProcessRequest(doc);
        this.responseMimeType = "text/xml";

    } else if (!localName.equals("Execute")) {
        throw new ExceptionReport(
                "The requested Operation not supported or not applicable to the specification: " + nodeName,
                ExceptionReport.OPERATION_NOT_SUPPORTED, localName);
    } else if (nodeURI.equals(WebProcessingService.WPS_NAMESPACE)) {
        throw new ExceptionReport("specified namespace is not supported: " + nodeURI,
                ExceptionReport.INVALID_PARAMETER_VALUE);
    }
}

From source file:org.ojbc.bundles.adapters.staticmock.StaticMockQuery.java

private Document createFirearmRegistrationDocument(Document document, String firearmId) throws Exception {
    Document copy = createNewDocument();
    copy.appendChild(copy.importNode(document.getDocumentElement(), true));
    Node rootElement = XmlUtils.xPathNodeSearch(copy, "/*");
    LOG.debug("Keeper: " + firearmId);
    NodeList otherFirearmNodes = XmlUtils.xPathNodeListSearch(rootElement,
            "firearm-ext:Firearm[@s:id != '" + firearmId + "']");
    for (int i = 0; i < otherFirearmNodes.getLength(); i++) {
        Node goner = otherFirearmNodes.item(i);
        LOG.debug("Goner: " + XmlUtils.xPathStringSearch(goner, "@s:id"));
        rootElement.removeChild(goner);//w w w  .j av a  2 s. com
    }
    NodeList otherItemRegNodes = XmlUtils.xPathNodeListSearch(rootElement,
            "firearm-ext:ItemRegistration[@s:id != /firearm-doc:PersonFirearmRegistrationQueryResults/nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref='"
                    + firearmId + "']/nc:ItemRegistrationReference/@s:ref]");
    for (int i = 0; i < otherItemRegNodes.getLength(); i++) {
        rootElement.removeChild(otherItemRegNodes.item(i));
    }
    NodeList otherRegAssociationNodes = XmlUtils.xPathNodeListSearch(rootElement,
            "nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref != '" + firearmId + "']");
    for (int i = 0; i < otherRegAssociationNodes.getLength(); i++) {
        rootElement.removeChild(otherRegAssociationNodes.item(i));
    }
    copy.renameNode(rootElement, rootElement.getNamespaceURI(), "FirearmRegistrationQueryResults");
    Node documentRootElement = XmlUtils.xPathNodeSearch(document, "/*");
    rootElement.setPrefix(documentRootElement.getPrefix());
    return copy;
}

From source file:org.ojbc.util.xml.OjbcNamespaceContext.java

private Set<String> collectNamespaceURIs(Node e) {
    Set<String> ret = new HashSet<String>();
    String uri = e.getNamespaceURI();
    if (uri != null) {
        ret.add(uri);//w  w  w .j av a  2 s .  c o m
    }
    NodeList children = e.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child instanceof Element) {
            ret.addAll(collectNamespaceURIs(child));
        }
    }
    NamedNodeMap attributeMap = e.getAttributes();
    for (int i = 0; i < attributeMap.getLength(); i++) {
        Node attr = attributeMap.item(i);
        uri = attr.getNamespaceURI();
        if (uri != null) {
            ret.add(uri);
        }
    }
    return ret;
}

From source file:org.opendatakit.aggregate.parser.SubmissionParser.java

/**
 * Find the OpenRosa instanceID defined for this record, if any.
 * /*from w w  w  . j  av a 2 s. c  om*/
 * @return
 */
private String getOpenRosaInstanceId() {
    Node n = findMetaTag(root);
    if (n != null) {
        NodeList nl = n.getChildNodes();
        for (int i = 0; i < nl.getLength(); ++i) {
            Node cn = nl.item(i);
            String cnUri = cn.getNamespaceURI();
            String cnName = cn.getLocalName();
            if (cn.getNodeType() == Node.ELEMENT_NODE && cnName.equals(OPEN_ROSA_INSTANCE_ID)
                    && (cnUri == null || cnUri.equalsIgnoreCase(OPEN_ROSA_NAMESPACE)
                            || cnUri.equalsIgnoreCase(OPEN_ROSA_NAMESPACE_SLASH)
                            || cnUri.equalsIgnoreCase(OPEN_ROSA_NAMESPACE_PRELIM))) {
                NodeList cnl = cn.getChildNodes();
                boolean textFound = false;
                int idxText = -1;
                for (int j = 0; j < cnl.getLength(); ++j) {
                    Node cnln = cnl.item(j);
                    if (cnln.getNodeType() == Node.TEXT_NODE) {
                        if (textFound) {
                            throw new IllegalStateException("Expected a single text node");
                        }
                        textFound = true;
                        idxText = j;
                    }
                }
                if (textFound) {
                    return cnl.item(idxText).getNodeValue();
                }
            }
        }
    }
    return null;
}

From source file:org.opendatakit.aggregate.parser.SubmissionParser.java

/**
 * Traverse submission looking for OpenRosa metadata tag (with or without
 * namespace).//w  w w. j  a v a2s .  c om
 * 
 * @param parent
 * @return
 */
private Node findMetaTag(Node parent) {
    if (parent.getNodeType() != Node.ELEMENT_NODE)
        return null;
    @SuppressWarnings("unused")
    String parentName = parent.getLocalName();
    NodeList nl = parent.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i) {
        Node n = nl.item(i);
        String namespace = n.getNamespaceURI();
        String name = n.getLocalName();
        if (n.getNodeType() == Node.ELEMENT_NODE && name.equals(OPEN_ROSA_METADATA_TAG)
                && (namespace == null || namespace.equalsIgnoreCase(OPEN_ROSA_NAMESPACE)
                        || namespace.equalsIgnoreCase(OPEN_ROSA_NAMESPACE_SLASH)
                        || namespace.equalsIgnoreCase(OPEN_ROSA_NAMESPACE_PRELIM))) {
            return n;
        } else {
            n = findMetaTag(n);
            if (n != null)
                return n;
        }
    }
    return null;
}

From source file:org.opendaylight.controller.netconf.it.NetconfITTest.java

private void assertSameAttributes(final NamedNodeMap expectedAttributes,
        final NamedNodeMap returnedAttributes) {
    assertNotNull("Expecting 4 attributes", returnedAttributes);
    assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());

    for (int i = 0; i < expectedAttributes.getLength(); i++) {
        final Node expAttr = expectedAttributes.item(i);
        final Node attr = returnedAttributes.item(i);
        assertEquals(expAttr.getNodeName(), attr.getNodeName());
        assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
        assertEquals(expAttr.getTextContent(), attr.getTextContent());
    }/*from w w  w .ja va 2s . c o m*/
}

From source file:org.openehealth.ipf.commons.ihe.ws.utils.SoapUtils.java

/**
 * Searches for the first sub-element of the given XML element, which has
 * the given local name and whose namespace belongs to the given set.
 *
 * @param root//from   w  ww  .j  a v a 2s.co  m
 *      an XML element whose children will be iterated, null values are allowed
 * @param nsUris
 *      a set of namespace URIs the wanted element can belong to
 * @param wantedLocalName
 *      local name of the wanted element
 * @return
 *      corresponding child element or <code>null</code> when none found
 */
public static Element getElementNS(Element root, Set<String> nsUris, String wantedLocalName) {
    if (root == null) {
        return null;
    }

    Node node = root.getFirstChild();
    while (node != null) {
        if ((node instanceof Element) && nsUris.contains(node.getNamespaceURI())
                && node.getLocalName().equals(wantedLocalName)) {
            return (Element) node;
        }

        node = node.getNextSibling();
    }

    return null;
}

From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java

License:asdf

/**
 * Verifica se ambos os nos so iguais fazendo uma comparao em
 * profundidade./*from w w  w  .  j av  a 2 s.  c  om*/
 *
 * @param n1 -
 * @param n2 -
 * @throws Exception Se nbo forem iguais
 */
public static void isIgual(Node n1, Node n2) throws Exception {
    if (n1 == n2) {
        return;
    }

    isIgual(n1, n2, "NodeName", n1.getNodeName(), n2.getNodeName());
    isIgual(n1, n2, "NodeValue", n1.getNodeValue(), n2.getNodeValue());
    isIgual(n1, n2, "Namespace", n1.getNamespaceURI(), n2.getNamespaceURI());
    isIgual(n1, n2, "Prefix", n1.getPrefix(), n2.getPrefix());
    isIgual(n1, n2, "LocalName", n1.getLocalName(), n2.getLocalName());

    if (isMesmaClasse(Element.class, n1, n2)) {
        Element e1 = (Element) n1;
        Element e2 = (Element) n2;
        //Verifica se possuem os mesmos atributos
        NamedNodeMap nn1 = e1.getAttributes();
        NamedNodeMap nn2 = e2.getAttributes();
        if (nn1.getLength() != nn2.getLength()) {
            fail("O nmero atributos em " + XPathToolkit.getFullPath(n1) + " (qtd=" + nn1.getLength()
                    + "  diferente de n2 (qtd=" + nn2.getLength() + ")");
        }
        for (int i = 0; i < nn1.getLength(); i++) {
            isIgual((Attr) nn1.item(i), (Attr) nn2.item(i));
        }

        //Verifica se possuem os mesmos filhos
        Node filho1 = e1.getFirstChild();
        Node filho2 = e2.getFirstChild();
        int count = 0;
        while ((filho1 != null) && (filho2 != null)) {
            isIgual(filho1, filho2);
            filho1 = filho1.getNextSibling();
            filho2 = filho2.getNextSibling();
            count++;
        }
        if (filho1 != null) {
            fail("H mais node [" + count + "] " + XPathToolkit.getNomeTipo(filho1) + " ("
                    + XPathToolkit.getFullPath(filho1) + ") em n1:" + XPathToolkit.getFullPath(n1));
        }
        if (filho2 != null) {
            fail("H mais node [" + count + "] " + XPathToolkit.getNomeTipo(filho2) + " ("
                    + XPathToolkit.getFullPath(filho2) + ") em n2:" + XPathToolkit.getFullPath(n2));
        }

    } else if (isMesmaClasse(Attr.class, n1, n2)) {
        //Ok

    } else if (isMesmaClasse(Text.class, n1, n2)) {
        //Ok

    } else {
        fail("Tipo de n " + n1.getClass() + " no tratado");
    }

}

From source file:org.osaf.caldav4j.methods.PropFindMethod.java

/**
 * A lot of this code had to be copied from the parent XMLResponseMethodBase, since it's 
 * initHashtable doesn't allow for new types of Responses.
 * /*from  w  ww  .ja va2 s  . c  om*/
 * Of course, the same mistake is being made here, so it is a TODO to fix that
 *
 */
@SuppressWarnings("unchecked")
private void initHashtable() {
    responseHashtable = new Hashtable<String, CalDAVResponse>();
    responseURLs = new Vector<String>();
    // Also accept OK sent by buggy servers in reply to a PROPFIND
    // or REPORT (Xythos, Catacomb, ...?).
    int statusCode = getStatusCode();
    if (statusCode == WebdavStatus.SC_MULTI_STATUS) {

        Document rdoc = getResponseDocument();

        NodeList list = null;
        if (rdoc != null) {
            Element multistatus = getResponseDocument().getDocumentElement();
            list = multistatus.getChildNodes();
        }

        if (list != null) {
            for (int i = 0; i < list.getLength(); i++) {
                try {
                    Element child = (Element) list.item(i);
                    String name = DOMUtils.getElementLocalName(child);
                    String namespace = DOMUtils.getElementNamespaceURI(child);
                    if (Response.TAG_NAME.equals(name) && "DAV:".equals(namespace)) {
                        CalDAVResponse response = new CalDAVResponse(child);
                        String href = response.getHref();
                        responseHashtable.put(href, response);
                        responseURLs.add(href);
                    }
                } catch (ClassCastException e) {
                }
            }
        }
    } else if (statusCode == WebdavStatus.SC_CONFLICT || statusCode == WebdavStatus.SC_FORBIDDEN) {
        Document rdoc = getResponseDocument();
        Element errorElement = rdoc.getDocumentElement();

        // first make sure that the element is actually an error.
        if (!errorElement.getNamespaceURI().equals(NS_DAV)
                || !errorElement.getLocalName().equals(ELEMENT_ERROR)) {
            Node condition = errorElement.getChildNodes().item(0);
            error = errorMap.get(new QName(condition.getNamespaceURI(), condition.getLocalName()));
        }
    }
}

From source file:org.rapidcontext.app.web.WebDavRequest.java

/**
 * Parses a property find request. All properties found will be
 * added to the query properties map. If no properties node was
 * provided, all standard properties will be added.
 *
 * @param node           the properties node, or null
 * @param isCollection   the collection flag
 *///from  w w w. ja  va  2 s . c om
private void parsePropFind(Element node, boolean isCollection) {
    LinkedHashMap defaults;
    String name;

    defaults = isCollection ? PROPS_COLLECTION : PROPS_FILE;
    if (node == null) {
        properties.putAll(defaults);
    } else {
        Node child = node.getFirstChild();
        while (child != null) {
            if (child.getNodeType() != Node.ELEMENT_NODE) {
                // Ignore non-elements
            } else if ("DAV:".equals(child.getNamespaceURI())) {
                if (defaults.containsKey(child.getLocalName())) {
                    properties.put(child.getLocalName(), "");
                } else {
                    properties.put(child.getLocalName(), null);
                }
            } else {
                name = child.getNamespaceURI() + ":" + child.getLocalName();
                properties.put(name, null);
            }
            child = child.getNextSibling();
        }
    }
}