Example usage for org.dom4j XPath selectNodes

List of usage examples for org.dom4j XPath selectNodes

Introduction

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

Prototype

List<Node> selectNodes(Object context);

Source Link

Document

selectNodes performs this XPath expression on the given Node or List of Node s instances appending all the results together into a single list.

Usage

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

License:Apache License

/**
 * Check for title and at least one resource.
 * //from w  ww.j  av  a  2 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.modules.scorm.ScormCPManifestTreeModel.java

License:Apache License

/**
 * Constructor of the content packaging tree model
 * //from   w  w w. j  ava  2s  .  c o  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.openadaptor.auxil.convertor.map.DocumentMapFacade.java

License:Open Source License

/**
 * Redone to use the namespace Map if there is one.
 * @param path/*w ww . j  a  v  a  2s  . co  m*/
 * @return List Nodes referenced by this path
 */
protected List getNodes(String path) {
    if (nsMap == null) {
        return document.selectNodes(path);
    } else {
        // TODO Must be a way of setting the namespace once for the document.
        XPath xpath = DocumentHelper.createXPath(path);
        xpath.setNamespaceURIs(nsMap);
        return xpath.selectNodes(document);
    }
}

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
 * @return            Iterator over org.w3c.dom.Node objects, never null
 *//* w  w w.ja va2 s.c o m*/
public static Iterator selectIterator(org.dom4j.Node node, String expr, Map prefixes) {
    try {
        org.dom4j.XPath path = node.createXPath(expr);
        path.setNamespaceContext(new SimpleNamespaceContext(prefixes));

        return new IteratorFilter(path.selectNodes(node).iterator(), org.dom4j.Namespace.class);
    } catch (InvalidXPathException e) {
        throw new OXFException(e);
    }
}

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

License:Open Source License

public static Iterator selectIterator(org.dom4j.Node node, String expr, Map prefixes,
        VariableContext variableContext, FunctionContext functionContext) {
    try {/*from  www  .j  a va2  s  .c  o  m*/
        org.dom4j.XPath path = node.createXPath(expr);
        hookupPath(path, prefixes, variableContext, functionContext);
        return new IteratorFilter(path.selectNodes(node).iterator(), org.dom4j.Namespace.class);
    } catch (InvalidXPathException e) {
        throw new OXFException(e);
    }
}

From source file:org.pentaho.di.trans.steps.getxmldata.GetXMLData.java

License:Apache License

@SuppressWarnings("unchecked")
private boolean applyXPath() {
    try {/*from   w ww  .  j  av a  2 s  .c o  m*/
        XPath xpath = data.document.createXPath(data.PathValue);
        if (meta.isNamespaceAware()) {
            xpath = data.document.createXPath(addNSPrefix(data.PathValue, data.PathValue));
            xpath.setNamespaceURIs(data.NAMESPACE);
        }
        // get nodes list
        data.an = xpath.selectNodes(data.document);
        data.nodesize = data.an.size();
        data.nodenr = 0;
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "GetXMLData.Log.ErrorApplyXPath", e.getMessage()));
        return false;
    }
    return true;
}

From source file:org.pentaho.ui.xul.impl.AbstractXulLoader.java

License:Open Source License

public Document preProcess(Document srcDoc) throws XulException {

    XPath xpath = new DefaultXPath("//pen:include");

    HashMap uris = new HashMap();
    uris.put("xul", "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
    uris.put("pen", "http://www.pentaho.org/2008/xul");

    xpath.setNamespaceURIs(uris);/*from ww w. j  a  v  a 2s.c  o  m*/

    List<Element> eles = xpath.selectNodes(srcDoc);

    for (Element ele : eles) {
        String src = "";

        src = this.getRootDir() + ele.attributeValue("src");

        String resourceBundle = ele.attributeValue("resource");
        if (resourceBundle != null) {
            resourceBundles.add(resourceBundle);
        } else {
            resourceBundles.add(src.replace(".xul", ""));
        }

        InputStream in = null;
        try {
            in = getResourceAsStream(src);

            if (in != null) {
                logger.debug("Adding include src: " + src);
                includedSources.add(src);
            } else {
                // try fully qualified name
                src = ele.attributeValue("src");
                in = getResourceAsStream(src);
                if (in != null) {
                    includedSources.add(src);
                    logger.debug("Adding include src: " + src);
                } else {
                    File f = new File(this.getRootDir() + src);
                    if (f.exists()) {
                        try {
                            in = new FileInputStream(f);
                            includedSources.add(src);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }

            final Document doc = getDocFromInputStream(in);

            Element root = doc.getRootElement();
            String ignoreRoot = ele.attributeValue("ignoreroot");
            if (root.getName().equals("overlay")) {
                processOverlay(root, ele.getDocument().getRootElement());
            } else if (ignoreRoot == null || ignoreRoot.equalsIgnoreCase("false")) {
                logger.debug("Including entire file: " + src);
                List contentOfParent = ele.getParent().content();
                int index = contentOfParent.indexOf(ele);
                contentOfParent.set(index, root);

                if (root.getName().equals("dialog")) {
                    String newOnload = root.attributeValue("onload");
                    if (newOnload != null) {
                        String existingOnload = srcDoc.getRootElement().attributeValue("onload");
                        String finalOnload = "";
                        if (existingOnload != null) {
                            finalOnload = existingOnload + ", ";
                        }
                        finalOnload += newOnload;
                        srcDoc.getRootElement().setAttributeValue("onload", finalOnload);
                    }
                }

                // process any overlay children
                List<Element> overlays = ele.elements();
                for (Element overlay : overlays) {
                    logger.debug("Processing overlay within include");

                    this.processOverlay(overlay.attributeValue("src"), srcDoc);
                }
            } else {
                logger.debug("Including children: " + src);
                List contentOfParent = ele.getParent().content();
                int index = contentOfParent.indexOf(ele);
                contentOfParent.remove(index);
                List children = root.elements();
                for (int i = children.size() - 1; i >= 0; i--) {
                    Element child = (Element) children.get(i);
                    contentOfParent.add(index, child);

                    if (child.getName().equals("dialog")) {
                        String newOnload = child.attributeValue("onload");
                        if (newOnload != null) {
                            String existingOnload = srcDoc.getRootElement().attributeValue("onload");
                            String finalOnload = "";
                            if (existingOnload != null) {
                                finalOnload = existingOnload + ", ";
                            }
                            finalOnload += newOnload;
                            srcDoc.getRootElement().setAttributeValue("onload", finalOnload);
                        }
                    }
                }

                // process any overlay children
                List<Element> overlays = ele.elements();
                for (Element overlay : overlays) {
                    logger.debug("Processing overlay within include");

                    this.processOverlay(overlay.attributeValue("src"), srcDoc);
                }
            }
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ignored) {
                //ignored
            }
        }
    }

    return srcDoc;
}

From source file:org.soyatec.windowsazure.internal.util.xml.XPathQueryHelper.java

License:Apache License

/**
 * Parse entry from the feed document/*from  w  ww  .j av  a  2 s .c o  m*/
 * 
 * @param doc
 *            the document
 * @return a list
 */
@SuppressWarnings("unchecked")
public static List parseEntryFromFeed(final Document doc) {
    Map xmlMap = new HashMap();
    xmlMap.put("atom", TableStorageConstants.AtomNamespace);
    XPath x = doc.createXPath(ATOM_ENTRY_PATH);
    x.setNamespaceURIs(xmlMap);
    return x.selectNodes(doc);
}

From source file:org.soyatec.windowsazure.internal.util.xml.XPathQueryHelper.java

License:Apache License

/**
 * Select the service xml//from   w  w w .j  a va  2s.co m
 * 
 * @param doc
 * @param path
 * @return a list
 */
@SuppressWarnings("unchecked")
static List selectNodes(final Node doc, String path) {
    Map xmlMap = new HashMap();
    xmlMap.put(XMLNS, ServiceManagementConstants.ServiceManagementNS);
    XPath x = doc.createXPath(path);
    x.setNamespaceURIs(xmlMap);
    return x.selectNodes(doc);
}

From source file:org.springframework.extensions.webscripts.bean.ServiceInstall.java

License:Apache License

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
    if (!(req instanceof WebScriptServletRequest)) {
        throw new WebScriptException("Web Script install only supported via HTTP Servlet");
    }/*  www  . ja va  2 s  . com*/
    HttpServletRequest servletReq = ((WebScriptServletRequest) req).getHttpServletRequest();

    // construct model
    Map<String, Object> model = new HashMap<String, Object>(7, 1.0f);
    List<InstalledFile> installedFiles = new ArrayList<InstalledFile>();
    model.put("installedFiles", installedFiles);

    try {
        // parse request content
        Object content = req.parseContent();
        if (content == null || !(content instanceof FormData)) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                    "Web Script install request is not multipart/form-data");
        }

        // locate file upload
        FormData formData = (FormData) content;
        FormField file = null;
        for (FormField field : formData.getFields()) {
            if (field.getIsFile()) {
                if (file != null) {
                    throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                            "Web Script install request expects only one file upload");
                }
                file = field;
            }
        }
        if (file == null) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                    "Web Script install request is missing file upload");
        }

        // find web script definition
        Document document = null;
        InputStream fileIS = file.getContent().getInputStream();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileIS));
            SAXReader reader = new SAXReader();
            document = reader.read(bufferedReader);
        } finally {
            fileIS.close();
        }
        Element rootElement = document.getRootElement();
        XPath xpath = rootElement.createXPath("//ws:webscript");
        Map<String, String> uris = new HashMap<String, String>();
        uris.put("ws", "http://www.alfresco.org/webscript/1.0");
        xpath.setNamespaceURIs(uris);
        List nodes = xpath.selectNodes(rootElement);
        if (nodes.size() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                    "Cannot locate Web Script in uploaded file");
        }

        // extract web script definition
        Element webscriptElem = (Element) nodes.get(0);
        String scriptId = webscriptElem.attributeValue("scriptid");
        if (scriptId == null || scriptId.length() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                    "Expected scriptid value on webscript element");
        }
        Iterator iter = webscriptElem.elementIterator();
        while (iter.hasNext()) {
            Element fileElem = (Element) iter.next();
            String webscriptStore = fileElem.attributeValue("store");
            if (webscriptStore == null || webscriptStore.length() == 0) {
                throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                        "Expected store value on webscript element");
            }
            String webscriptPath = fileElem.attributeValue("path");
            if (webscriptPath == null || webscriptPath.length() == 0) {
                throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                        "Expected file value on webscript element");
            }
            String webscriptContent = fileElem.getText();

            // install web script implementation file
            installFile(webscriptStore, webscriptPath, webscriptContent);
            InstalledFile installedFile = new InstalledFile();
            installedFile.store = webscriptStore;
            installedFile.path = webscriptPath;
            installedFiles.add(installedFile);
        }

        // reset web scripts
        getContainer().reset();

        // locate installed web script
        Registry registry = getContainer().getRegistry();
        WebScript webscript = registry.getWebScript(scriptId);
        if (webscript == null) {
            throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to install Web Script " + scriptId);
        }
        model.put("installedScript", webscript.getDescription());
    } catch (DocumentException e) {
        throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (IOException e) {
        throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return model;
}