List of usage examples for org.w3c.dom Node getOwnerDocument
public Document getOwnerDocument();
Document
object associated with this node. From source file:com.ext.portlet.epsos.EpsosHelperService.java
/** * Add a tag of the form below under the given node: * /* w w w . jav a2 s . co m*/ * <product> <manufacturedProduct xmlns:epsos="urn:epsos-org:ep:medication" classCode="MANU"> <templateId root='1.3.6.1.4.1.19376.1.5.3.1.4.7.2'/> <templateId root='2.16.840.1.113883.10.20.1.53'/> <manufacturedMaterial classCode="MMAT" determinerCode="KIND"> <templateId root='1.3.6.1.4.1.12559.11.10.1.3.1.3.1'/> <!-- Id dispensed product--> <epsos:id root="222" extension="3213"/> <code code="409120009" displayName="Metformin and rosiglitazone" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"> <!-- Optional generic name --> <originalText> <reference value="reference"/> </originalText> </code> <name>Metformina y rosiglitazona</name> <!--Dose form --> <epsos:formCode code="10221000" displayName="Film-coated tablet" codeSystem="1.3.6.1.4.1.12559.11.10.1.3.1.42.2" codeSystemName="epSOS:DoseForm"/> <epsos:asContent classCode="CONT"> <!-- Package size--> <epsos:quantity> <epsos:numerator xsi:type="epsos:PQ" value="112" unit="1" /> <epsos:denominator xsi:type="epsos:PQ" value="1" unit="1"/> </epsos:quantity> <!-- Package --> <epsos:containerPackagedMedicine classCode="CONT" determinerCode="INSTANCE"> <epsos:formCode code="30009000" displayName="Box" codeSystem="1.3.6.1.4.1.12559.11.10.1.3.1.42.3" codeSystemName="epSOS:Package"/> <!-- A10BD03 Metformin and rosiglitazone --> <epsos:name> Metformin and rosiglitazone</epsos:name> <!-- random lot number has been assigned--> <epsos:lotNumberText>1322231</epsos:lotNumberText> <epsos:capacityQuantity value=' 112' unit='1'/> <!-- child proof--> <epsos:capTypeCode code="ChildProof"/> </epsos:containerPackagedMedicine> </epsos:asContent> <epsos:ingredient classCode="ACTI"> <!--Strength, --> <epsos:quantity> <epsos:numerator xsi:type="epsos:PQ" value="500+2" unit="mg"/> <epsos:denominator xsi:type="epsos:PQ" value="1" unit="1"/> </epsos:quantity> <epsos:ingredient classCode="MMAT" determinerCode="KIND"> <!-- ATC-code--> <epsos:code code="A10BD03" codeSystem="2.16.840.1.113883.6.73" displayName="Metformin and rosiglitazone"/> <epsos:name>Metformin and rosiglitazone</epsos:name> </epsos:ingredient> </epsos:ingredient> </manufacturedMaterial> </manufacturedProduct> </product> * * * * * * @param dom * @param node * @param doctor */ private void addProductTag(Document dom, Node node, ViewResult dispensedLine, Node prescriptionNode) { Node productNode = dom.createElement("product"); Node product = dom.createElement("manufacturedProduct"); addAttribute(dom, product, "xmlns:epsos", XML_DISPENSATION_PRODUCT_EPSOSNS); addAttribute(dom, product, "classCode", XML_DISPENSATION_PRODUCT_CLASSCODE); addTemplateId(dom, product, XML_DISPENSATION_PRODUCT_TEMPLATE1); addTemplateId(dom, product, XML_DISPENSATION_PRODUCT_TEMPLATE2); // change after September 29/30-2010 workshop: product tag must be the same as the one in prescription. // only changes allowed (if substituting) are the brand name and the package quantity tags Node materialNode = null; // use identical material info from prescription try { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression materialExpr = xpath .compile("substanceAdministration/consumable/manufacturedProduct/manufacturedMaterial"); Node oldMaterialNode = (Node) materialExpr.evaluate(prescriptionNode, XPathConstants.NODE); // fix to add epsos:id node XPathExpression code = xpath .compile("substanceAdministration/consumable/manufacturedProduct/manufacturedMaterial/code"); Node codeNode = (Node) code.evaluate(prescriptionNode, XPathConstants.NODE); if (codeNode == null) { code = xpath.compile( "substanceAdministration/consumable/manufacturedProduct/manufacturedMaterial/name"); codeNode = (Node) code.evaluate(prescriptionNode, XPathConstants.NODE); } Node epsosID = dom.createElement("epsos:id"); addAttribute(dom, epsosID, "root", XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE3); addAttribute(dom, epsosID, "extension", (String) dispensedLine.getField1()); oldMaterialNode.insertBefore(epsosID, codeNode); materialNode = oldMaterialNode.cloneNode(true); if (dispensedLine.getField3() != null && ((Boolean) dispensedLine.getField3()).booleanValue()) { // substitute case, change brand name and quantity tags XPathExpression brandNameExpr = xpath.compile("name"); Node nameNode = (Node) brandNameExpr.evaluate(materialNode, XPathConstants.NODE); nameNode.setTextContent((String) dispensedLine.getField2()); XPathExpression packContentExpr = xpath.compile("asContent"); Node contentNode = (Node) packContentExpr.evaluate(materialNode, XPathConstants.NODE); XPathExpression packQuantityExpr = xpath.compile("containerPackagedMedicine/capacityQuantity"); Node oldQuant = (Node) packQuantityExpr.evaluate(contentNode, XPathConstants.NODE); NamedNodeMap attributes = oldQuant.getAttributes(); Node unitNode = node.getOwnerDocument().createAttribute("unit"); unitNode.setNodeValue((String) dispensedLine.getField12()); attributes.setNamedItem(unitNode); Node attNode = node.getOwnerDocument().createAttribute("value"); attNode.setNodeValue((String) dispensedLine.getField7()); attributes.setNamedItem(attNode); // Node quant = createEpsosCapacityQuantityNode(dom, (String)dispensedLine.getField7(),(String)dispensedLine.getField12()); // if (contentNode != null && oldQuant != null) // contentNode.replaceChild(quant, oldQuant); } } catch (Exception e) { _log.error("error using identical material info from prescription"); } product.appendChild(materialNode); productNode.appendChild(product); node.appendChild(productNode); }
From source file:com.portfolio.data.provider.MysqlAdminProvider.java
private void getLinearXml(String portfolioUuid, String rootuuid, Node portfolio, boolean withChildren, String withChildrenOfXsiType, int userId, int groupId) throws SQLException, SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance(); DocumentBuilder parse = newInstance.newDocumentBuilder(); /*/*from ww w.ja v a 2s . c o m*/ long time0 = 0; long time1 = 0; long time2 = 0; long time3 = 0; //*/ // time0 = System.currentTimeMillis(); ResultSet resNode = getMysqlStructure(portfolioUuid, userId, groupId); // time1= System.currentTimeMillis(); Document document = portfolio.getOwnerDocument(); HashMap<String, Node> resolve = new HashMap<String, Node>(); /// Node -> parent ArrayList<Object[]> entries = new ArrayList<Object[]>(); processQuery(resNode, resolve, entries, document, parse); resNode.close(); resNode = getSharedMysqlStructure(portfolioUuid, userId, groupId); if (resNode != null) { processQuery(resNode, resolve, entries, document, parse); resNode.close(); } // time2 = System.currentTimeMillis(); /// Reconstruct tree for (int i = 0; i < entries.size(); ++i) { Object[] obj = entries.get(i); Node node = (Node) obj[0]; String childsId = (String) obj[1]; String[] tok = childsId.split(","); for (int j = 0; j < tok.length; ++j) { String id = tok[j]; Node child = resolve.get(id); if (child != null) node.appendChild(child); } } // time3 = System.currentTimeMillis(); Node rootNode = resolve.get(rootuuid); portfolio.appendChild(rootNode); /* System.out.println("---- Portfolio ---"); System.out.println("Time query: "+(time1-time0)); System.out.println("Parsing: "+(time2-time1)); System.out.println("Reconstruction: "+(time3-time2)); System.out.println("------------------"); //*/ }
From source file:com.portfolio.data.provider.MysqlDataProvider.java
private void getLinearXml(String portfolioUuid, String rootuuid, Node portfolio, boolean withChildren, String withChildrenOfXsiType, int userId, int groupId, String role) throws SQLException, SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance(); DocumentBuilder parse = newInstance.newDocumentBuilder(); /*// w ww. ja v a 2 s .c o m long time0 = 0; long time1 = 0; long time2 = 0; long time3 = 0; //*/ // time0 = System.currentTimeMillis(); ResultSet resNode = getMysqlStructure(portfolioUuid, userId, groupId); // time1= System.currentTimeMillis(); Document document = portfolio.getOwnerDocument(); HashMap<String, Node> resolve = new HashMap<String, Node>(); /// Node -> parent ArrayList<Object[]> entries = new ArrayList<Object[]>(); processQuery(resNode, resolve, entries, document, parse, role); resNode.close(); resNode = getSharedMysqlStructure(portfolioUuid, userId, groupId); if (resNode != null) { processQuery(resNode, resolve, entries, document, parse, role); resNode.close(); } // time2 = System.currentTimeMillis(); /// Reconstruct tree, using children list (node_children_uuid) for (int i = 0; i < entries.size(); ++i) { Object[] obj = entries.get(i); Node node = (Node) obj[0]; String childsId = (String) obj[1]; String[] tok = childsId.split(","); for (int j = 0; j < tok.length; ++j) { String id = tok[j]; Node child = resolve.get(id); if (child != null) node.appendChild(child); } } // time3 = System.currentTimeMillis(); Node rootNode = resolve.get(rootuuid); if (rootNode != null) portfolio.appendChild(rootNode); /* System.out.println("---- Portfolio ---"); System.out.println("Time query: "+(time1-time0)); System.out.println("Parsing: "+(time2-time1)); System.out.println("Reconstruction: "+(time3-time2)); System.out.println("------------------"); //*/ }
From source file:com.codeandpop.android.multilevelmenufragment.MultilevelMenuActivity.java
protected void replaceMenuFragment(Node menuItem) throws Exception { MultilevelMenuFragment menuFragment = new MultilevelMenuFragment(); List<MultilevelMenuItem> menuItems = menu.parse(menuItem); ArrayAdapter<MultilevelMenuItem> adapter = getMultilevelMenuViewAdapter(menuItems); menuFragment.setListAdapter(adapter); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (menuItem.getParentNode() == menuItem.getOwnerDocument()) { ft.add(getMultilevelMenuFragmentContainerResourceId(), menuFragment); } else {//from ww w . j ava 2 s . co m ft.replace(getMultilevelMenuFragmentContainerResourceId(), menuFragment); ft.addToBackStack(null); // Enable back button to go back to the previous menu } ft.commit(); }
From source file:net.sourceforge.pmd.lang.ast.AbstractNode.java
protected void appendElement(final org.w3c.dom.Node parentNode) { final DocumentNavigator docNav = new DocumentNavigator(); Document ownerDocument = parentNode.getOwnerDocument(); if (ownerDocument == null) { // If the parentNode is a Document itself, it's ownerDocument is // null/*w w w.j a v a2s . c om*/ ownerDocument = (Document) parentNode; } final String elementName = docNav.getElementName(this); final Element element = ownerDocument.createElement(elementName); parentNode.appendChild(element); for (final Iterator<Attribute> iter = docNav.getAttributeAxisIterator(this); iter.hasNext();) { final Attribute attr = iter.next(); element.setAttribute(attr.getName(), attr.getStringValue()); } for (final Iterator<Node> iter = docNav.getChildAxisIterator(this); iter.hasNext();) { final AbstractNode child = (AbstractNode) iter.next(); child.appendElement(element); } }
From source file:net.sourceforge.pmd.lang.xml.ast.DOMLineNumbers.java
private String unexpandEntities(Node n, String te) { String result = te;//w w w. ja v a2 s .com DocumentType doctype = n.getOwnerDocument().getDoctype(); // implicit entities result = result.replaceAll(Matcher.quoteReplacement("&"), "&"); result = result.replaceAll(Matcher.quoteReplacement("<"), "<"); result = result.replaceAll(Matcher.quoteReplacement(">"), ">"); result = result.replaceAll(Matcher.quoteReplacement("\""), """); result = result.replaceAll(Matcher.quoteReplacement("'"), "'"); if (doctype != null) { NamedNodeMap entities = doctype.getEntities(); String internalSubset = doctype.getInternalSubset(); if (internalSubset == null) { internalSubset = ""; } for (int i = 0; i < entities.getLength(); i++) { Node item = entities.item(i); String entityName = item.getNodeName(); Node firstChild = item.getFirstChild(); if (firstChild != null) { result = result.replaceAll(Matcher.quoteReplacement(firstChild.getNodeValue()), "&" + entityName + ";"); } else { Matcher m = Pattern .compile(Matcher.quoteReplacement("<!ENTITY " + entityName + " ") + "[']([^']*)[']>") .matcher(internalSubset); if (m.find()) { result = result.replaceAll(Matcher.quoteReplacement(m.group(1)), "&" + entityName + ";"); } } } } return result; }
From source file:nl.armatiek.xslweb.saxon.functions.ExtensionFunctionCall.java
protected NodeInfo source2NodeInfo(Source source, Configuration configuration) { Node node = ((DOMSource) source).getNode(); String baseURI = source.getSystemId(); DocumentWrapper documentWrapper = new DocumentWrapper(node.getOwnerDocument(), baseURI, configuration); return documentWrapper.wrap(node); }
From source file:org.alfresco.web.forms.xforms.Schema2XForms.java
@SuppressWarnings("unchecked") public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode, final Node newInstanceNode, final HashMap<String, String> schemaNamespaces) { final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode); prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode); instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI); for (final String prefix : schemaNamespaces.keySet()) { prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix)); instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix)); }//from ww w .jav a2 s . c o m // Evaluate non-recursive XPaths for all prototype elements at this level final Iterator<Pointer> it = prototypeContext.iteratePointers("*"); while (it.hasNext()) { final Pointer p = it.next(); Element proto = (Element) p.getNode(); String path = p.asPath(); // check if this is a prototype element with the attribute set boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype") && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true"); // We shouldn't locate a repeatable child with a fixed path if (isPrototype) { path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path); } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path); } } Document newInstanceDocument = newInstanceNode.getOwnerDocument(); // Locate the corresponding nodes in the instance document List<Node> l = (List<Node>) instanceContext.selectNodes(path); // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node if (l.isEmpty()) { if (!isPrototype) { LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to " + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement())); // Clone the prototype node and all its children Element clone = (Element) proto.cloneNode(true); newInstanceNode.appendChild(clone); if (oldInstanceNode instanceof Document) { // add XMLSchema instance NS addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX, NamespaceConstants.XMLSCHEMA_INSTANCE_NS); } } } else { // Otherwise, append the matches from the old instance document in order for (Node old : l) { Element oldEl = (Element) old; // Copy the old instance element rather than cloning it, so we don't copy over attributes Element clone = null; String nSUri = oldEl.getNamespaceURI(); if (nSUri == null) { clone = newInstanceDocument.createElement(oldEl.getTagName()); } else { clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName()); } newInstanceNode.appendChild(clone); if (oldInstanceNode instanceof Document) { // add XMLSchema instance NS addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX, NamespaceConstants.XMLSCHEMA_INSTANCE_NS); } // Copy over child text if this is not a complex type boolean isEmpty = true; for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) { if (n instanceof Text) { clone.appendChild(newInstanceDocument.importNode(n, false)); isEmpty = false; } else if (n instanceof Element) { break; } } // Populate the nil attribute. It may be true or false if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) { clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty)); } // Copy over attributes present in the prototype NamedNodeMap attributes = proto.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attribute = (Attr) attributes.item(i); String localName = attribute.getLocalName(); if (localName == null) { String name = attribute.getName(); if (oldEl.hasAttribute(name)) { clone.setAttributeNode( (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false)); } else { LOGGER.debug("[rebuildInstance] copying in missing attribute " + attribute.getNodeName() + " to " + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement())); clone.setAttributeNode((Attr) attribute.cloneNode(false)); } } else { String namespace = attribute.getNamespaceURI(); if (!((!isEmpty && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS) && localName.equals("nil")) || (namespace.equals(NamespaceService.ALFRESCO_URI) && localName.equals("prototype"))))) { if (oldEl.hasAttributeNS(namespace, localName)) { clone.setAttributeNodeNS((Attr) newInstanceDocument .importNode(oldEl.getAttributeNodeNS(namespace, localName), false)); } else { LOGGER.debug("[rebuildInstance] copying in missing attribute " + attribute.getNodeName() + " to " + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement())); clone.setAttributeNodeNS((Attr) attribute.cloneNode(false)); } } } } // recurse on children rebuildInstance(proto, oldEl, clone, schemaNamespaces); } } // Now add in a new copy of the prototype if (isPrototype) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to " + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement())); } newInstanceNode.appendChild(proto.cloneNode(true)); } } }
From source file:org.apache.any23.extractor.microdata.MicrodataParser.java
/** * Returns all the <b>itemprop</b>s for the given <b>itemscope</b> node. * * @param scopeNode node representing the <b>itemscope</b> * @param skipRoot if <code>true</code> the given root <code>node</code> * will be not read as a property, even if it contains the <b>itemprop</b> attribute. * @return the list of <b>itemprop</b>s detected within the given <b>itemscope</b>. * @throws MicrodataParserException if an error occurs while retrieving an property value. *///from w w w . ja v a2 s .c om public List<ItemProp> getItemProps(final Node scopeNode, boolean skipRoot) throws MicrodataParserException { final Set<Node> accepted = new LinkedHashSet<>(); if (!skipRoot) { NamedNodeMap attributes = scopeNode.getAttributes(); if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null) { accepted.add(scopeNode); } } // TreeWalker to walk DOM tree starting with the scopeNode. Nodes maybe visited multiple times. TreeWalker treeWalker = ((DocumentTraversal) scopeNode.getOwnerDocument()).createTreeWalker(scopeNode, NodeFilter.SHOW_ELEMENT, new NodeFilter() { @Override public short acceptNode(Node node) { if (node.getNodeType() == Node.ELEMENT_NODE) { NamedNodeMap attributes = node.getAttributes(); if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null && !scopeNode.equals(node)) { accepted.add(node); } if (attributes.getNamedItem(ITEMSCOPE_ATTRIBUTE) != null) { // Don't visit descendants of nodes that define a new scope return FILTER_REJECT; } } return FILTER_ACCEPT; } }, false); // To populate accepted we only need to walk the tree. while (treeWalker.nextNode() != null) ; final List<ItemProp> result = new ArrayList<>(); for (Node itemPropNode : accepted) { final String itemProp = DomUtils.readAttribute(itemPropNode, ITEMPROP_ATTRIBUTE, null); if (StringUtils.isBlank(itemProp)) { manageError(new MicrodataParserException("invalid property name '" + itemProp + "'", itemPropNode)); continue; } final String[] propertyNames = itemProp.trim().split("\\s+"); ItemPropValue itemPropValue; for (String propertyName : propertyNames) { try { itemPropValue = getPropertyValue(itemPropNode); } catch (MicrodataParserException mpe) { manageError(mpe); continue; } result.add(new ItemProp(DomUtils.getXPathForNode(itemPropNode), propertyName, itemPropValue)); } } return result; }
From source file:org.apache.camel.blueprint.handler.CamelNamespaceHandler.java
public static void renameNamespaceRecursive(Node node) { if (node.getNodeType() == Node.ELEMENT_NODE) { Document doc = node.getOwnerDocument(); if (((Element) node).getNamespaceURI().equals(BLUEPRINT_NS)) { doc.renameNode(node, SPRING_NS, node.getNodeName()); }//from ww w . java 2 s. co m } NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); ++i) { renameNamespaceRecursive(list.item(i)); } }