Example usage for org.dom4j XPath selectSingleNode

List of usage examples for org.dom4j XPath selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(Object context);

Source Link

Document

selectSingleNode evaluates this XPath expression on the given Node or List of Node s and returns the result as a single Node instance.

Usage

From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessage.java

License:Open Source License

/**
 * Gets a list of MessageIndex//from   ww  w . j  a  va2 s .c o m
 * returned from the XPath
 *
 * @param location Xpath to evaluate
 * @return The List of Node
 */
@SuppressWarnings("unchecked")
public Message getPart(Object location) throws MessageAccessException, MessageParseException {
    if (!(location instanceof XPath)) {
        throw new MessageAccessException("Only XPath location's are supported for accessing XMLMessage parts - "
                + "received: " + location.getClass());
    }
    XPath xpath = (XPath) location;

    String key = GET_PART_KEY_PREFIX + xpath.getText();
    if (getCache().containsKey(key)) {
        return (Message) getCache().get(key);
    } else {
        Node result = xpath.selectSingleNode(getDocument());
        Message indexedResult = new XMLMessageFactory().build(result, true);
        getCache().put(key, indexedResult);
        return indexedResult;
    }
}

From source file:org.infoglue.cms.util.dom.DOMBuilder.java

License:Open Source License

/**
 * A helper method to get nodes that has a namespace.
 *///from w  w w  . ja v a2s. c  om

public Node selectSingleNode(Node contextNode, String xpathExpression, String namespaceName,
        String namespaceValue) {
    Map namespaces = new HashMap();
    namespaces.put(namespaceName, namespaceValue);
    org.dom4j.XPath xpath = contextNode.createXPath(xpathExpression);
    xpath.setNamespaceURIs(namespaces);
    return xpath.selectSingleNode(contextNode);
}

From source file:org.infoglue.igide.editor.IGMultiPageEditor.java

License:Open Source License

/**
 * Saves the multi-page editor's document.
 *///from ww w.j av a  2s. c  o m
public void doSave(IProgressMonitor monitor) {
    Logger.logConsole("YES - doSave: " + monitor + ":" + isReloadCMSPushCall);
    saving = true;
    boolean dirtyflag = isDirty();
    Utils.getMonitor(monitor).beginTask("Saving content to CMS", 100);

    for (int i = 0; i < getPageCount(); i++) {
        IEditorPart editor = getEditor(i);
        editor.doSave(monitor);

    }

    Logger.logConsole("Saved each editor part...");
    Utils.getMonitor(monitor).worked(25);
    InfoglueEditorInput input = getInfoglueEditorInput();
    Logger.logConsole("input: " + input);
    input.getContent().doSave(monitor);
    System.out.println("isReloadCMSPushCall: " + isReloadCMSPushCall);
    if (!isReloadCMSPushCall)
        try {
            Logger.logConsole("saveLocalXML called");
            ContentVersion cv = InfoglueCMS.getProjectContentVersion(
                    input.getContent().getNode().getProject().getName(), input.getContent().getNode().getId());

            SAXReader reader = new SAXReader();

            Document document = reader.read(new StringReader(cv.getValue()));
            Map<String, String> namespaceUris = new HashMap<String, String>();
            namespaceUris.put("art", "x-schema:ArticleSchema.xml");

            XPath xPath = DocumentHelper.createXPath("/art:article/art:attributes");
            xPath.setNamespaceURIs(namespaceUris);

            Element attributesNode = (Element) xPath.selectSingleNode(document); //(Element)document.selectSingleNode("/article/attributes");

            @SuppressWarnings("unchecked")
            List<Element> attributes = attributesNode.elements();//document.selectNodes("//attributes/*");

            EditableInfoglueContent content = input.getContent();
            final ArrayList<String> contentAttributes = content.getAttributesOrder();

            Map<String, Element> attributeMap = new HashMap<String, Element>();

            // This loop remove elements from the DOM element
            for (Element attribute : attributes) {
                // DOM4j will shorten empty attributes, which is not good for InfoGlue
                if ("".equals(attribute.getText())) {
                    attribute.clearContent();
                    attribute.addCDATA("");
                }

                if (attributeMap.containsKey(attribute.getName())) {
                    Logger.logConsole("Found duplicate attribute. Removing it. Name: " + attribute.getName());
                    attributesNode.remove(attribute);
                } else {
                    String attributeName = attribute.getName();
                    if (contentAttributes.contains(attributeName)) {
                        attributeMap.put(attributeName, attribute);
                    } else if (!"IGAuthorFullName".equals(attributeName)
                            && !"IGAuthorEmail".equals(attributeName)) {
                        Logger.logConsole(
                                "Found attribute in version that is not in the content type. Removing. Name: "
                                        + attributeName);
                        attributesNode.remove(attribute);
                    }
                }
            }

            // This loop add elements to the DOM element
            for (int i = 0; i < getPageCount(); i++) {
                IEditorPart editor = getEditor(i);
                editor.doSave(monitor);
                IEditorInput editorInput = editor.getEditorInput();
                AttributeEditorInput attributeInput = null;
                if (editorInput instanceof AttributeEditorInput) {
                    attributeInput = (AttributeEditorInput) editorInput;
                    ContentTypeAttribute cta = attributeInput.getAttribute();
                    Element attributeNode = attributeMap.get(cta.getName());
                    if (attributeNode == null) {
                        Logger.logConsole("Found no attribute for editor, name: " + cta.getName());
                        Element attributeElement = attributesNode.addElement(cta.getName());
                        attributeElement.clearContent();
                        attributeElement.addCDATA(cta.getValue());
                    } else {
                        System.out.println("Setting value: " + cta.getValue() + " on node: " + cta.getName());
                        attributeNode.clearContent();
                        attributeNode.addCDATA(cta.getValue());
                    }
                }
            }

            // Sort the attributes
            attributes = (List<Element>) attributesNode.elements();
            Collections.sort(attributes, new Comparator<Element>() {
                @Override
                public int compare(Element element1, Element element2) {
                    int index1 = contentAttributes.indexOf(element1);
                    int index2 = contentAttributes.indexOf(element2);

                    if (index1 != -1 && index2 != -1) {
                        return index1 - index2;
                    } else if (index1 == -1 && index2 != -1) {
                        return 1;
                    } else if (index1 != -1 && index2 == -1) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });

            // Re-set the attributes after manipulation and sorting
            attributesNode.setContent(attributes);

            cv.setValue(document.asXML());

            InfoglueCMS.saveLocalXML(input.getContent().getNode(), cv);
            Logger.logConsole((new StringBuilder("Part in doSave:")).append(cv.getValue().substring(113, 200))
                    .toString());
        } catch (Exception e) {
            Logger.logConsole("Error in saveLocal");
            System.out.println("Exception: " + e.getMessage() + ", class: " + e.getClass());
            e.printStackTrace();
        }
    Utils.getMonitor(monitor).worked(100);
    Utils.getMonitor(monitor).done();
    saving = false;
}

From source file:org.jbpm.jpdl.xml.AbstractXmlTestCase.java

License:Open Source License

static Element toXmlAndParse(ProcessDefinition processDefinition, String xpathExpression, String namespace)
        throws Exception {
    Element element = toXmlAndParseWithNamespace(processDefinition);
    XPath xpath = DocumentHelper.createXPath(xpathExpression);
    HashMap m = new HashMap();
    m.put("", namespace);

    xpath.setNamespaceURIs(m);//  w  w  w  .ja va 2 s.  c  o m

    return (Element) xpath.selectSingleNode(element);
}

From source file:org.olat.fileresource.types.ImsCPFileResource.java

License:Apache License

/**
 * Check for title and at least one resource.
 * //from   ww w  .j ava  2s .c  o  m
 * @param unzippedDir
 * @return True if is of type.
 */
public static boolean validate(final File unzippedDir) throws AddingResourceException {
    final File fManifest = new File(unzippedDir, "imsmanifest.xml");
    final Document doc = IMSLoader.loadIMSDocument(fManifest);
    // do not throw exception already here, as it might be only a generic zip file
    if (doc == null) {
        return false;
    }

    // get all organization elements. need to set namespace
    final Element rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    final Map nsuris = new HashMap(1);
    nsuris.put("ns", nsuri);

    // Check for organiztaion element. Must provide at least one... title gets ectracted from either
    // the (optional) <title> element or the mandatory identifier attribute.
    // This makes sure, at least a root node gets created in CPManifestTreeModel.
    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);
    final Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AddingResourceException("resource.no.organisation");
    }

    // Check for at least one <item> element referencing a <resource>, which will serve as an entry point.
    // This is mandatory, as we need an entry point as the user has the option of setting
    // CPDisplayController to not display a menu at all, in which case the first <item>/<resource>
    // element pair gets displayed.
    final XPath resourcesXPath = rootElement.createXPath("//ns:resources");
    resourcesXPath.setNamespaceURIs(nsuris);
    final Element elResources = (Element) resourcesXPath.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AddingResourceException("resource.no.resource"); // no <resources> element.
    }
    final XPath itemsXPath = rootElement.createXPath("//ns:item");
    itemsXPath.setNamespaceURIs(nsuris);
    final List items = itemsXPath.selectNodes(rootElement);
    if (items.size() == 0) {
        throw new AddingResourceException("resource.no.item"); // no <item> element.
    }
    for (final Iterator iter = items.iterator(); iter.hasNext();) {
        final Element item = (Element) iter.next();
        final String identifierref = item.attributeValue("identifierref");
        if (identifierref == null) {
            continue;
        }
        final XPath resourceXPath = rootElement
                .createXPath("//ns:resource[@identifier='" + identifierref + "']");
        resourceXPath.setNamespaceURIs(nsuris);
        final Element elResource = (Element) resourceXPath.selectSingleNode(elResources);
        if (elResource == null) {
            throw new AddingResourceException("resource.no.matching.resource");
        }
        if (elResource.attribute("scormtype") != null) {
            return false;
        }
        if (elResource.attribute("scormType") != null) {
            return false;
        }
        if (elResource.attribute("SCORMTYPE") != null) {
            return false;
        }
        if (elResource.attributeValue("href") != null) {
            return true; // success.
        }
    }
    return false;
    // throw new AddingResourceException("resource.general.error");
}

From source file:org.olat.fileresource.types.ScormCPFileResource.java

License:Apache License

/**
 * Check for title and at least one resource.
 * /*from  ww  w  .  j  a v a2  s.  c  o m*/
 * @param unzippedDir
 * @return True if is of type.
 */
public static boolean validate(final File unzippedDir) throws AddingResourceException {
    final File fManifest = new File(unzippedDir, "imsmanifest.xml");
    final Document doc = IMSLoader.loadIMSDocument(fManifest);
    // do not throw exception already here, as it might be only a generic zip file
    if (doc == null) {
        return false;
    }

    String adluri = null;
    String seqencingUri = null;
    String simpleSeqencingUri = null;
    // get all organization elements. need to set namespace
    final Element rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    // look for the adl cp namespace that differs a scorm package from a normal cp package
    final Namespace nsADL = rootElement.getNamespaceForPrefix("adlcp");
    if (nsADL != null) {
        adluri = nsADL.getURI();
    }
    final Namespace nsADLSeq = rootElement.getNamespaceForPrefix("adlseq");
    if (nsADLSeq != null) {
        seqencingUri = nsADLSeq.getURI();
    }
    final Namespace nsADLSS = rootElement.getNamespaceForPrefix("imsss");
    if (nsADLSS != null) {
        simpleSeqencingUri = nsADLSS.getURI();
    }
    // we can only support scorm 1.2 so far.
    if (adluri != null
            && !((adluri.indexOf("adlcp_rootv1p2") != -1) || (adluri.indexOf("adlcp_rootv1p3") != -1))) {
        // we dont have have scorm 1.2 or 1.3 namespace so it can't be a scorm package
        throw new AddingResourceException("scorm.no.scorm.namespace");
    }

    final Map nsuris = new HashMap(5);
    nsuris.put("ns", nsuri);
    nsuris.put("adluri", adluri);
    // we might have a scorm 2004 which we do not yet support
    if (seqencingUri != null) {
        nsuris.put("adlseq", seqencingUri);
    }
    if (simpleSeqencingUri != null) {
        nsuris.put("imsss", simpleSeqencingUri);
    }

    // Check for organiztaion element. Must provide at least one... title gets ectracted from either
    // the (optional) <title> element or the mandatory identifier attribute.
    // This makes sure, at least a root node gets created in CPManifestTreeModel.
    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);
    final Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AddingResourceException("resource.no.organisation");
    }

    // Check for at least one <item> element referencing a <resource> of adlcp:scormtype="sco" or "asset",
    // which will serve as an entry point.
    final XPath resourcesXPath = rootElement.createXPath("//ns:resources");
    resourcesXPath.setNamespaceURIs(nsuris);
    final Element elResources = (Element) resourcesXPath.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AddingResourceException("resource.no.resource"); // no <resources> element.
    }
    final XPath itemsXPath = rootElement.createXPath("//ns:item");
    itemsXPath.setNamespaceURIs(nsuris);
    final List items = itemsXPath.selectNodes(rootElement);
    if (items.size() == 0) {
        throw new AddingResourceException("scorm.no.item"); // no <item> element.
    }

    // check for scorm 2004 simple sequencing stuff which we do not yet support
    if (seqencingUri != null) {
        final XPath seqencingXPath = rootElement.createXPath("//ns:imsss");
        final List sequences = seqencingXPath.selectNodes(rootElement);
        if (sequences.size() > 0) {
            throw new AddingResourceException("scorm.found.seqencing"); // seqencing elements found -> scorm 2004
        }
    }

    final Set set = new HashSet();
    for (final Iterator iter = items.iterator(); iter.hasNext();) {
        final Element item = (Element) iter.next();
        final String identifier = item.attributeValue("identifier");
        // check if identifiers are unique, reject if not so
        if (!set.add(identifier)) {
            throw new AddingResourceException("resource.general.error");// TODO:create special error message for non unique ids
        }
    }

    for (final Iterator iter = items.iterator(); iter.hasNext();) {
        final Element item = (Element) iter.next();
        final String identifierref = item.attributeValue("identifierref");
        if (identifierref == null) {
            continue;
        }
        final XPath resourceXPath = rootElement
                .createXPath("//ns:resource[@identifier='" + identifierref + "']");
        resourceXPath.setNamespaceURIs(nsuris);
        final Element elResource = (Element) resourceXPath.selectSingleNode(elResources);
        if (elResource == null) {
            throw new AddingResourceException("resource.no.matching.resource");
        }
        // check for scorm attribute
        final Attribute scormAttr = elResource.attribute("scormtype");
        // some packages have attribute written like "scormType"
        final Attribute scormAttrUpper = elResource.attribute("scormType");
        if (scormAttr == null && scormAttrUpper == null) {
            throw new AddingResourceException("scorm.no.attribute.scormtype");
        }
        String attr = "";
        if (scormAttr != null) {
            attr = scormAttr.getStringValue();
        }
        if (scormAttrUpper != null) {
            attr = scormAttrUpper.getStringValue();
        }
        if (attr == null) {
            throw new AddingResourceException("scorm.no.attribute.value");
        }
        if (elResource.attributeValue("href") != null
                && (attr.equalsIgnoreCase("sco") || attr.equalsIgnoreCase("asset"))) {
            return true; // success.
        }
    }
    throw new AddingResourceException("resource.general.error");
}

From source file:org.olat.ims.qti.container.ItemContext.java

License:Apache License

/**
 * Method shuffle. shuffle clones the current item (since the whole qti tree is readonly) and shuffles it
 * //  w w w  .j  a  v  a 2  s  .co m
 * @param item
 * @return Element
 */
private Element shuffle(final Element item) {
    // get the render_choice
    final XPath choice = DocumentHelper.createXPath(".//render_choice[@shuffle=\"Yes\"]");
    final Element tel_rendchoice = (Element) choice.selectSingleNode(item);
    // if shuffle is disable, just return the item
    if (tel_rendchoice == null) {
        return item;
    }
    // else: we have to shuffle
    // assume: all response_label have same parent: either render_choice or a
    // flow_label
    final Element shuffleItem = item.createCopy();
    // clone the whole item
    final Element el_rendchoice = (Element) choice.selectSingleNode(shuffleItem);
    // <!ELEMENT render_choice ((material | material_ref | response_label |
    // flow_label)* ,response_na?)>
    // <!ATTLIST response_label rshuffle (Yes | No ) 'Yes' .....
    final List el_labels = el_rendchoice.selectNodes(".//response_label[@rshuffle=\"Yes\"]");
    final int shusize = el_labels.size();

    // set up a list of children with their parents and the position of the
    // child (in case several children have the same parent
    final List respList = new ArrayList(shusize);
    final List parentList = new ArrayList(shusize);
    final int[] posList = new int[shusize];
    int j = 0;

    for (final Iterator responses = el_labels.iterator(); responses.hasNext();) {
        final Element response = (Element) responses.next();
        final Element parent = response.getParent();
        final int pos = parent.indexOf(response);
        posList[j++] = pos;
        respList.add(response.clone()); // need to use clones so they are not
        // attached anymore
        parentList.add(parent);
    }
    Collections.shuffle(respList);
    // put the children back to the parents
    for (int i = 0; i < parentList.size(); i++) {
        final Element parent = (Element) parentList.get(i);
        final int pos = posList[i];
        final Element child = (Element) respList.get(i);
        parent.elements().set(pos, child);
    }
    return shuffleItem;
}

From source file:org.olat.modules.cp.CPManifestTreeModel.java

License:Apache License

/**
 * Constructor of the content packaging tree model
 * //from ww w . ja  v  a2  s . c  om
 * @param manifest the imsmanifest.xml file
 */
CPManifestTreeModel(final VFSLeaf manifest) {
    final Document doc = loadDocument(manifest);
    // get all organization elements. need to set namespace
    rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    nsuris.put("ns", nsuri);

    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);
    final Element orgaEl = (Element) meta.selectSingleNode(rootElement); // TODO: accept several organizations?
    if (orgaEl == null) {
        throw new AssertException("could not find element organization");
    }

    final XPath metares = rootElement.createXPath("//ns:resources");
    metares.setNamespaceURIs(nsuris);
    final Element elResources = (Element) metares.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AssertException("could not find element resources");
    }

    final List resourcesList = elResources.elements("resource");
    resources = new HashMap(resourcesList.size());
    for (final Iterator iter = resourcesList.iterator(); iter.hasNext();) {
        final Element elRes = (Element) iter.next();
        final String identVal = elRes.attributeValue("identifier");
        String hrefVal = elRes.attributeValue("href");
        if (hrefVal != null) { // href is optional element for resource element
            try {
                hrefVal = URLDecoder.decode(hrefVal, "UTF-8");
            } catch (final UnsupportedEncodingException e) {
                // each JVM must implement UTF-8
            }
        }
        resources.put(identVal, hrefVal);
    }
    final GenericTreeNode gtn = buildNode(orgaEl);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}

From source file:org.olat.modules.scorm.ScormCPManifestTreeModel.java

License:Apache License

/**
 * Constructor of the content packaging tree model
 * /*from  w  w w.jav  a 2s.  co  m*/
 * @param manifest the imsmanifest.xml file
 * @param itemStatus a Map containing the status of each item like "completed, not attempted, ..."
 */
public ScormCPManifestTreeModel(final File manifest, final Map itemStatus) {
    this.itemStatus = itemStatus;
    final Document doc = loadDocument(manifest);
    // get all organization elements. need to set namespace
    rootElement = doc.getRootElement();
    final String nsuri = rootElement.getNamespace().getURI();
    nsuris.put("ns", nsuri);

    final XPath meta = rootElement.createXPath("//ns:organization");
    meta.setNamespaceURIs(nsuris);

    final XPath metares = rootElement.createXPath("//ns:resources");
    metares.setNamespaceURIs(nsuris);
    final Element elResources = (Element) metares.selectSingleNode(rootElement);
    if (elResources == null) {
        throw new AssertException("could not find element resources");
    }

    final List resourcesList = elResources.elements("resource");
    resources = new HashMap(resourcesList.size());
    for (final Iterator iter = resourcesList.iterator(); iter.hasNext();) {
        final Element elRes = (Element) iter.next();
        final String identVal = elRes.attributeValue("identifier");
        String hrefVal = elRes.attributeValue("href");
        if (hrefVal != null) { // href is optional element for resource element
            try {
                hrefVal = URLDecoder.decode(hrefVal, "UTF-8");
            } catch (final UnsupportedEncodingException e) {
                // each JVM must implement UTF-8
            }
        }
        resources.put(identVal, hrefVal);
    }
    /*
     * Get all organizations
     */
    List organizations = new LinkedList();
    organizations = meta.selectNodes(rootElement);
    if (organizations.isEmpty()) {
        throw new AssertException("could not find element organization");
    }
    final GenericTreeNode gtn = buildTreeNodes(organizations);
    setRootNode(gtn);
    rootElement = null; // help gc
    resources = null;
}

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

License:Open Source License

/**
 * Apply the given XPath expression to the given node.
 *
 * @param prefixes  mapping of prefixes to namespace URIs for prefixes used in expr
 *//*  w  ww  .  j a  va  2 s .  co m*/
public static Node selectSingleNode(Node node, String expr, Map prefixes) {
    try {
        XPath path = new DOMXPath(expr);
        path.setNamespaceContext(new SimpleNamespaceContext(prefixes));
        return (Node) path.selectSingleNode(node);
    } catch (JaxenException e) {
        throw new OXFException(e);
    }
}