Example usage for org.dom4j XPath setNamespaceURIs

List of usage examples for org.dom4j XPath setNamespaceURIs

Introduction

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

Prototype

void setNamespaceURIs(Map<String, String> map);

Source Link

Document

Sets the current NamespaceContext from a Map where the keys are the String namespace prefixes and the values are the namespace URIs.

Usage

From source file:org.intalio.tempo.workflow.fds.dispatches.NotifyDispatcher.java

License:Open Source License

public Document dispatchRequest(Document request) throws InvalidInputFormatException {
    Element rootElement = request.getRootElement();
    userProcessNamespace = rootElement.getNamespaceURI();

    Namespace ns = new Namespace("tms", TMS_NS);
    rootElement.setQName(new QName("createTaskRequest", ns));

    Element metadataElement = rootElement.element("metadata");
    metadataElement.setQName(new QName("metadata", ns));
    metadataElement.detach();/*from  w  ww . j av a 2 s .c  om*/

    Element taskElement = rootElement.addElement("task");
    taskElement.setQName(new QName("task", ns));

    taskElement.add(metadataElement);
    if (metadataElement.selectSingleNode("taskId") == null) {
        Element taskIdElement = metadataElement.addElement(new QName("taskId", ns));
        taskIdElement.setText(generateUID());
    }
    if (metadataElement.selectSingleNode("taskType") == null) {
        Element taskTypeElement = metadataElement.addElement(new QName("taskType", ns));
        taskTypeElement.setText("NOTIFICATION");
    }

    Element inputElement = rootElement.element("input");
    inputElement.setQName(new QName("input", ns));
    //inputElement.addNamespace("fe", userProcessNamespace);
    inputElement.detach();
    taskElement.add(inputElement);

    //TODO remove from TMS. Not needed
    rootElement.addElement("participantToken");

    /*
     * Now, change the namespace the
     * input, to TMS_NS.
     */

    XPath xpath = DocumentHelper.createXPath("/tms:createTaskRequest/tms:task/tms:input//*");
    HashMap map = MessageConstants._nsMap;
    map.put("tms", TMS_NS);
    xpath.setNamespaceURIs(MessageConstants._nsMap);
    List allTaskInputElements = xpath.selectNodes(request);

    xpath = DocumentHelper.createXPath("//*");
    List allBody = xpath.selectNodes(request);
    int size = allBody.size();
    LOG.debug(allTaskInputElements.size() + ":" + size);
    for (int i = 0; i < size; ++i) {
        Node node = (Node) allBody.get(i);
        if (!allTaskInputElements.contains(node)) {
            Element element = (Element) node;
            element.remove(element.getNamespaceForURI(userProcessNamespace));
            element.setQName(new QName(element.getName(), ns));
        }
    }

    return request;
}

From source file:org.intalio.tempo.workflow.fds.dispatches.NotifyDispatcher.java

License:Open Source License

public Document dispatchResponse(Document response) throws InvalidInputFormatException {
    XPath xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/soapenv:Fault");
    xpath.setNamespaceURIs(MessageConstants.get_nsMap());
    List fault = xpath.selectNodes(response);
    if (fault.size() != 0) {
        // return fault as-is
        LOG.error("Fault response during notify:\n" + response.asXML());
        return response;
    }/*from w w w. j  av a2 s.  c  o  m*/
    Document notifyResponse = DocumentHelper.createDocument();
    Element rootElement = notifyResponse.addElement("notifyResponse", userProcessNamespace);
    Element statusElement = rootElement.addElement("status", userProcessNamespace);
    statusElement.setText("OK");
    return notifyResponse;
}

From source file:org.jage.platform.config.xml.loaders.AbstractDocumentLoader.java

License:Open Source License

/**
 * Initializes the given xpath with the configuration namespace, then returns it.
 * @param xpath a xpath to initialize//from w w w.ja v a2  s  .  c  o  m
 * @return the initialized xpath
 */
protected static final XPath initXpath(final XPath xpath) {
    final ConfigNamespaces configNamespace = ConfigNamespaces.DEFAULT;
    xpath.setNamespaceURIs(singletonMap(configNamespace.getPrefix(), configNamespace.getUri()));
    return xpath;
}

From source file:org.jage.platform.config.xml.loaders.NormalizingDocumentLoader.java

License:Open Source License

private XPath createXPath(ConfigNamespaces namespace, ConfigTags tag) {
    XPath xpath = DocumentHelper.createXPath(format("//%1$s:%2$s", namespace.getPrefix(), tag.toString()));
    xpath.setNamespaceURIs(singletonMap(namespace.getPrefix(), namespace.getUri()));
    return xpath;
}

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

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

From source file:org.mule.module.xml.filters.JXPathFilter.java

License:Open Source License

private boolean accept(Object obj) {
    if (obj == null) {
        logger.warn("Applying JXPathFilter to null object.");
        return false;
    }//from w w  w . j av a2  s.  c om
    if (pattern == null) {
        logger.warn("Expression for JXPathFilter is not set.");
        return false;
    }
    if (expectedValue == null) {
        // Handle the special case where the expected value really is null.
        if (pattern.endsWith("= null") || pattern.endsWith("=null")) {
            expectedValue = "null";
            pattern = pattern.substring(0, pattern.lastIndexOf("="));
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("Expected value for JXPathFilter is not set, using 'true' by default");
            }
            expectedValue = Boolean.TRUE.toString();
        }
    }

    Object xpathResult = null;
    boolean accept = false;

    Document dom4jDoc;
    try {
        dom4jDoc = XMLUtils.toDocument(obj, muleContext);
    } catch (Exception e) {
        logger.warn("JxPath filter rejected message because of an error while parsing XML: " + e.getMessage(),
                e);
        return false;
    }

    // Payload is XML
    if (dom4jDoc != null) {
        if (namespaces == null) {
            // no namespace defined, let's perform a direct evaluation
            xpathResult = dom4jDoc.valueOf(pattern);
        } else {
            // create an xpath expression with namespaces and evaluate it
            XPath xpath = DocumentHelper.createXPath(pattern);
            xpath.setNamespaceURIs(namespaces);
            xpathResult = xpath.valueOf(dom4jDoc);
        }
    }
    // Payload is a Java object
    else {
        if (logger.isDebugEnabled()) {
            logger.debug("Passing object of type " + obj.getClass().getName() + " to JXPathContext");
        }
        JXPathContext context = JXPathContext.newContext(obj);
        initialise(context);
        xpathResult = context.getValue(pattern);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("JXPathFilter Expression result = '" + xpathResult + "' -  Expected value = '"
                + expectedValue + "'");
    }
    // Compare the XPath result with the expected result.
    if (xpathResult != null) {
        accept = xpathResult.toString().equals(expectedValue);
    } else {
        // A null result was actually expected.
        if (expectedValue.equals("null")) {
            accept = true;
        }
        // A null result was not expected, something probably went wrong.
        else {
            logger.warn("JXPathFilter expression evaluates to null: " + pattern);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("JXPathFilter accept object  : " + accept);
    }

    return accept;
}

From source file:org.mule.module.xml.transformer.JXPathExtractor.java

License:Open Source License

/**
 * Evaluate the expression in the context of the given object and returns the
 * result. If the given object is a string, it assumes it is an valid xml and
 * parses it before evaluating the xpath expression.
 *///from   w w w .  ja  v  a2 s.  c o  m
@Override
public Object doTransform(Object src, String encoding) throws TransformerException {
    try {
        Object result = null;
        if (src instanceof String) {
            Document doc = DocumentHelper.parseText((String) src);

            XPath xpath = doc.createXPath(expression);
            if (namespaces != null) {
                xpath.setNamespaceURIs(namespaces);
            }

            // This is the way we always did it before, so keep doing it that way
            // as xpath.evaluate() will return non-string results (like Doubles)
            // for some scenarios.
            if (outputType == null && singleResult) {
                return xpath.valueOf(doc);
            }

            // TODO handle non-list cases, see
            //http://www.dom4j.org/apidocs/org/dom4j/XPath.html#evaluate(java.lang.Object)
            Object obj = xpath.evaluate(doc);
            if (obj instanceof List) {
                for (int i = 0; i < ((List) obj).size(); i++) {
                    final Node node = (Node) ((List) obj).get(i);
                    result = add(result, node);

                    if (singleResult) {
                        break;
                    }
                }
            } else {
                result = add(result, obj);
            }

        } else {
            JXPathContext context = JXPathContext.newContext(src);
            result = context.getValue(expression);
        }
        return result;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }

}

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

License:Apache License

/**
 * Check for title and at least one resource.
 * /*  w  w w . j a  v  a 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  w w  w  .  j  a  v a2  s  . co  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.cp.CPManifestTreeModel.java

License:Apache License

/**
 * Constructor of the content packaging tree model
 * /*from  ww w. j av  a 2s .co  m*/
 * @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;
}