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:Main.java

public static void main(String[] args) {

    String simpleXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><person><name>Bob</name></person>";
    InputSource inputSource = new InputSource(new StringReader(simpleXML));
    XPath xpath = XPathFactory.newInstance().newXPath();

    try {// w  ww  .ja  v a2 s. c  om
        String name = xpath.evaluate("//name", inputSource);
        System.out.println(name);
    } catch (XPathExpressionException e) {
        System.out.println(e.getMessage());
    }
}

From source file:Main.java

public static String getFirstValueFromXPath(Element parent, String xpath) throws Exception {
    try {//from ww  w  . j  a v  a2 s . c  om
        XPath xPath = XPathFactory.newInstance().newXPath();
        return (String) xPath.compile(xpath).evaluate(parent, XPathConstants.STRING);
    } catch (XPathExpressionException xpee) {
        throw new Exception(xpee.getMessage());
    }
}

From source file:Main.java

public static String getFirstValueFromXPath(Document parent, String xpath) throws Exception {
    try {/*from  w  ww .  ja  v a  2s . c o  m*/
        XPath xPath = XPathFactory.newInstance().newXPath();
        return (String) xPath.compile(xpath).evaluate(parent, XPathConstants.STRING);
    } catch (XPathExpressionException xpee) {
        throw new Exception(xpee.getMessage());
    }
}

From source file:Main.java

/***
 * Returns the string value of evaluated xpath
 *
 * @param  document    - XML Document to check
 * @param  xpathString - xpath to evaluate
 * @return String evaluation of the xpath
 *//*from w  ww  .  j a  va  2 s. com*/
public static String getValueFromXPath(Document document, String xpathString) {
    try {
        return (String) XPathFactory.newInstance().newXPath().evaluate(xpathString, document,
                XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Error evaluating xpath [" + xpathString + "] -- " + e.getMessage());
    }
}

From source file:Main.java

/**
 * Performs a xpath query on a document and returns the matching nodelist.
 *
 * @param context the Context where to start with the query
 * @param query the XPath-Query//w w  w  .  j a  v  a2 s  . co  m
 * @return nodelist of matches
 * @throws Exception on error
 */
public static NodeList query(Node context, String query) throws Exception {
    NodeList result = null;
    XPath xpath = XPathFactory.newInstance().newXPath();

    try {
        result = (NodeList) xpath.evaluate(query, context, XPathConstants.NODESET);
    } catch (XPathExpressionException xpx) {
        throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx);
    }
    return result;
}

From source file:Main.java

/**
 * Performs a xpath query on a document and returns the matching nodelist.
 *
 * @param doc/*from  w w  w.  ja  v a 2 s  .  c o  m*/
 * @param xpathQuery
 * @return nodelist of matches
 * @throws Exception
 */
public static NodeList query(Document doc, String xpathQuery) throws Exception {
    NodeList result = null;
    // prepare XPath
    XPath xpath = XPathFactory.newInstance().newXPath();

    try {
        // query xml
        result = (NodeList) xpath.evaluate(xpathQuery, doc, XPathConstants.NODESET);
    } catch (XPathExpressionException xpx) {
        throw new Exception("Error evaluating XPath: " + xpx.getMessage(), xpx);
    }
    return result;
}

From source file:cz.incad.kramerius.imaging.lp.DeleteGeneratedDeepZoomCache.java

/**
 * Recursive delete /*from w  w w.  ja  v a 2s  .  c  om*/
 * @param pid Master PID
 * @param fedoraAccess FedoraAccess implementation
 * @param discStruct DiscStructure instance 
 * @throws IOException IO error has been occurred
 * @throws ProcessSubtreeException Error in tree walking 
 */
public static void deleteCacheForPID(String pid, final FedoraAccess fedoraAccess,
        final DiscStrucutreForStore discStruct) throws IOException, ProcessSubtreeException {
    if (fedoraAccess.isImageFULLAvailable(pid)) {
        try {
            deleteFolder(pid, discStruct);
        } catch (XPathExpressionException e) {
            LOGGER.severe(e.getMessage());
        }
    } else {

        fedoraAccess.processSubtree(pid, new TreeNodeProcessor() {

            @Override
            public void process(String pid, int level) throws ProcessSubtreeException {
                try {
                    if (fedoraAccess.isImageFULLAvailable(pid)) {
                        //LOGGER.info("Deleting " + (pageIndex++) +" uuid = "+uuid);
                        deleteFolder(pid, discStruct);
                    }
                } catch (DOMException e) {
                    LOGGER.severe(e.getMessage());
                } catch (XPathExpressionException e) {
                    LOGGER.severe(e.getMessage());
                } catch (IOException e) {
                    LOGGER.severe(e.getMessage());
                }
            }

            @Override
            public boolean skipBranch(String pid, int level) {
                return false;
            }

            @Override
            public boolean breakProcessing(String pid, int level) {
                return false;
            }

        });

    }

}

From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java

/**
 * Returns the query result or <code>null</code>.
 * //from  ww  w . j a  v  a  2s.  c  om
 * @param node
 *          the context node
 * @param xpathExpression
 *          the xpath expression
 * @param defaultValue
 *          the default value
 * @param processor
 *          the xpath engine
 * 
 * @return the selected string or <code>defaultValue</code> if the query
 *         didn't yield a result
 */
public static String valueOf(Node node, String xpathExpression, String defaultValue, XPath processor) {

    if (node == null || processor == null)
        return null;

    try {
        String value = StringUtils.trimToNull(processor.evaluate(xpathExpression, node));

        // If we are running in test mode, we may neglect namespaces
        if (value == null) {
            NamespaceContext ctx = processor.getNamespaceContext();
            if (ctx instanceof XPathNamespaceContext && ((XPathNamespaceContext) ctx).isTest()) {
                if (xpathExpression.matches("(.*)[a-zA-Z0-9]+\\:[a-zA-Z0-9]+(.*)")) {
                    String xpNs = xpathExpression.replaceAll("[a-zA-Z0-9]+\\:", "");
                    value = StringUtils.trimToNull(processor.evaluate(xpNs, node));
                }
            }
        }
        return (value != null) ? value : defaultValue;
    } catch (XPathExpressionException e) {
        logger.warn("Error when selecting '{}': {}", xpathExpression, e.getMessage());
        return null;
    }
}

From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

public static Document replaceTokens(Document doc, Policy configTokens)
        throws XPathExpressionException, TransformerConfigurationException {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(configTokens);
    logger.info("============= to apply the following config tokens ================\n{}", json);

    try {/*from  ww w  .  j av a  2  s .  c  om*/
        for (int i = 0; i < configTokens.tokens.size(); i++) {

            logger.debug("=============Checking for Xpath Expressions {}  ================\n",
                    configTokens.tokens.get(i).xpath);
            XPathExpression expression = xpath.compile(configTokens.tokens.get(i).xpath);

            NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);

            for (int j = 0; j < nodes.getLength(); j++) {

                if (nodes.item(j).hasChildNodes()) {
                    logger.debug("=============Updated existing value {} to new value {} ================\n",
                            nodes.item(j).getTextContent(), configTokens.tokens.get(i).value);
                    nodes.item(j).setTextContent(configTokens.tokens.get(i).value);
                }
            }

        }

        return doc;
    } catch (XPathExpressionException e) {

        logger.error(String.format(
                "\n\n=============The Xpath Expressions in config.json are incorrect. Please check. ================\n\n%s",
                e.getMessage()), e);
        throw e;
    }

}

From source file:com.espertech.esper.event.xml.SchemaXMLPropertyParser.java

/**
 * Return the xPath corresponding to the given property.
 * The propertyName String may be simple, nested, indexed or mapped.
 *
 * @param propertyName is the event property name
 * @param namespace is the default namespace
 * @param schemaModel is the schema model
 * @param xPathFactory is the xpath factory instance to use
 * @param rootElementName is the name of the root element
 * @param eventAdapterService for type lookup and creation
 * @param xmlEventType the resolving type
 * @param isAllowFragment whether fragmenting is allowed
 * @param defaultNamespace default namespace
 * @return xpath expression/* w w w  .j  a  va2 s. co  m*/
 * @throws EPException is there are XPath errors
 */
public static EventPropertyGetter getXPathResolution(String propertyName, XPathFactory xPathFactory,
        String rootElementName, String namespace, SchemaModel schemaModel,
        EventAdapterService eventAdapterService, BaseXMLEventType xmlEventType, boolean isAllowFragment,
        String defaultNamespace) throws EPException {
    if (log.isDebugEnabled()) {
        log.debug("Determining XPath expression for property '" + propertyName + "'");
    }

    XPathNamespaceContext ctx = new XPathNamespaceContext();
    List<String> namespaces = schemaModel.getNamespaces();

    String defaultNamespacePrefix = null;
    for (int i = 0; i < namespaces.size(); i++) {
        String prefix = "n" + i;
        ctx.addPrefix(prefix, namespaces.get(i));
        if ((defaultNamespace != null) && (defaultNamespace.equals(namespaces.get(i)))) {
            defaultNamespacePrefix = prefix;
        }
    }

    Tree ast = PropertyParser.parse(propertyName);
    Property property = PropertyParser.parse(propertyName, false);
    boolean isDynamic = property.isDynamic();

    SchemaElementComplex rootComplexElement = SchemaUtil.findRootElement(schemaModel, namespace,
            rootElementName);
    String prefix = ctx.getPrefix(rootComplexElement.getNamespace());
    if (prefix == null) {
        prefix = "";
    } else {
        prefix += ':';
    }

    StringBuilder xPathBuf = new StringBuilder();
    xPathBuf.append('/');
    xPathBuf.append(prefix);
    if (rootElementName.startsWith("//")) {
        xPathBuf.append(rootElementName.substring(2));
    } else {
        xPathBuf.append(rootElementName);
    }

    SchemaElementComplex parentComplexElement = rootComplexElement;
    Pair<String, QName> pair = null;

    if (ast.getChildCount() == 1) {
        pair = makeProperty(rootComplexElement, ast.getChild(0), ctx, true, isDynamic, defaultNamespacePrefix);
        if (pair == null) {
            throw new PropertyAccessException("Failed to locate property '" + propertyName + "' in schema");
        }
        xPathBuf.append(pair.getFirst());
    } else {
        for (int i = 0; i < ast.getChildCount(); i++) {
            boolean isLast = (i == ast.getChildCount() - 1);
            Tree child = ast.getChild(i);
            pair = makeProperty(parentComplexElement, child, ctx, isLast, isDynamic, defaultNamespacePrefix);
            if (pair == null) {
                throw new PropertyAccessException("Failed to locate property '" + propertyName
                        + "' nested property part '" + child.toString() + "' in schema");
            }

            String text = child.getChild(0).getText();
            SchemaItem obj = SchemaUtil.findPropertyMapping(parentComplexElement, text);
            if (obj instanceof SchemaElementComplex) {
                parentComplexElement = (SchemaElementComplex) obj;
            }
            xPathBuf.append(pair.getFirst());
        }
    }

    String xPath = xPathBuf.toString();
    if ((ExecutionPathDebugLog.isDebugEnabled) && (log.isDebugEnabled())) {
        log.debug(".parse XPath for property '" + propertyName + "' is expression=" + xPath);
    }

    // Compile assembled XPath expression
    XPath path = xPathFactory.newXPath();
    path.setNamespaceContext(ctx);

    if (log.isDebugEnabled()) {
        log.debug("Compiling XPath expression '" + xPath + "' for property '" + propertyName
                + "' using namespace context :" + ctx);
    }

    XPathExpression expr;
    try {
        expr = path.compile(xPath);
    } catch (XPathExpressionException e) {
        String detail = "Error constructing XPath expression from property expression '" + propertyName
                + "' expression '" + xPath + "'";
        if (e.getMessage() != null) {
            throw new EPException(detail + " :" + e.getMessage(), e);
        }
        throw new EPException(detail, e);
    }

    // get type
    SchemaItem item = property.getPropertyTypeSchema(rootComplexElement, eventAdapterService);
    if ((item == null) && (!isDynamic)) {
        return null;
    }

    Class resultType;
    if (!isDynamic) {
        resultType = SchemaUtil.toReturnType(item);
    } else {
        resultType = Node.class;
    }

    FragmentFactory fragmentFactory = null;
    if (isAllowFragment) {
        fragmentFactory = new FragmentFactoryDOMGetter(eventAdapterService, xmlEventType, propertyName);
    }
    return new XPathPropertyGetter(propertyName, xPath, expr, pair.getSecond(), resultType, fragmentFactory);
}