Example usage for org.dom4j XPath setVariableContext

List of usage examples for org.dom4j XPath setVariableContext

Introduction

In this page you can find the example usage for org.dom4j XPath setVariableContext.

Prototype

void setVariableContext(VariableContext variableContext);

Source Link

Document

Sets the variable context to be used when evaluating XPath expressions

Usage

From source file:itensil.workflow.activities.rules.XPathConditionEval.java

License:Open Source License

protected XPath getXPath(String exp, Document datDoc, Activity activity) {
    XPath xp = datDoc.createXPath(exp);
    XPathFunctionContext xpfc = new XPathFunctionContext(false);
    xpfc.registerFunction(null, "sub-activities", new XPFuncSubActivities(activity));
    xpfc.registerFunction(null, "is-sub", new XPFuncIsSub(activity));
    xpfc.registerFunction(null, "parent", new XPFuncParent(activity));
    RulesXPathFunctions.initFunctionContext(xpfc, this, activity);
    xp.setFunctionContext(xpfc);/*from ww  w .  jav a2s . c  o  m*/

    // Entity variables here...
    EntityManager entMan = new EntityManager(SecurityAssociation.getUser());
    List<EntityActivity> entRecList = entMan.recordsAllInActivity(activity);
    if (!entRecList.isEmpty()) {
        String entityId = null;
        String entName = null;

        SimpleVariableContext svc = new SimpleVariableContext();
        xp.setVariableContext(svc);
        HashMap<String, ArrayList<EntityLazyRecordRoot>> entMap = new HashMap<String, ArrayList<EntityLazyRecordRoot>>();
        for (EntityActivity entAct : entMan.recordsAllInActivity(activity)) {
            try {
                if (!entAct.getEntityId().equals(entityId)) {
                    entityId = entAct.getEntityId();
                    entName = UriHelper.name(RepositoryHelper.getNodeById(entityId, false).getUri());
                }
                String relName = XMLWriter.nmTokenFilter(entAct.getName());
                ArrayList<EntityLazyRecordRoot> ls = entMap.get(relName);
                if (ls == null) {
                    ls = new ArrayList<EntityLazyRecordRoot>();
                    entMap.put(relName, ls);
                }
                ls.add(new EntityLazyRecordRoot(entMan, entName, String.valueOf(entAct.getRecordId()),
                        relName));

            } catch (Exception ex) {
                logger.warn("Entity rules problem", ex);
            }
        }

        for (Map.Entry<String, ArrayList<EntityLazyRecordRoot>> nmList : entMap.entrySet()) {
            ArrayList ls = nmList.getValue();
            svc.setVariableValue(nmList.getKey(), ls);
        }
    }

    return xp;
}

From source file:org.apache.taglibs.xtags.xpath.AddTag.java

License:Apache License

/** A factory method to create new XPath instances */
protected XPath createXPath(String xpathExpression) {
    XPath xpath = getDocumentFactory().createXPath(xpathExpression);
    xpath.setVariableContext(JspVariableContext.getInstance(pageContext));
    return xpath;
}

From source file:org.danann.cernunnos.xml.SingleNodePhrase.java

License:Apache License

public Object evaluate(TaskRequest req, TaskResponse res) {

    Node src = (Node) source.evaluate(req, res);
    final String xpathExpresion = (String) this.xpath.evaluate(req, res);
    final XPath xpath = this.xpathCache.getCachedObject(req, res, xpathExpresion, XPathCacheFactory.INSTANCE);
    try {/*from   w ww .  j  av a2 s .c o  m*/
        xpath.setVariableContext(new RequestVariableContext(req));
        return xpath.selectSingleNode(src);
    } finally {
        xpath.setVariableContext(null);
    }
}

From source file:org.danann.cernunnos.xml.ValueOfPhrase.java

License:Apache License

public Object evaluate(TaskRequest req, TaskResponse res) {

    Node src = (Node) source.evaluate(req, res);
    final String xpathExpresion = (String) expression.evaluate(req, res);
    final XPath xpath = this.xpathCache.getCachedObject(req, res, xpathExpresion, XPathCacheFactory.INSTANCE);
    try {/*w ww.  j  a va  2s.com*/
        xpath.setVariableContext(new RequestVariableContext(req));
        return xpath.valueOf(src);
    } finally {
        xpath.setVariableContext(null);
    }

}

From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java

License:Open Source License

/**
 * Evaluates an XPath expression/*from   ww w.j  a  va2s. c o  m*/
 */
public static Object evaluate(final URIResolver uriResolver, Object context,
        final VariableContextImpl variableContext, final DocumentContext documentContext,
        final LocationData locationData, String select, NamespaceContext namespaceContext) {
    FunctionContext functionContext = new FunctionContext() {
        public org.jaxen.Function getFunction(final String namespaceURI, final String prefix,
                final String localName) {

            // Override document() and doc()
            if (/*namespaceURI == null &&*/ ("document".equals(localName) || "doc".equals(localName))) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            String url = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                            Document result = documentContext.getDocument(url);
                            if (result == null) {
                                Source source = uriResolver.resolve(url, locationData.getSystemID());
                                if (!(source instanceof SAXSource))
                                    throw new ValidationException("Unsupported source type", locationData);
                                XMLReader xmlReader = ((SAXSource) source).getXMLReader();
                                LocationSAXContentHandler contentHandler = new LocationSAXContentHandler();
                                xmlReader.setContentHandler(contentHandler);
                                xmlReader.parse(new InputSource());
                                result = contentHandler.getDocument();
                                documentContext.addDocument(url, result);
                            }
                            return result;
                        } catch (Exception e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "get-namespace-uri-for-prefix".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        String prefix = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                        Element element = null;
                        if (args.get(1) instanceof List) {
                            List list = (List) args.get(1);
                            if (list.size() == 1)
                                element = (Element) list.get(0);
                        } else if (args.get(1) instanceof Element) {
                            element = (Element) args.get(1);
                        }
                        if (element == null)
                            throw new ValidationException("An element is expected as the second argument "
                                    + "in get-namespace-uri-for-prefix()", locationData);
                        return element.getNamespaceForPrefix(prefix);
                    }
                };
            } else if (/*namespaceURI == null &&*/ "distinct-values".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        List originalList = args.get(0) instanceof List ? (List) args.get(0)
                                : Collections.singletonList(args.get(0));
                        List resultList = new ArrayList();
                        XPath stringXPath = Dom4jUtils.createXPath("string(.)");
                        for (Iterator i = originalList.iterator(); i.hasNext();) {
                            Object item = (Object) i.next();
                            String itemString = (String) stringXPath.evaluate(item);
                            if (!resultList.contains(itemString))
                                resultList.add(itemString);
                        }
                        return resultList;
                    }
                };
            } else if (/*namespaceURI == null &&*/ "evaluate".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            if (args.size() != 3) {
                                try {
                                    return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix,
                                            localName);
                                } catch (UnresolvableException e) {
                                    throw new ValidationException(e, locationData);
                                }
                            } else {
                                String xpathString = (String) Dom4jUtils.createXPath("string(.)")
                                        .evaluate(args.get(0));
                                XPath xpath = Dom4jUtils.createXPath(xpathString);
                                Map namespaceURIs = new HashMap();
                                List namespaces = (List) args.get(1);
                                for (Iterator i = namespaces.iterator(); i.hasNext();) {
                                    org.dom4j.Namespace namespace = (org.dom4j.Namespace) i.next();
                                    namespaceURIs.put(namespace.getPrefix(), namespace.getURI());
                                }
                                xpath.setNamespaceURIs(namespaceURIs);
                                return xpath.evaluate(args.get(2));
                            }
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "tokenize".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            String input = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                            String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1));
                            List result = new ArrayList();
                            while (input.length() != 0) {
                                int position = input.indexOf(pattern);
                                if (position != -1) {
                                    result.add(input.substring(0, position));
                                    input = input.substring(position + 1);
                                } else {
                                    result.add(input);
                                    input = "";
                                }
                            }
                            return result;
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "string-join".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            List strings = (List) args.get(0);
                            String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1));
                            StringBuilder result = new StringBuilder();
                            boolean isFirst = true;
                            for (Iterator i = strings.iterator(); i.hasNext();) {
                                if (!isFirst)
                                    result.append(pattern);
                                else
                                    isFirst = false;
                                String item = (String) (String) Dom4jUtils.createXPath("string(.)")
                                        .evaluate(i.next());
                                result.append(item);
                            }
                            return result.toString();
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "reverse".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            List result = new ArrayList((List) args.get(0));
                            Collections.reverse(result);
                            return result;
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else {
                try {
                    // Go through standard XPath functions
                    return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix, localName);
                } catch (UnresolvableException e) {
                    // User-defined function
                    try {
                        final Closure closure = findClosure(
                                variableContext.getVariableValue(namespaceURI, prefix, localName));
                        if (closure == null)
                            throw new ValidationException(
                                    "'" + qualifiedName(prefix, localName) + "' is not a function",
                                    locationData);
                        return new org.jaxen.Function() {
                            public Object call(Context context, List args) {
                                return closure.execute(args);
                            }
                        };
                    } catch (UnresolvableException e2) {
                        throw new ValidationException("Cannot invoke function '"
                                + qualifiedName(prefix, localName) + "', no such function", locationData);
                    }
                }
            }
        }

        private Closure findClosure(Object xpathObject) {
            if (xpathObject instanceof Closure) {
                return (Closure) xpathObject;
            } else if (xpathObject instanceof List) {
                for (Iterator i = ((List) xpathObject).iterator(); i.hasNext();) {
                    Closure closure = findClosure(i.next());
                    if (closure != null)
                        return closure;
                }
                return null;
            } else {
                return null;
            }
        }
    };

    try {
        // Create XPath
        XPath xpath = Dom4jUtils.createXPath(select);

        // Set variable, namespace, and function context
        if (context instanceof Context) {
            // Create a new context, as Jaxen may modify the current node in the context (is this a bug?)
            Context currentContext = (Context) context;
            Context newContext = new Context(new ContextSupport(namespaceContext, functionContext,
                    variableContext, DocumentNavigator.getInstance()));
            newContext.setNodeSet(currentContext.getNodeSet());
            newContext.setSize(currentContext.getSize());
            newContext.setPosition(currentContext.getPosition());
            context = newContext;
        } else {
            xpath.setVariableContext(variableContext);
            xpath.setNamespaceContext(namespaceContext);
            xpath.setFunctionContext(functionContext);
        }

        // Execute XPath
        return xpath.evaluate(context);
    } catch (Exception e) {
        throw new ValidationException(e, locationData);
    }
}

From source file:org.orbeon.oxf.xml.XPathUtils.java

License:Open Source License

private static void hookupPath(org.dom4j.XPath path, Map prefixes, VariableContext variableContext,
        FunctionContext functionContext) {
    if (prefixes != null)
        path.setNamespaceContext(new SimpleNamespaceContext(prefixes));
    if (variableContext != null)
        path.setVariableContext(variableContext);
    if (functionContext != null) {
        final FunctionContext _functionContext = functionContext;
        path.setFunctionContext(new FunctionContext() {
            public Function getFunction(String namespaceURI, String prefix, String localName)
                    throws UnresolvableException {

                Function f = _functionContext.getFunction(namespaceURI, prefix, localName);
                if (f != null)
                    return f;
                else
                    return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix, localName);
            }/*from  w w  w  .  ja  v  a2s  .  c o m*/
        });
    }
}