Example usage for org.apache.commons.jxpath JXPathContext iteratePointers

List of usage examples for org.apache.commons.jxpath JXPathContext iteratePointers

Introduction

In this page you can find the example usage for org.apache.commons.jxpath JXPathContext iteratePointers.

Prototype

public abstract Iterator iteratePointers(String xpath);

Source Link

Document

Traverses the xpath and returns an Iterator of Pointers.

Usage

From source file:org.chiba.xml.xforms.config.Config.java

/**
 * Read custom instance serializer that are used by AbstractConnector.
 *
 * @param configContext  the JXPath context holding the configuration.
 * @param sectionPath    the context relative path to the section.
 * @param scheme         the name of the attribute holding the scheme.
 * @param method         the name of the attribute holding the method.
 * @param mediatype      the name of the attribute holding the mediatype.
 * @param serializerClass the name of the attribute holding the InstanceSerializer implementation.
 * @return the specified configuration section in a hash map.
 * @throws Exception if any error occured during configuration loading.
 *//*from  w w  w.ja va2s. co m*/
private InstanceSerializerMap loadSerializer(JXPathContext configContext, String sectionPath, String scheme,
        String method, String mediatype, String serializerClass) throws Exception {
    InstanceSerializerMap map = new InstanceSerializerMap();
    Iterator iterator = configContext.iteratePointers(sectionPath);

    while (iterator.hasNext()) {
        Pointer pointer = (Pointer) iterator.next();
        Element element = (Element) pointer.getNode();

        try {

            String schemeVal = element.getAttribute(scheme);
            schemeVal = ("".equals(schemeVal)) ? "*" : schemeVal;

            String methodVal = element.getAttribute(method);
            methodVal = ("".equals(methodVal)) ? "*" : methodVal;

            String mediatypeVal = element.getAttribute(mediatype);
            mediatypeVal = ("".equals(mediatypeVal)) ? "*" : mediatypeVal;

            String classVal = element.getAttribute(serializerClass);
            if (classVal == null) {
                continue;
            }

            InstanceSerializer serializer = (InstanceSerializer) Class.forName(classVal).newInstance();

            map.registerSerializer(schemeVal, methodVal, mediatypeVal, serializer);

        } catch (Exception e) {
            // silently ignore invalid references ...
            LOGGER.error("registerSerializer(\"" + scheme + "\",\"" + method + "\"," + mediatype + "\",\""
                    + serializerClass + "\") failed: " + e.getMessage(), e);
        }
    }

    return map;
}

From source file:org.chiba.xml.xforms.config.Config.java

private HashMap loadExtensionFunctions(JXPathContext configContext, String sectionPath) {
    HashMap map = new HashMap();
    Iterator iterator = configContext.iteratePointers(sectionPath);

    while (iterator.hasNext()) {
        Pointer pointer = (Pointer) iterator.next();
        Element element = (Element) pointer.getNode();

        String namespace = element.getAttribute("namespace");
        namespace = ("".equals(namespace)) ? null : namespace;

        //String prefix = element.getAttribute("prefix");
        //prefix = ("".equals(prefix)) ? null : prefix;

        String function = element.getAttribute("name");
        function = ("".equals(function)) ? null : function;

        String functionClass = element.getAttribute("class");
        functionClass = ("".equals(functionClass)) ? null : functionClass;

        String key = (namespace == null) ? function : namespace + ((function == null) ? "" : " " + function);
        //String prefixKey = (prefix == null) ? function : prefix + ((function == null) ? "" : " " + function);

        if ((function != null) && (functionClass != null)) {
            String javaFunction = element.getAttribute("java-name");
            javaFunction = ((javaFunction == null) || "".equalsIgnoreCase(javaFunction)) ? function
                    : javaFunction;/*from w  w w.  j a  va  2  s  .  c  om*/
            String[] classFunction = new String[] { functionClass, javaFunction };

            if (key != null) {
                map.put(key, classFunction);
            }
            //if (prefixKey != null) {
            //    map.put(prefixKey, classFunction);
            //}
        }
    }

    return map;
}

From source file:org.chiba.xml.xforms.config.DefaultConfig.java

private HashMap loadExtensionFunctions(JXPathContext configContext, String sectionPath) {
    HashMap map = new HashMap();
    Iterator iterator = configContext.iteratePointers(sectionPath);

    while (iterator.hasNext()) {
        Pointer pointer = (Pointer) iterator.next();
        Element element = (Element) pointer.getNode();

        String namespace = element.getAttribute("namespace");
        namespace = ("".equals(namespace)) ? null : namespace;

        //String prefix = element.getXFormsAttribute("prefix");
        //prefix = ("".equals(prefix)) ? null : prefix;

        String function = element.getAttribute("name");
        function = ("".equals(function)) ? null : function;

        String functionClass = element.getAttribute("class");
        functionClass = ("".equals(functionClass)) ? null : functionClass;

        String key = (namespace == null) ? function : namespace + ((function == null) ? "" : " " + function);
        //String prefixKey = (prefix == null) ? function : prefix +
        // ((function == null) ? "" : " " + function);

        if ((function != null) && (functionClass != null)) {
            String javaFunction = element.getAttribute("java-name");
            javaFunction = ((javaFunction == null) || "".equalsIgnoreCase(javaFunction)) ? function
                    : javaFunction;//  www  .j  a v a 2 s.  co  m
            String[] classFunction = new String[] { functionClass, javaFunction };

            if (key != null) {
                map.put(key, classFunction);
            }
            //if (prefixKey != null) {
            //    map.put(prefixKey, classFunction);
            //}
        }
    }

    return map;
}

From source file:org.chiba.xml.xforms.config.DefaultConfig.java

private HashMap loadCustomElements(JXPathContext configContext, String sectionPath) {
    HashMap map = new HashMap();
    Iterator iterator = configContext.iteratePointers(sectionPath);

    while (iterator.hasNext()) {
        Pointer pointer = (Pointer) iterator.next();
        Element element = (Element) pointer.getNode();

        String namespace = element.getAttribute("namespace");
        namespace = ("".equals(namespace)) ? null : namespace;

        String elementName = element.getAttribute("name");
        elementName = ("".equals(elementName)) ? null : elementName;

        String elementClass = element.getAttribute("class");
        elementClass = ("".equals(elementClass)) ? null : elementClass;

        String key = (namespace == null) ? elementName
                : namespace + ((elementName == null) ? "" : ":" + elementName);

        if ((elementName != null) && (elementClass != null)) {
            if (key != null) {
                map.put(key, elementClass);
            }/*from   w  w w.j a v  a  2s.  c  o m*/
        }
    }

    return map;
}

From source file:org.chiba.xml.xforms.constraints.DependencyGraph.java

/**
 * determines which nodes are referenced by given xpath expression and returns them as nodes.
 *
 * @param xpath - the xpath expression under examination
 * @return a list with nodes referenced in given xpath
 *///from   w w w.  ja v a  2 s .c  o  m
public Vector getXPathRefNodes(JXPathContext relativeContext, String xpath) {
    ReferenceFinder referenceFinder = new ReferenceFinder();
    Parser.parseExpression(xpath, referenceFinder);

    List pathes = referenceFinder.getLocationPathes();
    Vector refNodes = new Vector();

    for (int i = 0; i < pathes.size(); i++) {
        String refPath = pathes.get(i).toString();
        Instance instance = (Instance) relativeContext.getParentContext().getContextBean();
        JXPathContext context = relativeContext;

        if (PathUtil.hasInstanceFunction(refPath)) {
            String instanceId = PathUtil.getInstanceId(instance.getModel(), refPath);

            // use container for instance lookup to allow cross-model references
            instance = (Instance) instance.getModel().getContainer().lookup(instanceId);
            context = instance.getInstanceContext();
        }

        // iterate all referenced nodes
        Iterator iterator = context.iteratePointers(refPath);

        while (iterator.hasNext()) {
            Pointer localPointer = (Pointer) iterator.next();
            //                Object node = localPointer.getNode();
            //                if (node instanceof Pointer) {
            //                    localPointer = (Pointer) node;
            //                }

            String realPath = localPointer.asPath();
            LocalValue localValue = instance.getModelItem(realPath);

            if (localValue != null) {
                // add *existing* reference node
                refNodes.add(localValue.getNode());
            }
        }
    }

    return refNodes;
}

From source file:org.chiba.xml.xforms.constraints.Validator.java

/**
 * Validates the specified instance data node and its descendants.
 *
 * @param instance the instance to be validated.
 * @param path an xpath denoting an arbitrary subtre of the instance.
 * @return <code>true</code> if all relevant instance data nodes are valid
 *         regarding in terms of their <code>constraint</code> and
 *         <code>required</code> properties, otherwise <code>false</code>.
 *//*from  w  ww.  j ava  2  s .  c o m*/
public boolean validate(Instance instance, String path) {
    // initialize
    boolean result = true;
    String expressionPath = path;

    if (!path.endsWith("/")) {
        expressionPath = expressionPath + "/";
    }

    // set expression path to contain the specified path and its subtree
    expressionPath = expressionPath + "descendant-or-self::*";

    // evaluate expression path
    JXPathContext context = instance.getInstanceContext();
    Iterator iterator = context.iteratePointers(expressionPath);
    Pointer locationPointer;
    String locationPath;

    while (iterator.hasNext()) {
        locationPointer = (Pointer) iterator.next();
        locationPath = locationPointer.asPath();
        Element element = (Element) locationPointer.getNode();

        // validate element node against type
        String type = element.getAttributeNS(NamespaceCtx.XMLSCHEMA_INSTANCE_NS, "type");
        result &= validateNode(instance, locationPath, type);

        // handle attributes explicitely since JXPath has
        // seriuos problems with namespaced attributes
        NamedNodeMap attributes = element.getAttributes();

        for (int index = 0; index < attributes.getLength(); index++) {
            Attr attr = (Attr) attributes.item(index);

            if (isInstanceAttribute(attr)) {
                // validate attribute node
                result &= validateNode(instance, locationPath + "/@" + attr.getNodeName());
            }
        }
    }

    return result;
}

From source file:org.chiba.xml.xforms.Instance.java

private Pointer getLastPointer(JXPathContext jxPathContext, String xpath) {
    // this is ugly and expensive, but needed as long as
    // jxpath has problems with last()
    Pointer finalPointer = null;//from ww  w.  j  av  a  2 s  . c  om
    Iterator members = jxPathContext.iteratePointers(xpath);
    while (members.hasNext()) {
        finalPointer = (Pointer) members.next();
    }

    return finalPointer;
}

From source file:org.dcm4chee.xds2.registry.ws.XDSPersistenceWrapper.java

/**
 * Correct metadata parameters to conform to XDS specification.
 * Replace non-conformant ids to uuids, update references, check classification scemes, nodes, etc
 *//*from w w  w . j  a v  a 2  s.c  om*/
void checkAndCorrectSubmitObjectsRequest(SubmitObjectsRequest req) throws XDSException {

    // TODO: DB_RESTRUCT - CODE INSPECTION - is it correct to replace ids with uuids for ALL identifiables, not only ROs?

    JXPathContext requestContext = JXPathContext.newContext(req);

    ////// Pre-process - move detached classifications from registryObjectList into corresponding objects

    Iterator<JAXBElement<? extends IdentifiableType>> objectListIterator = req.getRegistryObjectList()
            .getIdentifiable().iterator();
    while (objectListIterator.hasNext()) {

        JAXBElement<? extends IdentifiableType> elem = objectListIterator.next();

        /// filter Classifications only
        if (!ClassificationType.class.isAssignableFrom(elem.getValue().getClass()))
            continue;

        /// find referenced object and add the classification to the referenced object 
        ClassificationType cl = (ClassificationType) elem.getValue();
        // this xpath return all nodes in the tree with the specified id 
        Iterator referencedObjs = (Iterator) requestContext
                .iteratePointers(String.format("//*[id = '%s']", cl.getClassifiedObject()));
        try {
            Object o = ((Pointer) referencedObjs.next()).getValue();

            if (!RegistryObjectType.class.isAssignableFrom(o.getClass()))
                throw new XDSException(XDSException.XDS_ERR_REGISTRY_METADATA_ERROR,
                        "Classification " + cl.getId() + " classifies object " + cl.getClassifiedObject()
                                + " which is not a Registry Object",
                        null);
            RegistryObjectType registryObj = (RegistryObjectType) o;

            // add this classification to the classification list
            registryObj.getClassification().add(cl);

        } catch (NoSuchElementException e) {
            throw new XDSException(XDSException.XDS_ERR_REGISTRY_METADATA_ERROR,
                    "Classified object " + cl.getClassifiedObject()
                            + " not found in the request (Classification " + cl.getId() + " )",
                    null);
        }
        // there must be a single node with referenced id
        if (referencedObjs.hasNext())
            throw new XDSException(
                    XDSException.XDS_ERR_REGISTRY_METADATA_ERROR, "Classification " + cl.getId()
                            + " references an object " + cl.getClassifiedObject() + " that is not unique",
                    null);

        /// remove the detached classification from the list
        objectListIterator.remove();
    }

    ////// First run - replace non-uuid IDs with UUIDs for all identifiables, included nested ones

    // Use //id xpath to find all id fields of identifiables in the request
    Iterator ids = (Iterator) requestContext.iteratePointers("//id");

    while (ids.hasNext()) {

        Pointer p = (Pointer) ids.next();
        String oldId = (String) p.getValue();
        String newIdUUID = oldId;

        if (oldId == null)
            continue;

        // Replace non-UUID id with a generated UUID
        if (!oldId.startsWith("urn:")) {
            newIdUUID = "urn:uuid:" + UUID.randomUUID().toString();
            p.setValue(newIdUUID);
            log.debug("Replacing id {} with uuid {}", oldId, newIdUUID);
        }

        newUUIDs.put(oldId, newIdUUID);
    }

    ////// Second run - perform check and correction recursively
    for (JAXBElement<? extends IdentifiableType> elem : req.getRegistryObjectList().getIdentifiable()) {

        // filter RegistryObjects only
        if (!RegistryObjectType.class.isAssignableFrom(elem.getValue().getClass()))
            continue;
        RegistryObjectType ro = (RegistryObjectType) elem.getValue();

        checkAndCorrectMetadata(ro);
    }
}

From source file:org.firesoa.common.jxpath.JXPathTestCase.java

protected void assertXPathPointerIterator(JXPathContext ctx, String xpath, Collection expected) {
    Collection actual;//from  www.ja  v a2 s .  co  m
    if (expected instanceof List) {
        actual = new ArrayList();
    } else {
        actual = new HashSet();
    }
    Iterator it = ctx.iteratePointers(xpath);
    while (it.hasNext()) {
        Pointer pointer = (Pointer) it.next();
        actual.add(pointer.toString());
    }
    assertEquals("Evaluating pointer iterator <" + xpath + ">", expected, actual);
}

From source file:org.lilyproject.runtime.conf.test.JXPathTest.java

public void testIt() throws Exception {
    String path = "jxpathconf.xml";
    Conf conf = XmlConfBuilder.build(getClass().getResourceAsStream(path), path);

    JXPathContext context = JXPathContext.newContext(conf);

    assertEquals("Venus", context.getValue("planet"));
    assertEquals("Mars", context.getValue("@planet"));

    assertEquals("5", context.getValue("/things/thing[@name='Book']/@quantity"));
    assertEquals("50", context.getValue("/things/thing[@name='Bicycle']/@quantity"));

    assertEquals("Book", context.getValue("/things/thing[1]/@name"));

    assertEquals("Bicycle", context.getValue("/things/thing[2]/@name"));
    assertEquals("Bicycle", context.getValue("/things/thing[last()]/@name"));

    List<Conf> things = new ArrayList<Conf>();
    Iterator thingsIt = context.iteratePointers("things/thing[position() < 3]");
    while (thingsIt.hasNext()) {
        Pointer pointer = (Pointer) thingsIt.next();
        assertTrue(pointer.getNode() instanceof Conf);
        things.add((Conf) pointer.getNode());
    }// w  w w  . j av  a 2 s .  c  o m
    assertEquals(2, things.size());
}