List of usage examples for org.dom4j XPath setNamespaceURIs
void setNamespaceURIs(Map<String, String> map);
From source file:org.olat.modules.cp.CPManifestTreeModel.java
License:Apache License
private GenericTreeNode buildNode(final Element item) { final GenericTreeNode gtn = new GenericTreeNode(); // extract title String title = item.elementText("title"); if (title == null) { title = item.attributeValue("identifier"); }//from w ww .java 2s . c om gtn.setAltText(title); gtn.setTitle(title); if (item.getName().equals("organization")) { gtn.setIconCssClass("o_cp_org"); gtn.setAccessible(false); } else if (item.getName().equals("item")) { gtn.setIconCssClass("o_cp_item"); // set resolved file path directly final String identifierref = item.attributeValue("identifierref"); final XPath meta = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']"); meta.setNamespaceURIs(nsuris); final String href = (String) resources.get(identifierref); if (href != null) { gtn.setUserObject(href); // allow lookup of a treenode given a href so we can quickly adjust the menu if the user clicks on hyperlinks within the text hrefToTreeNode.put(href, gtn); } else { gtn.setAccessible(false); } } final List chds = item.elements("item"); final int childcnt = chds.size(); for (int i = 0; i < childcnt; i++) { final Element childitem = (Element) chds.get(i); final GenericTreeNode gtnchild = buildNode(childitem); gtn.addChild(gtnchild); } return gtn; }
From source file:org.olat.modules.scorm.ScormCPManifestTreeModel.java
License:Apache License
/** * Constructor of the content packaging tree model * /* www . ja v a 2 s. 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.olat.modules.scorm.ScormCPManifestTreeModel.java
License:Apache License
private GenericTreeNode buildNode(final Element item) { final GenericTreeNode treeNode = new GenericTreeNode(); // extract title String title = item.elementText("title"); if (title == null) { title = item.attributeValue("identifier"); }//from w w w. java 2s . c o m treeNode.setAltText(title); treeNode.setTitle(title); if (item.getName().equals("organization")) { treeNode.setIconCssClass("o_scorm_org"); treeNode.setAccessible(false); } else if (item.getName().equals("item")) { scormIdToNode.put(new Integer(nodeId).toString(), treeNode); nodeToId.put(treeNode, new Integer(nodeId)); // set node images according to scorm sco status final String itemStatusDesc = (String) itemStatus.get(Integer.toString(nodeId)); treeNode.setIconCssClass("o_scorm_item"); if (itemStatusDesc != null) { // add icon decorator for current status treeNode.setIconDecorator1CssClass("o_scorm_" + itemStatusDesc); } nodeId++; // set resolved file path directly final String identifierref = item.attributeValue("identifierref"); final XPath meta = rootElement.createXPath("//ns:resource[@identifier='" + identifierref + "']"); meta.setNamespaceURIs(nsuris); final String href = (String) resources.get(identifierref); if (href != null) { treeNode.setUserObject(href); // allow lookup of a treenode given a href so we can quickly adjust the menu if the user clicks on hyperlinks within the text hrefToTreeNode.put(href, treeNode); } else { treeNode.setAccessible(false); } } final List chds = item.elements("item"); final int childcnt = chds.size(); for (int i = 0; i < childcnt; i++) { final Element childitem = (Element) chds.get(i); final GenericTreeNode gtnchild = buildNode(childitem); treeNode.addChild(gtnchild); } return treeNode; }
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// ww w . ja va2s. c o 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.openxml4j.opc.signature.RelationshipTransform.java
License:Apache License
@SuppressWarnings("unchecked") public static void SortRelationshipElementsById(Document doc) { HashMap map = new HashMap(); map.put("rel", PackageNamespaces.RELATIONSHIPS); XPath xpath = DocumentHelper.createXPath("//rel:" + PackageRelationship.RELATIONSHIP_TAG_NAME); xpath.setNamespaceURIs(map); XPath sortXpath = DocumentHelper.createXPath("@Id"); List<Element> sortedElements = xpath.selectNodes(doc, sortXpath); doc.getRootElement().setContent(sortedElements); }
From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java
License:Open Source License
/** * Evaluates an XPath expression/* w w w. j a va 2 s . com*/ */ 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.pentaho.di.trans.steps.getxmldata.GetXMLData.java
License:Apache License
@SuppressWarnings("unchecked") private boolean applyXPath() { try {/*from w w w . j a v a2 s. c om*/ 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.di.trans.steps.getxmldata.GetXMLData.java
License:Apache License
private Object[] processPutRow(Node node) throws KettleException { // Create new row... Object[] outputRowData = buildEmptyRow(); // Create new row or clone if (meta.isInFields()) { System.arraycopy(data.readrow, 0, outputRowData, 0, data.nrReadRow); }/*from ww w . j a va2s . c om*/ try { data.nodenr++; // Read fields... for (int i = 0; i < data.nrInputFields; i++) { // Get field GetXMLDataField xmlDataField = meta.getInputFields()[i]; // Get the Path to look for String XPathValue = xmlDataField.getResolvedXPath(); if (meta.isuseToken()) { // See if user use Token inside path field // The syntax is : @_Fieldname- // PDI will search for Fieldname value and replace it // Fieldname must be defined before the current node XPathValue = substituteToken(XPathValue, outputRowData); if (isDetailed()) { logDetailed(XPathValue); } } // Get node value String nodevalue; // Handle namespaces if (meta.isNamespaceAware()) { XPath xpathField = node.createXPath(addNSPrefix(XPathValue, data.PathValue)); xpathField.setNamespaceURIs(data.NAMESPACE); if (xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF) { nodevalue = xpathField.valueOf(node); } else { // nodevalue=xpathField.selectSingleNode(node).asXML(); Node n = xpathField.selectSingleNode(node); if (n != null) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } else { if (xmlDataField.getResultType() == GetXMLDataField.RESULT_TYPE_VALUE_OF) { nodevalue = node.valueOf(XPathValue); } else { // nodevalue=node.selectSingleNode(XPathValue).asXML(); Node n = node.selectSingleNode(XPathValue); if (n != null) { nodevalue = n.asXML(); } else { nodevalue = ""; } } } // Do trimming switch (xmlDataField.getTrimType()) { case GetXMLDataField.TYPE_TRIM_LEFT: nodevalue = Const.ltrim(nodevalue); break; case GetXMLDataField.TYPE_TRIM_RIGHT: nodevalue = Const.rtrim(nodevalue); break; case GetXMLDataField.TYPE_TRIM_BOTH: nodevalue = Const.trim(nodevalue); break; default: break; } // Do conversions // ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(data.totalpreviousfields + i); ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(data.totalpreviousfields + i); outputRowData[data.totalpreviousfields + i] = targetValueMeta.convertData(sourceValueMeta, nodevalue); // Do we need to repeat this field if it is null? if (meta.getInputFields()[i].isRepeated()) { if (data.previousRow != null && Utils.isEmpty(nodevalue)) { outputRowData[data.totalpreviousfields + i] = data.previousRow[data.totalpreviousfields + i]; } } } // End of loop over fields... int rowIndex = data.totalpreviousfields + data.nrInputFields; // See if we need to add the filename to the row... if (meta.includeFilename() && !Utils.isEmpty(meta.getFilenameField())) { outputRowData[rowIndex++] = data.filename; } // See if we need to add the row number to the row... if (meta.includeRowNumber() && !Utils.isEmpty(meta.getRowNumberField())) { outputRowData[rowIndex++] = data.rownr; } // Possibly add short filename... if (meta.getShortFileNameField() != null && meta.getShortFileNameField().length() > 0) { outputRowData[rowIndex++] = data.shortFilename; } // Add Extension if (meta.getExtensionField() != null && meta.getExtensionField().length() > 0) { outputRowData[rowIndex++] = data.extension; } // add path if (meta.getPathField() != null && meta.getPathField().length() > 0) { outputRowData[rowIndex++] = data.path; } // Add Size if (meta.getSizeField() != null && meta.getSizeField().length() > 0) { outputRowData[rowIndex++] = data.size; } // add Hidden if (meta.isHiddenField() != null && meta.isHiddenField().length() > 0) { outputRowData[rowIndex++] = Boolean.valueOf(data.path); } // Add modification date if (meta.getLastModificationDateField() != null && meta.getLastModificationDateField().length() > 0) { outputRowData[rowIndex++] = data.lastModificationDateTime; } // Add Uri if (meta.getUriField() != null && meta.getUriField().length() > 0) { outputRowData[rowIndex++] = data.uriName; } // Add RootUri if (meta.getRootUriField() != null && meta.getRootUriField().length() > 0) { outputRowData[rowIndex] = data.rootUriName; } RowMetaInterface irow = getInputRowMeta(); if (irow == null) { data.previousRow = outputRowData; } else { // clone to previously allocated array to make sure next step doesn't // change it in between... System.arraycopy(outputRowData, 0, this.prevRow, 0, outputRowData.length); // Pick up everything else that needs a real deep clone data.previousRow = irow.cloneRow(outputRowData, this.prevRow); } } catch (Exception e) { if (getStepMeta().isDoingErrorHandling()) { // Simply add this row to the error row putError(data.outputRowMeta, outputRowData, 1, e.toString(), null, "GetXMLData001"); data.errorInRowButContinue = true; return null; } else { logError(e.toString()); throw new KettleException(e.toString()); } } return outputRowData; }
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); 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 {/*from ww w.j a v a2s . com*/ 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 w w .j a v a2 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); }