Search in sources :

Example 86 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project robovm by robovm.

the class XPathExpressionImpl method evaluate.

/**
     * <p>Evaluate the compiled XPath expression in the context of the 
     * specified <code>InputSource</code> and return the result as the
     *  specified type.</p>
     *
     * <p>This method builds a data model for the {@link InputSource} and calls
     * {@link #evaluate(Object item, QName returnType)} on the resulting 
     * document object.</p>
     *
     * <p>See "Evaluation of XPath Expressions" section of JAXP 1.3 spec
     *  for context item evaluation,
     * variable, function and QName resolution and return type conversion.</p>
     *
     * <p>If <code>returnType</code> is not one of the types defined in 
     * {@link XPathConstants},
     * then an <code>IllegalArgumentException</code> is thrown.</p>
     *
     *<p>If <code>source</code> or <code>returnType</code> is <code>null</code>,
     * then a <code>NullPointerException</code> is thrown.</p>
     *
     * @param source The <code>InputSource</code> of the document to evaluate
     * over.
     * @param returnType The desired return type.
     *
     * @return The <code>Object</code> that is the result of evaluating the
     * expression and converting the result to
     *   <code>returnType</code>.
     *
     * @throws XPathExpressionException If the expression cannot be evaluated.
     * @throws IllegalArgumentException If <code>returnType</code> is not one
     * of the types defined in {@link XPathConstants}.
     * @throws NullPointerException If  <code>source</code> or 
     * <code>returnType</code> is <code>null</code>.
     */
public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException {
    if ((source == null) || (returnType == null)) {
        String fmsg = XSLMessages.createXPATHMessage(XPATHErrorResources.ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL, null);
        throw new NullPointerException(fmsg);
    }
    // defined in XPathConstants 
    if (!isSupported(returnType)) {
        String fmsg = XSLMessages.createXPATHMessage(XPATHErrorResources.ER_UNSUPPORTED_RETURN_TYPE, new Object[] { returnType.toString() });
        throw new IllegalArgumentException(fmsg);
    }
    try {
        if (dbf == null) {
            dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            dbf.setValidating(false);
        }
        db = dbf.newDocumentBuilder();
        Document document = db.parse(source);
        return eval(document, returnType);
    } catch (Exception e) {
        throw new XPathExpressionException(e);
    }
}
Also used : XPathExpressionException(javax.xml.xpath.XPathExpressionException) Document(org.w3c.dom.Document) XPathExpressionException(javax.xml.xpath.XPathExpressionException) TransformerException(javax.xml.transform.TransformerException)

Example 87 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project robovm by robovm.

the class JaxenXPathTestSuite method createFromTest.

/**
     * Returns the test described by the given {@code <test>} element. Such
     * tests come in one of three varieties:
     *
     * <ul>
     *   <li>Expected failures.
     *   <li>String matches. These tests have a nested {@code <valueOf>} element
     *       that sub-selects an expected text.
     *   <li>Count matches. These tests specify how many nodes are expected to
     *       match.
     * </ul>
     */
private static TestCase createFromTest(final XPath xpath, final Context context, final Element element) {
    final String select = element.getAttribute("select");
    /* Such as <test exception="true" select="..." count="0"/> */
    if (element.getAttribute("exception").equals("true")) {
        return new XPathTest(context, select) {

            @Override
            void test(Node contextNode) {
                try {
                    xpath.evaluate(select, contextNode);
                    fail("Expected exception!");
                } catch (XPathExpressionException expected) {
                }
            }
        };
    }
    /* a <test> with a nested <valueOf>, both of which have select attributes */
    NodeList valueOfElements = element.getElementsByTagName("valueOf");
    if (valueOfElements.getLength() == 1) {
        final Element valueOf = (Element) valueOfElements.item(0);
        final String valueOfSelect = valueOf.getAttribute("select");
        return new XPathTest(context, select) {

            @Override
            void test(Node contextNode) throws XPathExpressionException {
                Node newContext = (Node) xpath.evaluate(select, contextNode, XPathConstants.NODE);
                assertEquals(valueOf.getTextContent(), xpath.evaluate(valueOfSelect, newContext, XPathConstants.STRING));
            }
        };
    }
    /* Such as <test select="..." count="5"/> */
    final String count = element.getAttribute("count");
    if (count.length() > 0) {
        return new XPathTest(context, select) {

            @Override
            void test(Node contextNode) throws XPathExpressionException {
                NodeList result = (NodeList) xpath.evaluate(select, contextNode, XPathConstants.NODESET);
                assertEquals(Integer.parseInt(count), result.getLength());
            }
        };
    }
    throw new UnsupportedOperationException("Unsupported test: " + context);
}
Also used : XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element)

Example 88 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project honeycomb by altamiracorp.

the class ConfigurationParser method parseAdapters.

private static Map<String, Map<String, String>> parseAdapters(Document doc) {
    // Extract adapter names from document
    NodeList adapterNameNodes;
    try {
        adapterNameNodes = (NodeList) xPath.evaluate(QUERY_ADAPTER_NAMES, doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        logger.error("Unable to parse adapter names from honeycomb configuration.", e);
        throw new RuntimeException("Exception while parsing adapter names from honeycomb configuration.", e);
    }
    List<String> adapterNames = Lists.newArrayList();
    for (int i = 0; i < adapterNameNodes.getLength(); i++) {
        Node adapterNameNode = adapterNameNodes.item(i);
        if (adapterNameNode.getNodeType() == Node.ATTRIBUTE_NODE) {
            adapterNames.add(adapterNameNode.getNodeValue());
        }
    }
    // Extract individual adapter options from the document
    ImmutableMap.Builder<String, Map<String, String>> adapters = ImmutableMap.builder();
    for (String adapterName : adapterNames) {
        adapters.put(adapterName, parseOptions(adapterName, doc));
    }
    return adapters.build();
}
Also used : XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 89 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project atlas by alibaba.

the class ManifestFileUtils method getPackage.

public static String getPackage(File manifestFile) {
    String version = manifestMap.get(manifestFile.getAbsolutePath());
    if (null != version) {
        return version;
    }
    XPath xpath = AndroidXPathFactory.newXPath();
    try {
        version = xpath.evaluate("/manifest/@package", new InputSource(new FileInputStream(manifestFile)));
        manifestMap.put(manifestFile.getAbsolutePath(), version);
        return version;
    } catch (XPathExpressionException e) {
    // won't happen.
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
    return null;
}
Also used : XPath(javax.xml.xpath.XPath) InputSource(org.xml.sax.InputSource) XPathExpressionException(javax.xml.xpath.XPathExpressionException) FileNotFoundException(java.io.FileNotFoundException) FileInputStream(java.io.FileInputStream)

Example 90 with XPathExpressionException

use of javax.xml.xpath.XPathExpressionException in project perun by CESNET.

the class MUStrategy method parseResponse.

/**
	 * Parse String response as XML document and retrieve Publications from it.
	 * @param xml XML response from MU Prezentator
	 * @return List of Publications
	 * @throws CabinetException If anything fails
	 */
protected List<Publication> parseResponse(String xml) throws CabinetException {
    assert xml != null;
    List<Publication> result = new ArrayList<Publication>();
    //hook for titles with &
    xml = xml.replace("&", "&amp;");
    //log.debug("RESPONSE: "+xml);
    //Create new document factory builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        throw new CabinetException("Error when creating newDocumentBuilder.", ex);
    }
    Document doc;
    try {
        doc = builder.parse(new InputSource(new StringReader(xml)));
    } catch (SAXParseException ex) {
        throw new CabinetException("Error when parsing uri by document builder.", ErrorCodes.MALFORMED_HTTP_RESPONSE, ex);
    } catch (SAXException ex) {
        throw new CabinetException("Problem with parsing is more complex, not only invalid characters.", ErrorCodes.MALFORMED_HTTP_RESPONSE, ex);
    } catch (IOException ex) {
        throw new CabinetException("Error when parsing uri by document builder. Problem with input or output.", ErrorCodes.MALFORMED_HTTP_RESPONSE, ex);
    }
    //Prepare xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression publicationsQuery;
    try {
        publicationsQuery = xpath.compile("/P/UL/publication");
    } catch (XPathExpressionException ex) {
        throw new CabinetException("Error when compiling xpath query.", ex);
    }
    NodeList nodeList;
    try {
        nodeList = (NodeList) publicationsQuery.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException ex) {
        throw new CabinetException("Error when evaluate xpath query on document.", ex);
    }
    //Test if there is any nodeset in result
    if (nodeList.getLength() == 0) {
        //There is no results, return empty subjects
        return result;
    }
    //Iterate through nodes and convert them to Map<String,String>
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node singleNode = nodeList.item(i);
        // remove node from original structure in order to keep access time constant (otherwise is exp.)
        singleNode.getParentNode().removeChild(singleNode);
        try {
            Publication publication = convertNodeToPublication(singleNode);
            result.add(publication);
        } catch (InternalErrorException ex) {
            log.error("Unable to parse Publication:", ex);
        }
    }
    return result;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Publication(cz.metacentrum.perun.cabinet.model.Publication) IOException(java.io.IOException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Aggregations

XPathExpressionException (javax.xml.xpath.XPathExpressionException)139 NodeList (org.w3c.dom.NodeList)65 XPath (javax.xml.xpath.XPath)64 Document (org.w3c.dom.Document)46 Node (org.w3c.dom.Node)46 IOException (java.io.IOException)42 XPathExpression (javax.xml.xpath.XPathExpression)38 SAXException (org.xml.sax.SAXException)27 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)25 XPathFactory (javax.xml.xpath.XPathFactory)23 ArrayList (java.util.ArrayList)22 HashMap (java.util.HashMap)18 Test (org.junit.Test)17 InputSource (org.xml.sax.InputSource)17 Element (org.w3c.dom.Element)16 Response (com.jayway.restassured.response.Response)12 ValidatableResponse (com.jayway.restassured.response.ValidatableResponse)12 DocumentBuilder (javax.xml.parsers.DocumentBuilder)12 AbstractIntegrationTest (org.codice.ddf.itests.common.AbstractIntegrationTest)12 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)11