Search in sources :

Example 61 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project processdash by dtuma.

the class XMLUtils method xPathObjects.

static <T> List<T> xPathObjects(String expr, Object context) {
    try {
        NodeList nodes = (NodeList) xPath().evaluate(expr, context, XPathConstants.NODESET);
        List<T> result = new ArrayList<T>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); i++) result.add((T) nodes.item(i));
        return result;
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList)

Example 62 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project ddf by codice.

the class XPathHelperTest method testXPathHelperNoTitle.

@Test
public void testXPathHelperNoTitle() throws Exception {
    try {
        String xmlString = getFileContentsAsString(TEST_DATA_PATH + "IngestMetadata_NoTitle.xml");
        XPathHelper xHelper = new XPathHelper(xmlString);
        String title = (String) xHelper.evaluate("//ns1:title", new MockNamespaceResolver());
        LOGGER.debug("testXPathHelper_NoTitle() - title = [{}]", title);
        assertNotNull(title);
        assertTrue(title.length() == 0);
    } catch (XPathExpressionException e1) {
        LOGGER.error("Exception thrown during testXPathHelper_NoTitle", e1);
    }
}
Also used : XPathHelper(ddf.util.XPathHelper) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Test(org.junit.Test)

Example 63 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project ddf by codice.

the class XPathHelperTest method testXPathHelperWithAnyNamespaceTextPath.

@Test
public void testXPathHelperWithAnyNamespaceTextPath() throws Exception {
    try {
        String xmlString = getFileContentsAsString(TEST_DATA_PATH + INPUT_FILE);
        XPathHelper xHelper = new XPathHelper(xmlString);
        NodeList nodeList = (NodeList) xHelper.evaluate("//xyz:fileTitle", XPathConstants.NODESET);
        LOGGER.debug("testXPathHelper_WithAnyNamespaceTextPath() - nodeList length = {}", nodeList.getLength());
        fail("Expected an XPathExpressionException");
    } catch (XPathExpressionException e1) {
        LOGGER.error("Exception thrown during testXPathHelper_WithAnyNamespaceTextPath", e1);
    }
}
Also used : XPathHelper(ddf.util.XPathHelper) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Test(org.junit.Test)

Example 64 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project ddf by codice.

the class ContextualEvaluator method getIndexableText.

/**
     * Extract the text from the specified XML Document that is to be indexed using the specified
     * XPath selectors.
     *
     * @param document
     * @param xpathSelectors
     * @return
     */
private static String getIndexableText(String document, String[] xpathSelectors) {
    String methodName = "getIndexableText";
    List<String> indexedText = new ArrayList<String>();
    LOGGER.debug("xpathSelectors.size = {}", xpathSelectors.length);
    StringBuilder sbuilder = new StringBuilder();
    try {
        // TODO Is this safe for all cases? Can there be multiple default namespaces such that
        // this would screw up the metadata?
        // Treat the "default namespace" (i.e., xmlns="http://some.namespace") the same as the
        // "no namespace" (i.e., xmlns="")
        // so that user-specified XPath Selectors do not need to specify a namespace for
        // expressions in the default namespace
        // (For example, user can specify //fileTitle vs. //namespace:fileTitle, where a
        // NamespaceContext/NamespaceResolver
        // would try to resolve the namespace they specified)
        // The regex below, "xmlns=['\"].*?['\"]", looks for:
        // xmlns="any chars between single or double quotes"
        document = document.replaceAll("xmlns=['\"].*?['\"]", "");
        XPathHelper xHelper = new XPathHelper(document);
        for (String xpath : xpathSelectors) {
            LOGGER.debug("Processing xpath selector: {}", xpath);
            NodeList nodeList = (NodeList) xHelper.evaluate(xpath, XPathConstants.NODESET);
            LOGGER.debug("nodeList length = {}", nodeList.getLength());
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                    Attr attribute = (Attr) node;
                    LOGGER.debug("Adding text [{}]", attribute.getNodeValue());
                    sbuilder.append(attribute.getNodeValue() + " ");
                // On each element node detected, traverse all of its children. Look for
                // any Text nodes it has, adding their text values to the list of indexable text
                } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element elem = (Element) node;
                    traverse(elem, indexedText);
                // getTextContent() concatenates *all* text from all descendant Text nodes
                // without
                // any white space between each Text node's value, e.g., JohnDoe vs. John
                // Doe
                // That's not good ...
                } else {
                    LOGGER.debug("Unsupported node type: " + node.getNodeType() + ",   node name = " + node.getNodeName());
                }
            }
        }
    } catch (XPathExpressionException e1) {
        LOGGER.debug("Unable to evaluate XPath", e1);
    }
    // Append all of the Text nodes' values to the single indexable text string
    for (String text : indexedText) {
        sbuilder.append(text);
    }
    return sbuilder.toString();
}
Also used : XPathHelper(ddf.util.XPathHelper) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Attr(org.w3c.dom.Attr)

Example 65 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project ddf by codice.

the class GmdTransformer method setMetacardDates.

private void setMetacardDates(Metacard metacard, final XstreamPathValueTracker pathValueTracker) {
    try (InputStream inputStream = getSourceInputStream()) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (ParserConfigurationException e) {
            LOGGER.debug("Unable to configure features on document builder.", e);
        }
        domFactory.setNamespaceAware(false);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(inputStream);
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression dataExpression = xPath.compile(GmdConstants.RESOURCE_DATE_PATH);
        NodeList dataList = (NodeList) dataExpression.evaluate(document, XPathConstants.NODESET);
        if (dataList != null && dataList.getLength() > 0) {
            List<String> dateList = new ArrayList<>();
            List<String> dateTypes = pathValueTracker.getAllValues(toPath(GmdConstants.CITATION_DATE_TYPE_PATH));
            for (int i = 0; i < dataList.getLength(); i++) {
                Node node = dataList.item(i);
                String datestring = node.getTextContent().trim().replaceAll(WHITE_SPACE_PATTER.pattern(), " ").replaceAll(NEW_LINE_PATTERN.pattern(), " ");
                String[] stringArray = datestring.split(" ");
                dateList.add(stringArray[0]);
            }
            if (CollectionUtils.isNotEmpty(dateList) && CollectionUtils.isNotEmpty(dateTypes) && dateList.size() == dateTypes.size()) {
                setDates(dateList, dateTypes, metacard);
            }
        }
    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        LOGGER.debug("Unable to parse dates in XML document.  Metacard Created / Effective / Modified dates will not be set.", e);
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) InputStream(java.io.InputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

XPathExpressionException (javax.xml.xpath.XPathExpressionException)157 XPath (javax.xml.xpath.XPath)79 NodeList (org.w3c.dom.NodeList)74 Document (org.w3c.dom.Document)51 Node (org.w3c.dom.Node)50 IOException (java.io.IOException)47 XPathExpression (javax.xml.xpath.XPathExpression)42 SAXException (org.xml.sax.SAXException)32 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)29 XPathFactory (javax.xml.xpath.XPathFactory)29 ArrayList (java.util.ArrayList)23 Element (org.w3c.dom.Element)22 InputSource (org.xml.sax.InputSource)20 HashMap (java.util.HashMap)19 Test (org.junit.Test)17 DocumentBuilder (javax.xml.parsers.DocumentBuilder)14 Response (com.jayway.restassured.response.Response)12 ValidatableResponse (com.jayway.restassured.response.ValidatableResponse)12 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)12 AbstractIntegrationTest (org.codice.ddf.itests.common.AbstractIntegrationTest)12