Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:org.ms123.common.importing.XmlImporter.java

private String getSourceValue(Stack<Element> parentElementStack, Map<String, String> binding) {
    int size = parentElementStack.size();
    Element bestElement = null;/*from w ww . j  a v a 2s .  co  m*/
    String bestSource = null;
    for (int i = size - 1; i >= 0; i--) {
        Element element = parentElementStack.get(i);
        String p = getElementPath(element);
        String s = binding.get("source");
        String source = removePart(s, p);
        if (bestSource == null || (countSegments(bestSource) > countSegments(source))) {
            if (m_xpathUtils.isExist(source, element, XPathConstants.NODE)) {
                bestSource = source;
                bestElement = element;
            }
        }
    }
    System.out.println("\tgetSourceValue.bestSource:" + bestSource);
    System.out.println("\tgetSourceValue.bestElement:" + bestElement);
    String value = m_xpathUtils.getValueString(bestSource, bestElement);
    System.out.println("getSourceValue.value:" + value);
    return value;
}

From source file:org.mule.ibeans.IBeansSupport.java

/**
 * Select a single XML node using an Xpath
 * @param xpath the XPath expression to evaluate
 * @param node the node (or document) to exaluate on
 * @return the result of the evaluation.  Note that if an error occurs, the error is logged and null is returned
 *///w w w.ja va 2s .  c  o  m
public static Node selectOne(String xpath, Node node) {
    try {
        XPath xp = createXPath(node);
        return (Node) xp.evaluate(xpath, node, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        logger.error(e.getMessage());
        return null;
    }
}

From source file:org.mule.module.dxpath.DxTransformer.java

/**
 * Result type from this transformer.//from   w ww.ja v a 2  s.c  om
 * 
 * @param resultType
 *            Result type from this transformer.
 */
public void setResultType(ResultType resultTypeType) {
    QName resultType;
    switch (resultTypeType) {
    case BOOLEAN:
        resultType = XPathConstants.BOOLEAN;
        break;
    case NODE:
        resultType = XPathConstants.NODE;
        break;
    case NODESET:
        resultType = XPathConstants.NODESET;
        break;
    case NUMBER:
        resultType = XPathConstants.NUMBER;
        break;
    default:
        resultType = XPathConstants.STRING;
        break;
    }
    this.resultType = resultType;
}

From source file:org.mule.module.xml.util.XMLUtils.java

/**
 * Select a single XML node using an Xpath
 * @param xpath the XPath expression to evaluate
 * @param node the node (or document) to exaluate on
 * @return the result of the evaluation.
 * @throws XPathExpressionException if the XPath expression is malformed and cannot be parsed
 *///from  www  .  j a v  a  2s.  c o m
public static Node selectOne(String xpath, Node node) throws XPathExpressionException {
    XPath xp = createXPath(node);
    return (Node) xp.evaluate(xpath, node, XPathConstants.NODE);
}

From source file:org.mycontroller.standalone.api.XmlApi.java

public void update(String uri, String xpath, String value) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, TransformerFactoryConfigurationError, TransformerException {
    Document document = getDocument(uri);
    XPathExpression expression = getXPathExpression(xpath);
    Node node = (Node) expression.evaluate(document, XPathConstants.NODE);
    node.setTextContent(value);// w w  w . j  a  va  2  s .  c om
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(new DOMSource(document), new StreamResult(FileUtils.getFile(uri)));
}

From source file:org.nuxeo.ecm.core.io.impl.TestTypedExportedDocument.java

/**
 * Test typed exported document./*  w w  w  . j a  va 2  s  .c o m*/
 *
 * @throws Exception the exception
 */
@Test
public void testTypedExportedDocument() throws Exception {

    DocumentModel doc = session
            .getDocument(new PathRef("/" + TypedExportedDocumentRepositoryInit.TEST_DOC_NAME));
    ExportedDocument exportedDoc = new TypedExportedDocumentImpl(doc);

    // Check system elements.
    assertEquals("File", exportedDoc.getType());
    assertEquals("testDoc", exportedDoc.getPath().toString());

    // Get w3c Document
    org.dom4j.Document dom4jDocument = exportedDoc.getDocument();
    Document document = dom4jToW3c(dom4jDocument);

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new CoreNamespaceContext());

    // Check dublincore schema
    Node schemaNode = (Node) xpath.evaluate("//schema[@name='dublincore']", document, XPathConstants.NODE);
    assertNotNull(schemaNode);

    Node fieldNode = (Node) xpath.evaluate("//dc:title[@type='string']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("My test doc", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:created[@type='date']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("2011-12-29T11:24:25.00Z", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:creator[@type='string']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("Administrator", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:modified[@type='date']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("2011-12-29T11:24:25.00Z", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:lastContributor[@type='string']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("Administrator", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:contributors[@type='scalarList']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);

    fieldNode = (Node) xpath.evaluate("//dc:contributors[@type='scalarList']/item[1]", document,
            XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("Administrator", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:contributors[@type='scalarList']/item[2]", document,
            XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("Joe", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:subjects[@type='scalarList']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);

    fieldNode = (Node) xpath.evaluate("//dc:subjects[@type='scalarList']/item[1]", document,
            XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("Art", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//dc:subjects[@type='scalarList']/item[2]", document,
            XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("Architecture", fieldNode.getTextContent());

    // Check file schema
    schemaNode = (Node) xpath.evaluate("//schema[@name='file']", document, XPathConstants.NODE);
    assertNotNull(schemaNode);

    fieldNode = (Node) xpath.evaluate("//file:filename[@type='string']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("test_file.doc", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//file:content[@type='content']", document, XPathConstants.NODE);
    assertNotNull(fieldNode);

    fieldNode = (Node) xpath.evaluate("//file:content[@type='content']/encoding", document,
            XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("UTF-8", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//file:content[@type='content']/mime-type", document,
            XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("text/plain", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//file:content[@type='content']/filename", document,
            XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertEquals("test_file.doc", fieldNode.getTextContent());

    fieldNode = (Node) xpath.evaluate("//file:content[@type='content']/data", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertTrue(!StringUtils.isEmpty(fieldNode.getTextContent()));

    fieldNode = (Node) xpath.evaluate("//file:content[@type='content']/digest", document, XPathConstants.NODE);
    assertNotNull(fieldNode);
    assertTrue(!StringUtils.isEmpty(fieldNode.getTextContent()));
}

From source file:org.nuxeo.ecm.platform.semanticentities.sources.DBpediaEntitySource.java

@Override
public List<EntitySuggestion> suggestRemoteEntity(String keywords, String type, int maxSuggestions)
        throws IOException {

    Map<String, String> localTypes = descriptor.getReverseMappedTypes();
    Set<String> acceptedLocalTypes = new TreeSet<String>();
    if (type != null) {
        acceptedLocalTypes.add(type);// w w  w. j a  v a  2  s  . c  o m
    } else {
        acceptedLocalTypes.addAll(localTypes.values());
    }
    // remove the overly generic type Entity for now
    acceptedLocalTypes.remove("Entity");

    // fetch more suggestions than requested since we will do type
    // post-filtering afterwards
    log.debug("suggestion query for keywords: " + keywords);
    InputStream bodyStream = fetchSuggestions(keywords, maxSuggestions * 3);
    if (bodyStream == null) {
        throw new IOException(String.format("Unable to fetch suggestion response for '%s'", keywords));
    }
    // Fetch the complete payload to make it easier for debugging (should
    // not be big anyway)
    String content = IOUtils.toString(bodyStream);
    log.trace(content);

    List<EntitySuggestion> suggestions = new ArrayList<EntitySuggestion>();
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document document = builder.parse(new ByteArrayInputStream(content.getBytes("utf-8")));
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList resultNodes = (NodeList) xpath.evaluate(RESULT_NODE_XPATH, document, XPathConstants.NODESET);
        for (int i = 0; i < resultNodes.getLength(); i++) {
            Node resultNode = resultNodes.item(i);
            String label = null;
            String uri = null;
            Node labelNode = (Node) xpath.evaluate("Label/text()", resultNode, XPathConstants.NODE);
            if (labelNode != null) {
                label = labelNode.getNodeValue();
            }
            Node uriNode = (Node) xpath.evaluate("URI/text()", resultNode, XPathConstants.NODE);
            if (uriNode != null) {
                uri = uriNode.getNodeValue();
            }
            NodeList typeNodes = (NodeList) xpath.evaluate("Classes/Class/URI/text()", resultNode,
                    XPathConstants.NODESET);
            String matchingLocalType = null;
            for (int k = 0; k < typeNodes.getLength(); k++) {
                Node typeNode = typeNodes.item(k);
                String localType = localTypes.get(typeNode.getNodeValue());
                if (localType != null && acceptedLocalTypes.contains(localType)) {
                    matchingLocalType = localType;
                    break;
                }
            }
            if (matchingLocalType != null && label != null && uri != null) {
                suggestions.add(new EntitySuggestion(label, uri, matchingLocalType));
                if (suggestions.size() >= maxSuggestions) {
                    break;
                }
            }
        }
    } catch (ParserConfigurationException e) {
        log.error(e, e);
        return Collections.emptyList();
    } catch (FactoryConfigurationError e) {
        log.error(e, e);
        return Collections.emptyList();
    } catch (XPathExpressionException e) {
        log.error(e, e);
        return Collections.emptyList();
    } catch (SAXException e) {
        throw new IOException(
                String.format("Invalid suggestion response for '%s' with type '%s'", keywords, type), e);
    } finally {
        bodyStream.close();
    }
    return suggestions;
}

From source file:org.nuxeo.theme.themes.ThemeParser.java

public static void parseProperties(org.w3c.dom.Element doc, Node node) throws ThemeIOException {
    NamedNodeMap attributes = node.getAttributes();
    Node elementAttr = attributes.getNamedItem("element");
    if (elementAttr == null) {
        throw new ThemeIOException("<properties> node has no 'element' attribute.");
    }//from  w  ww . j a  v a2 s. c o  m
    String elementXPath = elementAttr.getNodeValue();

    Node baseNode = getBaseNode(doc);
    Node element = null;
    try {
        element = (Node) xpath.evaluate(elementXPath, baseNode, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new ThemeIOException(e);
    }
    if (element == null) {
        throw new ThemeIOException("Could not find the element associated to: " + elementXPath);
    }
    Properties properties = getPropertiesFromNode(node);
    if (properties != null) {
        element.setUserData("properties", properties, null);
    }
}

From source file:org.nuxeo.theme.themes.ThemeParser.java

public static Node getBaseNode(org.w3c.dom.Element doc) throws ThemeIOException {
    Node baseNode = null;//from   w  w  w.ja v  a2  s .co m
    try {
        baseNode = (Node) xpath.evaluate('/' + DOCROOT_NAME + "/layout", doc, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new ThemeIOException(e);
    }
    if (baseNode == null) {
        throw new ThemeIOException("No <layout> section found.");
    }
    return baseNode;
}

From source file:org.obiba.opal.server.UpgradeCommand.java

/**
 * Load opal-config.xml and search for version node
 */// w  w  w  . ja va2s.c o  m
private boolean hasVersionInConfigXml() {
    try {
        File opalConfig = new File(System.getenv().get("OPAL_HOME"),
                "data" + File.separatorChar + "opal-config.xml");
        if (!opalConfig.exists())
            return false;

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(opalConfig);
        XPath xPath = XPathFactory.newInstance().newXPath();
        Node node = (Node) xPath.compile("//version").evaluate(doc.getDocumentElement(), XPathConstants.NODE);
        return node != null && !Strings.isNullOrEmpty(node.getNodeValue());
    } catch (SAXException | XPathExpressionException | ParserConfigurationException | IOException e) {
        throw new RuntimeException(e);
    }
}