Example usage for org.dom4j XPath setFunctionContext

List of usage examples for org.dom4j XPath setFunctionContext

Introduction

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

Prototype

void setFunctionContext(FunctionContext functionContext);

Source Link

Document

Sets the function context to be used when evaluating XPath expressions

Usage

From source file:hudson.model.Api.java

License:Open Source License

/**
 * Exposes the bean as XML.//from   ww w .ja v a  2  s  .com
 */
public void doXml(StaplerRequest req, StaplerResponse rsp, @QueryParameter String xpath,
        @QueryParameter String wrapper, @QueryParameter String tree, @QueryParameter int depth)
        throws IOException, ServletException {
    setHeaders(rsp);

    String[] excludes = req.getParameterValues("exclude");

    if (xpath == null && excludes == null) {
        // serve the whole thing
        rsp.serveExposedBean(req, bean, Flavor.XML);
        return;
    }

    StringWriter sw = new StringWriter();

    // first write to String
    Model p = MODEL_BUILDER.get(bean.getClass());
    TreePruner pruner = (tree != null) ? new NamedPathPruner(tree) : new ByDepth(1 - depth);
    p.writeTo(bean, pruner, Flavor.XML.createDataWriter(bean, sw));

    // apply XPath
    FilteredFunctionContext functionContext = new FilteredFunctionContext();
    Object result;
    try {
        Document dom = new SAXReader().read(new StringReader(sw.toString()));
        // apply exclusions
        if (excludes != null) {
            for (String exclude : excludes) {
                XPath xExclude = dom.createXPath(exclude);
                xExclude.setFunctionContext(functionContext);
                List<org.dom4j.Node> list = (List<org.dom4j.Node>) xExclude.selectNodes(dom);
                for (org.dom4j.Node n : list) {
                    Element parent = n.getParent();
                    if (parent != null)
                        parent.remove(n);
                }
            }
        }

        if (xpath == null) {
            result = dom;
        } else {
            XPath comp = dom.createXPath(xpath);
            comp.setFunctionContext(functionContext);
            List list = comp.selectNodes(dom);
            if (wrapper != null) {
                Element root = DocumentFactory.getInstance().createElement(wrapper);
                for (Object o : list) {
                    if (o instanceof String) {
                        root.addText(o.toString());
                    } else {
                        root.add(((org.dom4j.Node) o).detach());
                    }
                }
                result = root;
            } else if (list.isEmpty()) {
                rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath));
                return;
            } else if (list.size() > 1) {
                rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size()));
                return;
            } else {
                result = list.get(0);
            }
        }

    } catch (DocumentException e) {
        LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:" + sw, e);
        throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.", e);
    }

    if (isSimpleOutput(result) && !permit(req)) {
        // simple output prohibited
        rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN,
                "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester");
        return;
    }

    // switch to gzipped output
    OutputStream o = rsp.getCompressedOutputStream(req);
    try {
        if (isSimpleOutput(result)) {
            // simple output allowed
            rsp.setContentType("text/plain;charset=UTF-8");
            String text = result instanceof CharacterData ? ((CharacterData) result).getText()
                    : result.toString();
            o.write(text.getBytes("UTF-8"));
            return;
        }

        // otherwise XML
        rsp.setContentType("application/xml;charset=UTF-8");
        new XMLWriter(o).write(result);
    } finally {
        o.close();
    }
}

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);

    // Entity variables here...
    EntityManager entMan = new EntityManager(SecurityAssociation.getUser());
    List<EntityActivity> entRecList = entMan.recordsAllInActivity(activity);
    if (!entRecList.isEmpty()) {
        String entityId = null;//from w w w  .ja va  2  s.c  o m
        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.orbeon.oxf.transformer.xupdate.statement.Utils.java

License:Open Source License

/**
 * Evaluates an XPath expression/* w ww  . ja v  a  2s.  c  om*/
 */
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);
            }/* w ww .  ja  va  2s.co  m*/
        });
    }
}