Example usage for javax.xml.xpath XPathExpressionException getMessage

List of usage examples for javax.xml.xpath XPathExpressionException getMessage

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpressionException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.mercatis.lighthouse3.commons.commons.XmlMuncher.java

/**
 * This method returns the list of string values reached by the given XPath
 * expression in the XML document being munched.
 *
 * @param xpathExpression the XPath expression to evaluate.
 * @return the list of values reached by the expression.
 * @throws XPathExpressionException in case of an error
 *///from w  ww  .  ja  v a 2 s  .c  om
public List<String> readValuesFromXml(String xpathExpression) {
    List<String> result = new ArrayList<String>();

    try {

        Iterator<LinkedHashMap<String, String>> documentPaths = this.documentPaths.iterator();

        while (documentPaths.hasNext()) {
            Iterator<Entry<String, String>> currentPaths = documentPaths.next().entrySet().iterator();
            ;

            while (currentPaths.hasNext()) {
                Entry<String, String> path = currentPaths.next();

                if (this.xpathExpressionToRegexp(xpathExpression).matcher(path.getKey()).matches()) {
                    if (!"".equals(path.getValue()) && (path.getValue() != null))
                        result.add(path.getValue());
                }
            }
        }

    } catch (XPathExpressionException e) {
        throw new DOMException((short) 0, "Could not evaluate XPathExpression: " + e.getMessage());

    }

    return result;
}

From source file:com.mercatis.lighthouse3.commons.commons.XmlMuncher.java

/**
 * This method returns the value reached by the given XPath expression in
 * the XML document being munched.// w  w  w. j  av  a  2s.  c  om
 *
 * @param xpathExpression the XPath expression to evaluate.
 * @return the value reached by the expression. If nothing is reached,
 *         <code>null</code> is returned.
 * @throws XPathExpressionException in case of an error
 */
public String readValueFromXml(String xpathExpression) {
    String result = null;

    try {
        Pattern pattern = this.xpathExpressionToRegexp(xpathExpression);
        boolean valueFound = false;

        Iterator<LinkedHashMap<String, String>> documentPaths = this.documentPaths.iterator();

        while (documentPaths.hasNext() && !valueFound) {
            Iterator<Entry<String, String>> currentPaths = documentPaths.next().entrySet().iterator();

            while (currentPaths.hasNext() && !valueFound) {
                Entry<String, String> path = currentPaths.next();

                if (pattern.matcher(path.getKey()).matches()) {
                    if (!EMPTY_STRING.equals(path.getValue()) && (path.getValue() != null)) {
                        result = path.getValue();
                        valueFound = true;
                    }
                }
            }
        }

    } catch (XPathExpressionException e) {
        throw new DOMException((short) 0, "Could not evaluate XPathExpression: " + e.getMessage());
    }

    return result;
}

From source file:com.mercatis.lighthouse3.commons.commons.XmlMuncher.java

/**
 * This method produces sub munchers out of the current XML muncher limited
 * to a certain context. This allows one to query repeating complex element
 * structures./* w  w w  . j  a  v a 2 s. c o  m*/
 *
 * @param xpathExpression the XPath expression defining the context.
 * @return a list of new munchers.
 * @throws XPathExpressionException in case the XPath expression is invalid.
 */
public List<XmlMuncher> getSubMunchersForContext(String xpathExpression) throws DOMException {
    List<XmlMuncher> subMunchers = new ArrayList<XmlMuncher>();
    XmlMuncher currentMuncher = new XmlMuncher();

    Pattern translation = null;
    try {
        translation = this.translateXPathExpressionToRegexp(xpathExpression);
    } catch (XPathExpressionException e) {
        throw new DOMException((short) 0, "Could not evaluate XPathExpression: " + e.getMessage());
    }

    for (LinkedHashMap<String, String> currentPathBatch : this.documentPaths) {
        Iterator<Entry<String, String>> currentPaths = currentPathBatch.entrySet().iterator();
        ;

        while (currentPaths.hasNext()) {
            Entry<String, String> currentPath = currentPaths.next();

            String localizedPath = this.localizePath(translation, currentPath.getKey());

            if (localizedPath != null && !localizedPath.substring(1).contains("/")) {
                if (!currentMuncher.isEmpty()) {
                    subMunchers.add(currentMuncher);
                    currentMuncher = new XmlMuncher();
                }
            } else if (localizedPath != null) {
                currentMuncher.addDocumentPath(currentMuncher.documentPaths, localizedPath,
                        currentPath.getValue());
            }
        }

    }

    if (!currentMuncher.isEmpty()) {
        subMunchers.add(currentMuncher);
    }

    return subMunchers;
}

From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaTreeWalkerBase.java

/**
 * @param bos//from  w  ww  .  ja  va2s . c  om
 * @param object
 * @param elem
 * @param level
 * @throws Exception 
 */
protected void walkMapCalcMapTree(BoundedObjectSet bos, XmlBosMember currentMember, Document mapDoc, int level)
        throws Exception {
    String levelSpacer = getLevelSpacer(level);

    log.debug("walkMap(): " + levelSpacer + "Walking map  " + mapDoc.getDocumentURI() + "...");

    Element mapRoot = mapDoc.getDocumentElement();

    NodeList resultNl;
    try {
        resultNl = (NodeList) DitaUtil.allTopicrefsWithHrefs.evaluate(mapRoot, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new BosException(
                "XPath exception evaluating XPath against a DITA map managed object: " + e.getMessage(), e);
    }

    List<Document> childMaps = new ArrayList<Document>();

    for (int i = 0; i < resultNl.getLength(); i++) {
        Element topicRef = (Element) resultNl.item(i);
        if (DitaUtil.isMapReference(topicRef)) {
            String href = topicRef.getAttribute("href");
            log.debug("walkMap(): " + levelSpacer + "  handling map reference to href \"" + href + "\"...");
            Document targetDoc = null;
            try {
                targetDoc = AddressingUtil.resolveHrefToDoc(topicRef, href, bosConstructionOptions,
                        this.failOnAddressResolutionFailure);
            } catch (Exception e) {
                throw new BosException("Exception resolving href: " + e.getMessage(), e);
            }
            if (targetDoc != null) {
                childMaps.add(targetDoc);
            } else {
                throw new BosException("Failed to resolve @href value \"" + href
                        + "\" to a managed object from map " + mapDoc.getDocumentURI());
            }
        }
    }

    log.debug("walkMap(): " + levelSpacer + "  Found " + childMaps.size() + " child maps.");

    // Now we have a list of the child maps in document order by reference.
    // Iterate over them to update the key space:

    if (childMaps.size() > 0) {
        log.debug("walkMap(): " + levelSpacer + "  Adding key definitions from child maps...");

        for (Document childMap : childMaps) {
            keySpace.addKeyDefinitions(childMap.getDocumentElement());
        }

        // Now walk each of the maps to process the next level in the map hierarchy:

        log.debug("walkMap(): " + levelSpacer + "  Walking child maps...");
        for (Document childMapDoc : childMaps) {
            XmlBosMember childMember = bos.constructBosMember(currentMember, childMapDoc);
            bos.addMember(currentMember, childMember);
            walkMapCalcMapTree(bos, childMember, childMapDoc, level + 1);
        }
        log.debug("walkMap(): " + levelSpacer + "  Done walking child maps");
    }

}

From source file:com.geodan.ngr.serviceintegration.CSWTransformer.java

/**
 * Parses the InputStream to valid WMSResponses and returns them in a list using XPath.
 *
 * This method is essentially unchanged from the old Geodan implementation except it now parses a String.
 *
 * @param response      the String that contains the response from the GetRecords request
 * @return         a List that contains WMSResources or errors
 * @throws java.io.IOException in case of exception
 * @throws javax.xml.parsers.ParserConfigurationException in case of exception
 * @throws org.xml.sax.SAXException in case of exception
 *//*from ww  w . jav  a2 s. c om*/
private List<WMSResource> parse(String response)
        throws ParserConfigurationException, IOException, SAXException {

    List<WMSResource> wmsresourcelist = new ArrayList<WMSResource>();

    //
    // Create DOM document from response
    //
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    InputSource source = new InputSource(new StringReader(response));
    Document xmldoc = factory.newDocumentBuilder().parse(source);

    // With XPath get the WMS data
    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContext nsContext = new CSWNamespaceContext();
    xpath.setNamespaceContext(nsContext);

    // The XML parse expression
    String expr = "/GetRecordsResponse/SearchResults/MD_Metadata/distributionInfo/MD_Distribution/transferOptions/MD_DigitalTransferOptions/onLine/CI_OnlineResource";
    try {
        // Run XPath
        NodeList nodes = (NodeList) xpath.evaluate(expr, xmldoc, XPathConstants.NODESET);

        // Check for nodes else generate error no records available
        if (nodes != null && nodes.getLength() > 0) {

            // Get for every node the values if no name and URL are available then generate a error. If the title has no value then the name can be the title.
            for (int i = 0; i < nodes.getLength(); i++) {
                Element el = (Element) nodes.item(i);
                String title = findTitle(el);
                String description = findDescription(el);
                String url = getValue(el, "gmd:linkage");
                String protocol = getValue(el, "gmd:protocol");
                String name = getValue(el, "gmd:name");
                if (name != null && url != null && !name.equals("") && !url.equals("")) {
                    WMSResource wmsresource = new WMSResource(title, url, protocol, name, description);
                    if (title == null) {
                        wmsresource.setTitle(name);
                    }
                    wmsresourcelist.add(wmsresource);
                } else {
                    // Because there already is an List<WMSRecords> the method "getException" will not be used
                    WMSResource wmsresource = new WMSResource(" \"records\": []}}");
                    wmsresourcelist.add(wmsresource);
                }
            }
        } else {
            // Because there already is an List<WMSRecords> the method "getException" will not be used
            WMSResource wmsresource = new WMSResource(" \"records\": []}}");
            wmsresourcelist.add(wmsresource);
        }
    } catch (XPathExpressionException e) {
        // Because there already is an List<WMSRecords> the method "getException" will not be used
        WMSResource wmsresource = new WMSResource("\"error\": \"There is an XPathExpressionException\"}}");
        wmsresourcelist.add(wmsresource);
    } catch (Exception e) {
        log.error("ERROR: " + e.getMessage());
        e.printStackTrace();
        // Because there already is an List<WMSRecords> the method "getException" will not be used
        WMSResource wmsresource = new WMSResource("\"error\": \"The result could not be parsed\"}}");
        wmsresourcelist.add(wmsresource);
    }
    // Return the results
    return wmsresourcelist;
}

From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java

/**
 * Returns the error codes/*from  ww  w  .  ja v  a 2  s  . com*/
 * @param rootNode
 * @param xpath
 * @return
 * @throws TSClientExecutionException
 */
protected List<Long> parseErrorCodes(Node rootNode, XPath xpath) throws TSClientExecutionException {

    NodeList errorCodeNodes = null;
    try {
        errorCodeNodes = (NodeList) xpath.evaluate(TEST_EXEC_ERROR_CODES, rootNode, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new TSClientExecutionException(
                "Failed to parse out error codes from document received from " + httpHost.getHostName());
    }

    List<Long> result = new ArrayList<Long>();
    if (errorCodeNodes != null && errorCodeNodes.getLength() > 0) {
        for (int i = 0; i < errorCodeNodes.getLength(); i++) {
            if (errorCodeNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                try {
                    // TODO refactor to xpath
                    String errorCodeStr = errorCodeNodes.item(i).getTextContent();//;(String)xpath.evaluate(TEST_EXEC_SINGLE_ERROR_CODE, errorCodeNodes.item(i), XPathConstants.STRING);                  
                    result.add(Long.parseLong(errorCodeStr.trim()));
                } catch (NumberFormatException e) {
                    throw new TSClientExecutionException(
                            "Failed to parse error code from document received from " + httpHost.getHostName()
                                    + ". Error: " + e.getMessage());
                    //               } catch(XPathExpressionException e) {
                    //                  throw new TSClientExecutionException("Failed to parse error code from document received from " + httpHost.getHostName() + ". Error: " + e.getMessage());
                }
            }
        }
    }
    return result;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.ClinicalXmlValidator.java

/**
 * This method parses the clinical XML file for dates to validate, regardless of formatting (whitespaces).
 *
 * @param xmlFile the XML file to validate
 * @param xPath the xpath object//from  w ww .j av  a  2  s . c om
 * @param document the document parsed from the xml
 * @param context the application context
 * @param dateNameToValueMap a Map to store the dates that need to be compared later
 * @param datePrecision map to store precision of dates (day, month, or year)
 * @return <code>true</code> if the dates are all valid, <code>false</code> otherwise
 * @throws IOException
 */
protected boolean checkDateValidation(final File xmlFile, final XPath xPath, final Document document,
        final QcContext context, final Map<String, Date> dateNameToValueMap,
        final Map<String, String> datePrecision) throws IOException {

    boolean result = true;

    try {
        //Iterate on the list of element's name suffixes to validate the different dates
        final Iterator<String> xpathSuffixIterator = getDatesToValidate().iterator();
        String xpathSuffix;
        while (xpathSuffixIterator.hasNext()) {

            xpathSuffix = xpathSuffixIterator.next();
            int indexOfColon = xpathSuffix.indexOf(":");
            String namespacePrefix = null;
            if (indexOfColon > 0) {
                namespacePrefix = xpathSuffix.substring(0, indexOfColon);
            }
            // only check the date if it is in a namespace contained in this document
            if (namespacePrefix == null
                    || xPath.getNamespaceContext().getNamespaceURI(namespacePrefix) != null) {
                //Update result
                result = checkDateForXPath(document, xPath, xpathSuffix, context, dateNameToValueMap,
                        datePrecision) && result;
            }
        }

    } catch (XPathExpressionException e) {

        //Update result
        result = false;
        context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR, xmlFile.getName(),
                new StringBuilder().append("XPath Expression error reading '").append(xmlFile.getName())
                        .append("': ").append(e.getMessage()).toString()));
    } catch (UnexpectedInput e) {

        //Update result
        result = false;
        context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR, xmlFile.getName(),
                new StringBuilder().append("Unexpected input error reading '").append(xmlFile.getName())
                        .append("': ").append(e.getMessage()).toString()));
    }

    return result;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ClinicalDateObscurer.java

/**
 * Parses the given XML <code>Document</code> and return a <code>NodeList</code> of all XML Nodes that match <code>yearOfPrefix<code>.
 *
 * @param document the <code>Document</code> to parse
 * @param xpath an <code>XPath</code> instance
 * @return a <code>NodeList</code> of all XML Nodes that match <code>yearOfPrefix<code>
 * @throws ProcessorException if there are not as many nodes matching <code>monthOfPrefix<code> and <code>dayOfPrefix<code>
 *//*  w w  w  . j a v a  2  s  .  co  m*/
private List<Node> getAllYearOfDatesFromDocument(Document document, XPath xpath) throws ProcessorException {

    // Get all the date Nodes from the Document
    final String yearOfNodesAttributesExpression = getXPathExpressionForAnyElementContaining(yearOfPrefix);
    final String monthOfNodesAttributesExpression = getXPathExpressionForAnyElementContaining(monthOfPrefix);
    final String dayOfNodesAttributesExpression = getXPathExpressionForAnyElementContaining(dayOfPrefix);

    final NodeList yearOfNodes;
    final NodeList monthOfNodes;
    final NodeList dayOfNodes;

    try {
        yearOfNodes = getNodeListFromXPathExpression(document, xpath, yearOfNodesAttributesExpression);
        monthOfNodes = getNodeListFromXPathExpression(document, xpath, monthOfNodesAttributesExpression);
        dayOfNodes = getNodeListFromXPathExpression(document, xpath, dayOfNodesAttributesExpression);

        // new rule: if a year_of node has no month or day, ignore it since its not a full date
        // this means year-only elements will not be obscured
        Map<String, Node> yearOfDates = new HashMap<String, Node>();
        Set<String> monthOfDates = new HashSet<String>();
        Set<String> dayOfDates = new HashSet<String>();

        for (int i = 0; i < yearOfNodes.getLength(); i++) {
            yearOfDates.put(getDateNameFromNodeName(yearOfNodes.item(i), yearOfPrefix), yearOfNodes.item(i));
        }
        for (int i = 0; i < monthOfNodes.getLength(); i++) {
            monthOfDates.add(getDateNameFromNodeName(monthOfNodes.item(i), monthOfPrefix));
        }
        for (int i = 0; i < dayOfNodes.getLength(); i++) {
            dayOfDates.add(getDateNameFromNodeName(dayOfNodes.item(i), dayOfPrefix));
        }

        final List<Node> dateYears = new ArrayList<Node>();
        for (final String yearOfDate : yearOfDates.keySet()) {
            if (monthOfDates.contains(yearOfDate) && dayOfDates.contains(yearOfDate)) {
                dateYears.add(yearOfDates.get(yearOfDate));
            } // else, does not have month and day so not complete date so ignore it -- if the schema is like that, it means the date doesn't need to be obscured
        }

        return dateYears;

    } catch (final XPathExpressionException e) {
        throw new ProcessorException("Error while getting dates element from XML Document: " + e.getMessage(),
                e);
    }
}

From source file:io.pyd.synchro.SyncJob.java

/**
 * Parses remote node structure directly from XML stream using modified
 * SAXparser.// w  w w  . jav  a2 s  .c o m
 * 
 * @param remoteTreeFile
 * @param parentNode
 * @param list
 * @param save
 * @throws SynchroOperationException
 * @throws InterruptedException
 */
protected void parseNodesFromStream(InputStream is, final Node parentNode, final List<Node> list,
        final boolean save) throws SynchroOperationException, InterruptedException {

    try {
        XMLReader reader = new XMLReader();
        reader.addHandler("tree", new NodeHandler() {

            @Override
            public void process(StructuredNode node) {

                // check if user wants to stop?
                if (interruptRequired) {
                    return;
                }

                try {
                    org.w3c.dom.Node xmlNode = node.queryXMLNode("/tree");

                    Node entry = new Node(Node.NODE_TYPE_ENTRY, "", parentNode);
                    // init node with properties saved to LOCAL property
                    // collection
                    entry.initFromXmlNode(xmlNode, true);

                    if (list != null) {
                        list.add(entry);
                    }
                } catch (XPathExpressionException e) {
                    // FIXME - how to manage this errors here?

                }
            }
        });
        reader.parse(is);

        if (interruptRequired) {
            throw new InterruptedException("Interrupt required");
        }
        if (list != null) {
            Logger.getRootLogger().info("Parsed " + list.size() + " nodes from stream");
        } else {
            Logger.getRootLogger().info("No items to parse");
        }
    } catch (ParserConfigurationException e) {
        throw new SynchroOperationException(
                "Error during parsing remote node tree structure: " + e.getMessage(), e);
    } catch (SAXException e) {

        throw new SynchroOperationException(
                "Error during parsing remote node tree structure: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new SynchroOperationException(
                "Error during parsing remote node tree structure: " + e.getMessage(), e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // we cannot do here nothing more
            }
        }
    }
}

From source file:com.cloud.hypervisor.kvm.resource.LibvirtComputingResourceTest.java

static void assertNodeExists(final Document doc, final String xPathExpr) {
    try {/* w  w  w.j av  a 2s. co  m*/
        Assert.assertNotNull(
                XPathFactory.newInstance().newXPath().evaluate(xPathExpr, doc, XPathConstants.NODE));
    } catch (final XPathExpressionException e) {
        Assert.fail(e.getMessage());
    }
}