Search in sources :

Example 1 with BaseXPath

use of org.jaxen.BaseXPath in project pmd by pmd.

the class ViewerModel method evaluateXPathExpression.

/**
 * Evaluates the given XPath expression against the current tree.
 *
 * @param xPath
 *            XPath expression to be evaluated
 * @param evaluator
 *            object which requests the evaluation
 */
public void evaluateXPathExpression(String xPath, Object evaluator) throws ParseException, JaxenException {
    try {
        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.finest("xPath=" + xPath);
            LOGGER.finest("evaluator=" + evaluator);
        }
        XPath xpath = new BaseXPath(xPath, new DocumentNavigator());
        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.finest("xpath=" + xpath);
            LOGGER.finest("rootNode=" + rootNode);
        }
        try {
            evaluationResults = xpath.selectNodes(rootNode);
        } catch (Exception e) {
            LOGGER.finest("selectNodes problem:");
            e.printStackTrace(System.err);
        }
        if (LOGGER.isLoggable(Level.FINEST)) {
            LOGGER.finest("evaluationResults=" + evaluationResults);
        }
        fireViewerModelEvent(new ViewerModelEvent(evaluator, ViewerModelEvent.PATH_EXPRESSION_EVALUATED));
    } catch (JaxenException je) {
        je.printStackTrace(System.err);
        throw je;
    }
}
Also used : BaseXPath(org.jaxen.BaseXPath) XPath(org.jaxen.XPath) BaseXPath(org.jaxen.BaseXPath) JaxenException(org.jaxen.JaxenException) DocumentNavigator(net.sourceforge.pmd.lang.ast.xpath.DocumentNavigator) JaxenException(org.jaxen.JaxenException) ParseException(net.sourceforge.pmd.lang.ast.ParseException)

Example 2 with BaseXPath

use of org.jaxen.BaseXPath in project pmd by pmd.

the class JaxenXPathRuleQuery method createXPath.

private BaseXPath createXPath(final String xpathQueryString, final Navigator navigator) throws JaxenException {
    final BaseXPath xpath = new BaseXPath(xpathQueryString, navigator);
    if (properties.size() > 1) {
        final SimpleVariableContext vc = new SimpleVariableContext();
        for (Entry<PropertyDescriptor<?>, Object> e : properties.entrySet()) {
            final String propName = e.getKey().name();
            if (!"xpath".equals(propName)) {
                final Object value = e.getValue();
                vc.setVariableValue(propName, value != null ? value.toString() : null);
            }
        }
        xpath.setVariableContext(vc);
    }
    return xpath;
}
Also used : PropertyDescriptor(net.sourceforge.pmd.properties.PropertyDescriptor) BaseXPath(org.jaxen.BaseXPath) SimpleVariableContext(org.jaxen.SimpleVariableContext)

Example 3 with BaseXPath

use of org.jaxen.BaseXPath in project pmd by pmd.

the class JaxenXPathRuleQuery method initializeXPathExpression.

private void initializeXPathExpression(final Navigator navigator) throws JaxenException {
    /*
        Attempt to use the RuleChain with this XPath query.

        To do so, the queries should generally look like //TypeA or //TypeA | //TypeB. We will look at the parsed XPath
        AST using the Jaxen APIs to make this determination.

        If the query is not exactly what we are looking for, do not use the
        RuleChain.
        */
    nodeNameToXPaths = new HashMap<>();
    final BaseXPath originalXPath = createXPath(xpath, navigator);
    addQueryToNode(originalXPath, AST_ROOT);
    boolean useRuleChain = true;
    final Deque<Expr> pending = new ArrayDeque<>();
    pending.push(originalXPath.getRootExpr());
    while (!pending.isEmpty()) {
        final Expr node = pending.pop();
        // Need to prove we can handle this part of the query
        boolean valid = false;
        // Must be a LocationPath... that is something like //Type
        if (node instanceof LocationPath) {
            final LocationPath locationPath = (LocationPath) node;
            if (locationPath.isAbsolute()) {
                // Should be at least two steps
                @SuppressWarnings("unchecked") final List<Step> steps = locationPath.getSteps();
                if (steps.size() >= 2) {
                    final Step step1 = steps.get(0);
                    final Step step2 = steps.get(1);
                    // descendant or self axis
                    if (step1 instanceof AllNodeStep && step1.getAxis() == Axis.DESCENDANT_OR_SELF) {
                        // axis.
                        if (step2 instanceof NameStep && step2.getAxis() == Axis.CHILD) {
                            // Construct a new expression that is
                            // appropriate for RuleChain use
                            final XPathFactory xpathFactory = new DefaultXPathFactory();
                            // Instead of an absolute location path, we'll
                            // be using a relative path
                            final LocationPath relativeLocationPath = xpathFactory.createRelativeLocationPath();
                            // The first step will be along the self axis
                            final Step allNodeStep = xpathFactory.createAllNodeStep(Axis.SELF);
                            // Retain all predicates from the original name
                            // step
                            @SuppressWarnings("unchecked") final List<Predicate> predicates = step2.getPredicates();
                            for (Predicate predicate : predicates) {
                                allNodeStep.addPredicate(predicate);
                            }
                            relativeLocationPath.addStep(allNodeStep);
                            // location path
                            for (int i = 2; i < steps.size(); i++) {
                                relativeLocationPath.addStep(steps.get(i));
                            }
                            final BaseXPath xpath = createXPath(relativeLocationPath.getText(), navigator);
                            addQueryToNode(xpath, ((NameStep) step2).getLocalName());
                            valid = true;
                        }
                    }
                }
            }
        } else if (node instanceof UnionExpr) {
            // Or a UnionExpr, that is
            // something like //TypeA |
            // //TypeB
            UnionExpr unionExpr = (UnionExpr) node;
            pending.push(unionExpr.getLHS());
            pending.push(unionExpr.getRHS());
            valid = true;
        }
        if (!valid) {
            useRuleChain = false;
            break;
        }
    }
    if (useRuleChain) {
        // Use the RuleChain for all the nodes extracted from the xpath
        // queries
        super.ruleChainVisits.addAll(nodeNameToXPaths.keySet());
    } else {
        // Use original XPath if we cannot use the RuleChain
        nodeNameToXPaths.clear();
        addQueryToNode(originalXPath, AST_ROOT);
        if (LOG.isLoggable(Level.FINE)) {
            LOG.log(Level.FINE, "Unable to use RuleChain for XPath: " + xpath);
        }
    }
    if (navigator == null) {
        this.initializationStatus = InitializationStatus.PARTIAL;
        // Clear the node data, because we did not have a Navigator
        nodeNameToXPaths = null;
    } else {
        this.initializationStatus = InitializationStatus.FULL;
    }
}
Also used : UnionExpr(org.jaxen.expr.UnionExpr) AllNodeStep(org.jaxen.expr.AllNodeStep) Step(org.jaxen.expr.Step) NameStep(org.jaxen.expr.NameStep) ArrayDeque(java.util.ArrayDeque) Predicate(org.jaxen.expr.Predicate) XPathFactory(org.jaxen.expr.XPathFactory) DefaultXPathFactory(org.jaxen.expr.DefaultXPathFactory) UnionExpr(org.jaxen.expr.UnionExpr) Expr(org.jaxen.expr.Expr) LocationPath(org.jaxen.expr.LocationPath) BaseXPath(org.jaxen.BaseXPath) DefaultXPathFactory(org.jaxen.expr.DefaultXPathFactory) NameStep(org.jaxen.expr.NameStep) AllNodeStep(org.jaxen.expr.AllNodeStep)

Example 4 with BaseXPath

use of org.jaxen.BaseXPath in project freemarker by apache.

the class JaxenXPathSupport method executeQuery.

public TemplateModel executeQuery(Object context, String xpathQuery) throws TemplateModelException {
    try {
        BaseXPath xpath;
        Map<String, BaseXPath> xpathCache = (Map<String, BaseXPath>) XPATH_CACHE_ATTR.get();
        synchronized (xpathCache) {
            xpath = xpathCache.get(xpathQuery);
            if (xpath == null) {
                xpath = new BaseXPath(xpathQuery, FM_DOM_NAVIGATOR);
                xpath.setNamespaceContext(customNamespaceContext);
                xpath.setFunctionContext(FM_FUNCTION_CONTEXT);
                xpath.setVariableContext(FM_VARIABLE_CONTEXT);
                xpathCache.put(xpathQuery, xpath);
            }
        }
        List result = xpath.selectNodes(context != null ? context : EMPTY_ARRAYLIST);
        if (result.size() == 1) {
            // [2.4] Use the proper object wrapper (argument in 2.4)
            return ObjectWrapper.DEFAULT_WRAPPER.wrap(result.get(0));
        }
        NodeListModel nlm = new NodeListModel(result, null);
        nlm.xpathSupport = this;
        return nlm;
    } catch (UndeclaredThrowableException e) {
        Throwable t = e.getUndeclaredThrowable();
        if (t instanceof TemplateModelException) {
            throw (TemplateModelException) t;
        }
        throw e;
    } catch (JaxenException je) {
        throw new TemplateModelException(je);
    }
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) BaseXPath(org.jaxen.BaseXPath) UndeclaredThrowableException(freemarker.template.utility.UndeclaredThrowableException) JaxenException(org.jaxen.JaxenException) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with BaseXPath

use of org.jaxen.BaseXPath in project pmd by pmd.

the class DocumentNavigatorTest method testXPath2.

@Test
public void testXPath2() throws JaxenException {
    BaseXPath xPath = new BaseXPath(".//*", new DocumentNavigator());
    List<?> matches = xPath.selectNodes(rule.importDeclaration);
    assertEquals(1, matches.size());
}
Also used : BaseXPath(org.jaxen.BaseXPath) DocumentNavigator(net.sourceforge.pmd.lang.ast.xpath.DocumentNavigator) Test(org.junit.Test)

Aggregations

BaseXPath (org.jaxen.BaseXPath)8 DocumentNavigator (net.sourceforge.pmd.lang.ast.xpath.DocumentNavigator)3 LocationPath (org.jaxen.expr.LocationPath)3 JaxenException (org.jaxen.JaxenException)2 DocumentNavigator (org.jaxen.dom.DocumentNavigator)2 Expr (org.jaxen.expr.Expr)2 NameStep (org.jaxen.expr.NameStep)2 Step (org.jaxen.expr.Step)2 Test (org.junit.Test)2 TemplateModelException (freemarker.template.TemplateModelException)1 UndeclaredThrowableException (freemarker.template.utility.UndeclaredThrowableException)1 ArrayDeque (java.util.ArrayDeque)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 ParseException (net.sourceforge.pmd.lang.ast.ParseException)1 PropertyDescriptor (net.sourceforge.pmd.properties.PropertyDescriptor)1 SimpleVariableContext (org.jaxen.SimpleVariableContext)1 XPath (org.jaxen.XPath)1