List of usage examples for org.w3c.dom Node insertBefore
public Node insertBefore(Node newChild, Node refChild) throws DOMException;
newChild
before the existing child node refChild
. From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java
private void addPathToApplicationContext(String pluginApplicationContextPath) throws UIException { StringBuffer applicationContextFilePathBuffer = new StringBuffer( System.getenv(SystemConfigSharedConstants.DCMA_HOME)); applicationContextFilePathBuffer.append(File.separator); applicationContextFilePathBuffer.append(SystemConfigSharedConstants.APPLICATION_CONTEXT_PATH_XML); String applicationContextFilePath = applicationContextFilePathBuffer.toString(); File applicationContextFile = new File(applicationContextFilePath); LOGGER.info("Making entry for " + pluginApplicationContextPath + " in the application context file at: " + applicationContextFilePath); try {/*www. jav a2s .c om*/ Document xmlDocument = XMLUtil.createDocumentFrom(applicationContextFile); NodeList beanTags = xmlDocument.getElementsByTagName(SystemConfigSharedConstants.BEANS_TAG); if (beanTags != null) { String searchTag = SystemConfigSharedConstants.BEANS_TAG; // Get the 1st bean node from Node beanNode = getFirstNodeOfType(beanTags, searchTag); Node importNodesClone = null; NodeList beanChildNodes = beanNode.getChildNodes(); searchTag = SystemConfigSharedConstants.IMPORT_TAG; importNodesClone = getFirstNodeOfType(beanChildNodes, searchTag); Node cloneNode = importNodesClone.cloneNode(true); cloneNode.getAttributes().getNamedItem(SystemConfigSharedConstants.RESOURCE).setTextContent( SystemConfigSharedConstants.CLASSPATH_META_INF + pluginApplicationContextPath); beanNode.insertBefore(cloneNode, importNodesClone); Source source = new DOMSource(xmlDocument); File batchXmlFile = new File(applicationContextFilePath); Result result = new StreamResult(batchXmlFile); Transformer xformer = null; try { xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, SystemConfigSharedConstants.YES); xformer.setOutputProperty(SystemConfigSharedConstants.XML_INDENT_AMOUNT, String.valueOf(2)); } catch (TransformerConfigurationException e) { String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE; LOGGER.error(errorMsg + e.getMessage(), e); throw new UIException(errorMsg); } catch (TransformerFactoryConfigurationError e) { String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE; LOGGER.error(errorMsg + e.getMessage(), e); throw new UIException(errorMsg); } try { xformer.transform(source, result); } catch (TransformerException e) { String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE; LOGGER.error(errorMsg + e.getMessage(), e); throw new UIException(errorMsg); } LOGGER.info("Application Context Entry made successfully."); } } catch (Exception e) { String errorMsg = SystemConfigSharedConstants.APPLICATION_CONTEXT_ENTRY_ERROR_MESSAGE; LOGGER.error(errorMsg + e.getMessage()); throw new UIException(errorMsg); } }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Adds the provided new node before the element selected by the xPath in the given node. * /*from ww w . jav a 2s . co m*/ * @param node * The node. * @param xPath * The xPath. * @param newNode * The new node. * @return The resulting node after the substitution. * @throws Exception * If anything fails. */ public static Node addBefore(final Node node, final String xPath, final Node newNode) throws Exception { Node result = node; Node after = selectSingleNode(result, xPath); assertNotNull("No node for xpath found [" + xPath + "]", after); Node parent = after.getParentNode(); parent.insertBefore(newNode, after); return result; }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Adds the provided new node after the element selected by the xPath in the given node. * //from ww w . j a va2 s. c o m * @param node * The node. * @param xPath * The xPath. * @param newNode * The new node. * @return The resulting node after the substitution. * @throws Exception * If anything fails. */ public static Node addAfter(final Node node, final String xPath, final Node newNode) throws Exception { Node result = node; Node before = selectSingleNode(result, xPath); assertNotNull("No node for xpath [" + xPath + "] found", before); Node parent = before.getParentNode(); parent.insertBefore(newNode, before.getNextSibling()); return result; }
From source file:de.escidoc.core.test.EscidocTestBase.java
/** * Adds the provided new node as the child of the element selected by the xPath in the given node. * /*from w w w . j a va 2s. co m*/ * @param node * The node. * @param xPath * The xPath. * @param newNode * The new node. * @return The resulting node after the substitution. * @throws Exception * If anything fails. */ public static Node addAsChild(final Node node, final String xPath, final Element newNode) throws Exception { Node result = node; Node parent = selectSingleNode(result, xPath); assertNotNull("No node for xpath found [" + xPath + "]", parent); // inserts at end of list parent.insertBefore(newNode, null); return result; }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
/** * Add a tag of the form below under the given node: * //w w w .ja v a 2 s . c om * <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.ext.portlet.epsos.EpsosHelperService.java
public byte[] generateDispensationDocumentFromPrescription(byte[] bytes, List<ViewResult> lines, List<ViewResult> dispensedLines, SpiritUserClientDto doctor, User user) { byte[] bytesED = null; try {//from w w w . ja v a 2 s.c o m DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(bytes)); XPath xpath = XPathFactory.newInstance().newXPath(); // TODO change effective time // TODO change language code to fit dispenser // TODO change OID, have to use country b OID // TODO author must be the dispenser not the prescriber // TODO custodian and legal authenticator should be not copied from ep doc // TODO // fixes // First I have to check if exists in order not to create it fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr", "state", "N/A"); // add telecom to patient role fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "state", "N/A"); // add street Address Line fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr", "streetAddressLine", "N/A"); // add City fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr", "city", "N/A"); // add postalcode fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr", "postalCode", "N/A"); fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "streetAddressLine", "N/A"); fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "city", "N/A"); fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "postalCode", "N/A"); changeNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization", "name", "N/A"); fixNode(dom, xpath, "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/author/assignedAuthor/representedOrganization/addr", "postalCode", "N/A"); String ful_ext = ""; String ful_root = ""; XPathExpression ful1 = xpath.compile("/ClinicalDocument/component/structuredBody/component/section/id"); NodeList fulRONodes = (NodeList) ful1.evaluate(dom, XPathConstants.NODESET); if (fulRONodes.getLength() > 0) { for (int t = 0; t < fulRONodes.getLength(); t++) { Node AddrNode = fulRONodes.item(t); try { ful_ext = AddrNode.getAttributes().getNamedItem("extension").getNodeValue() + ""; ful_root = AddrNode.getAttributes().getNamedItem("root").getNodeValue() + ""; } catch (Exception e) { } } } // fix infullfillment XPathExpression rootNodeExpr = xpath.compile("/ClinicalDocument"); Node rootNode = (Node) rootNodeExpr.evaluate(dom, XPathConstants.NODE); try { Node infulfilment = null; XPathExpression salRO = xpath.compile("/ClinicalDocument/inFulfillmentOf"); NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET); if (salRONodes.getLength() == 0) { XPathExpression salAddr = xpath.compile("/ClinicalDocument/relatedDocument"); NodeList salAddrNodes = (NodeList) salAddr.evaluate(dom, XPathConstants.NODESET); if (salAddrNodes.getLength() > 0) { for (int t = 0; t < salAddrNodes.getLength(); t++) { Node AddrNode = salAddrNodes.item(t); Node order = dom.createElement("inFulfillmentOf"); //legalNode.appendChild(order); /* * <relatedDocument typeCode="XFRM"> * <parentDocument> * <id extension="2601010002.pdf.ep.52105899467.52105899468:39" root="2.16.840.1.113883.2.24.2.30"/> * </parentDocument> * </relatedDocument> * * */ //Node order1 = dom.createElement("order"); Node order1 = dom.createElement("relatedDocument"); Node parentDoc = dom.createElement("parentDocument"); addAttribute(dom, parentDoc, "typeCode", "XFRM"); order1.appendChild(parentDoc); Node orderNode = dom.createElement("id"); addAttribute(dom, orderNode, "extension", ful_ext); addAttribute(dom, orderNode, "root", ful_root); parentDoc.appendChild(orderNode); rootNode.insertBefore(order, AddrNode); infulfilment = rootNode.cloneNode(true); } } } } catch (Exception e) { _log.error("Error fixing node inFulfillmentOf ..."); } XPathExpression Telecom = xpath .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization"); NodeList TelecomNodes = (NodeList) Telecom.evaluate(dom, XPathConstants.NODESET); if (TelecomNodes.getLength() == 0) { for (int t = 0; t < TelecomNodes.getLength(); t++) { Node TelecomNode = TelecomNodes.item(t); Node telecom = dom.createElement("telecom"); addAttribute(dom, telecom, "use", "WP"); addAttribute(dom, telecom, "value", "mailto:demo@epsos.eu"); TelecomNode.insertBefore(telecom, TelecomNodes.item(0)); } } // header xpaths XPathExpression clinicalDocExpr = xpath.compile("/ClinicalDocument"); Node clinicalDocNode = (Node) clinicalDocExpr.evaluate(dom, XPathConstants.NODE); if (clinicalDocNode != null) { addAttribute(dom, clinicalDocNode, "xmlns", "urn:hl7-org:v3"); addAttribute(dom, clinicalDocNode, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); addAttribute(dom, clinicalDocNode, "xsi:schemaLocation", "urn:hl7-org:v3 CDASchema/CDA_extended.xsd"); addAttribute(dom, clinicalDocNode, "classCode", "DOCCLIN"); addAttribute(dom, clinicalDocNode, "moodCode", "EVN"); } XPathExpression docTemplateIdExpr = xpath.compile("/ClinicalDocument/templateId"); XPathExpression docCodeExpr = xpath.compile("/ClinicalDocument/code[@codeSystemName='" + XML_LOINC_SYSTEM + "' and @codeSystem='" + XML_LOINC_CODESYSTEM + "']"); XPathExpression docTitleExpr = xpath.compile("/ClinicalDocument/title"); // change templateId / LOINC code / title to dispensation root code NodeList templateIdNodes = (NodeList) docTemplateIdExpr.evaluate(dom, XPathConstants.NODESET); if (templateIdNodes != null) { for (int t = 0; t < templateIdNodes.getLength(); t++) { Node templateIdNode = templateIdNodes.item(t); templateIdNode.getAttributes().getNamedItem("root").setNodeValue(XML_DISPENSATION_TEMPLATEID); if (t > 0) templateIdNode.getParentNode().removeChild(templateIdNode); // remove extra templateId nodes } } Node codeNode = (Node) docCodeExpr.evaluate(dom, XPathConstants.NODE); if (codeNode != null) { if (codeNode.getAttributes().getNamedItem("code") != null) codeNode.getAttributes().getNamedItem("code").setNodeValue(XML_DISPENSATION_LOINC_CODE); if (codeNode.getAttributes().getNamedItem("displayName") != null) codeNode.getAttributes().getNamedItem("displayName").setNodeValue("eDispensation"); if (codeNode.getAttributes().getNamedItem("codeSystemName") != null) codeNode.getAttributes().getNamedItem("codeSystemName") .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEMNAME); if (codeNode.getAttributes().getNamedItem("codeSystem") != null) codeNode.getAttributes().getNamedItem("codeSystem") .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEM); } Node titleNode = (Node) docTitleExpr.evaluate(dom, XPathConstants.NODE); if (titleNode != null) { titleNode.setTextContent(XML_DISPENSATION_TITLE); } XPathExpression sectionExpr = xpath .compile("/ClinicalDocument/component/structuredBody/component/section[templateId/@root='" + XML_PRESCRIPTION_ENTRY_TEMPLATEID + "']"); XPathExpression substanceExpr = xpath.compile("entry/substanceAdministration"); XPathExpression idExpr = xpath.compile("id"); NodeList prescriptionNodes = (NodeList) sectionExpr.evaluate(dom, XPathConstants.NODESET); // substanceAdministration.appendChild(newAuthorNode); if (prescriptionNodes != null && prescriptionNodes.getLength() > 0) { // calculate list of prescription ids to keep // calculate list of prescription lines to keep Set<String> prescriptionIdsToKeep = new HashSet<String>(); Set<String> materialIdsToKeep = new HashSet<String>(); HashMap<String, Node> materialReferences = new HashMap<String, Node>(); if (dispensedLines != null && dispensedLines.size() > 0) { for (int i = 0; i < dispensedLines.size(); i++) { ViewResult d_line = dispensedLines.get(i); materialIdsToKeep.add((String) d_line.getField10()); prescriptionIdsToKeep.add((String) d_line.getField9()); } } Node structuredBodyNode = null; for (int p = 0; p < prescriptionNodes.getLength(); p++) { // for each one of the prescription nodes (<component> tags) check if their id belongs to the list of prescription Ids to keep in dispensation document Node sectionNode = prescriptionNodes.item(p); Node idNode = (Node) idExpr.evaluate(sectionNode, XPathConstants.NODE); String prescrId = idNode.getAttributes().getNamedItem("extension").getNodeValue(); if (prescriptionIdsToKeep.contains(prescrId)) { NodeList substanceAdministrationNodes = (NodeList) substanceExpr.evaluate(sectionNode, XPathConstants.NODESET); if (substanceAdministrationNodes != null && substanceAdministrationNodes.getLength() > 0) { for (int s = 0; s < substanceAdministrationNodes.getLength(); s++) { // for each of the entries (substanceAdministration tags) within this prescription node // check if the materialid in question is one of the dispensed ones, else do nothing Node substanceAdministration = (Node) substanceAdministrationNodes.item(s); Node substanceIdNode = (Node) idExpr.evaluate(substanceAdministration, XPathConstants.NODE); String materialid = ""; try { materialid = substanceIdNode.getAttributes().getNamedItem("extension") .getNodeValue(); } catch (Exception e) { _log.error("error setting materialid"); } if (materialIdsToKeep.contains(materialid)) { // if the materialid is one of the dispensed ones, keep the substanceAdminstration node intact, // as it will be used as an entryRelationship in the dispensation entry we will create Node entryRelationshipNode = dom.createElement("entryRelationship"); addAttribute(dom, entryRelationshipNode, "typeCode", "REFR"); addTemplateId(dom, entryRelationshipNode, XML_DISPENSTATION_ENTRY_REFERENCEID); entryRelationshipNode.appendChild(substanceAdministration); materialReferences.put(materialid, entryRelationshipNode); } } } } // Then delete this node, dispensed lines will be written afterwards Node componentNode = sectionNode.getParentNode(); // component structuredBodyNode = componentNode.getParentNode(); // structuredBody structuredBodyNode.removeChild(componentNode); } // at the end of this for loop, prescription lines are removed from the document, and materialReferences hashmap contains // a mapping from materialId to ready nodes containing the entry relationship references to the corresponding prescription lines Node dispComponent = dom.createElement("component"); Node dispSection = dom.createElement("section"); addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_PARENT_TEMPLATEID); addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_TEMPLATEID); Node dispIdNode = dom.createElement("id"); //addAttribute(dom, dispIdNode, "root", prescriptionIdsToKeep.iterator().next()); addAttribute(dom, dispIdNode, "root", ful_root); addAttribute(dom, dispIdNode, "extension", ful_ext); dispSection.appendChild(dispIdNode); Node sectionCodeNode = dom.createElement("code"); addAttribute(dom, sectionCodeNode, "code", "60590-7"); addAttribute(dom, sectionCodeNode, "displayName", XML_DISPENSATION_TITLE); addAttribute(dom, sectionCodeNode, "codeSystem", XML_DISPENSATION_LOINC_CODESYSTEM); addAttribute(dom, sectionCodeNode, "codeSystemName", XML_DISPENSATION_LOINC_CODESYSTEMNAME); dispSection.appendChild(sectionCodeNode); Node title = dom.createElement("title"); title.setTextContent(XML_DISPENSATION_TITLE); dispSection.appendChild(title); Node text = dom.createElement("text"); Node textContent = this.generateDispensedLinesHtml(dispensedLines, db); textContent = textContent.cloneNode(true); dom.adoptNode(textContent); text.appendChild(textContent); dispSection.appendChild(text); dispComponent.appendChild(dispSection); structuredBodyNode.appendChild(dispComponent); for (int i = 0; i < dispensedLines.size(); i++) { ViewResult d_line = dispensedLines.get(i); String materialid = (String) d_line.getField10(); // for each dispensed line create a dispensation entry in the document, and use the entryRelationship calculated above Node entry = dom.createElement("entry"); Node supply = dom.createElement("supply"); addAttribute(dom, supply, "classCode", "SPLY"); addAttribute(dom, supply, "moodCode", "EVN"); // add templateId tags addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE1); addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE2); addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE3); // add id tag Node supplyId = dom.createElement("id"); addAttribute(dom, supplyId, "root", XML_DISPENSATION_ENTRY_SUPPLY_ID_ROOT); addAttribute(dom, supplyId, "extension", (String) d_line.getField1()); supply.appendChild(supplyId); // add quantity tag Node quantity = dom.createElement("quantity"); String nrOfPacks = (String) d_line.getField8(); nrOfPacks = nrOfPacks.trim(); String value = nrOfPacks; String unit = "1"; if (nrOfPacks.indexOf(" ") != -1) { value = nrOfPacks.substring(0, nrOfPacks.indexOf(" ")); unit = nrOfPacks.substring(nrOfPacks.indexOf(" ") + 1); } addAttribute(dom, quantity, "value", (String) d_line.getField7()); addAttribute(dom, quantity, "unit", (String) d_line.getField12()); supply.appendChild(quantity); // add product tag addProductTag(dom, supply, d_line, materialReferences.get(materialid)); // add performer tag addPerformerTag(dom, supply, doctor); // add entryRelationship tag supply.appendChild(materialReferences.get(materialid)); // add substitution relationship tag if (d_line.getField3() != null && ((Boolean) d_line.getField3()).booleanValue()) { Node substitutionNode = dom.createElement("entryRelationship"); addAttribute(dom, substitutionNode, "typeCode", "COMP"); Node substanceAdminNode = dom.createElement("substanceAdministration"); addAttribute(dom, substanceAdminNode, "classCode", "SBADM"); addAttribute(dom, substanceAdminNode, "moodCode", "INT"); Node seqNode = dom.createElement("doseQuantity"); addAttribute(dom, seqNode, "value", "1"); addAttribute(dom, seqNode, "unit", "1"); substanceAdminNode.appendChild(seqNode); substitutionNode.appendChild(substanceAdminNode); // changed quantity if (lines.get(0).getField21().equals(d_line.getField7())) { } // changed name if (lines.get(0).getField11().equals(d_line.getField2())) { } supply.appendChild(substitutionNode); } entry.appendChild(supply); dispSection.appendChild(entry); } } // copy author tag from eprescription XPathExpression authorExpr = xpath.compile("/ClinicalDocument/author"); Node oldAuthorNode = (Node) authorExpr.evaluate(dom, XPathConstants.NODE); Node newAuthorNode = oldAuthorNode.cloneNode(true); XPathExpression substExpr = xpath.compile( "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration"); NodeList substNodes = (NodeList) substExpr.evaluate(dom, XPathConstants.NODESET); XPathExpression entryRelExpr = xpath.compile( "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/entryRelationship"); NodeList entryRelNodes = (NodeList) entryRelExpr.evaluate(dom, XPathConstants.NODESET); Node entryRelNode = (Node) entryRelExpr.evaluate(dom, XPathConstants.NODE); if (substNodes != null) { // for (int t=0; t<substNodes.getLength(); t++) // { int t = 0; Node substNode = substNodes.item(t); substNode.insertBefore(newAuthorNode, entryRelNode); // } } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(dom); transformer.transform(source, result); String xmlString = result.getWriter().toString(); bytesED = xmlString.getBytes(); System.out.println(xmlString); } catch (Exception e) { _log.error(e.getMessage()); } return bytesED; }
From source file:nl.b3p.viewer.stripes.SldActionBean.java
private void addFilterToExistingSld() throws Exception { Filter f = CQL.toFilter(filter); f = (Filter) f.accept(new ChangeMatchCase(false), null); if (featureTypeName == null) { featureTypeName = layer;//ww w . j a v a2 s .c o m } FeatureTypeConstraint ftc = sldFactory.createFeatureTypeConstraint(featureTypeName, f, new Extent[] {}); if (newSld == null) { SLDTransformer sldTransformer = new SLDTransformer(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); sldTransformer.transform(ftc, bos); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document sldXmlDoc = db.parse(new ByteArrayInputStream(sldXml)); Document ftcDoc = db.parse(new ByteArrayInputStream(bos.toByteArray())); String sldVersion = sldXmlDoc.getDocumentElement().getAttribute("version"); if ("1.1.0".equals(sldVersion)) { // replace sld:FeatureTypeName element generated by GeoTools // by se:FeatureTypeName NodeList sldFTNs = ftcDoc.getElementsByTagNameNS(NS_SLD, "FeatureTypeName"); if (sldFTNs.getLength() == 1) { Node sldFTN = sldFTNs.item(0); Node seFTN = ftcDoc.createElementNS(NS_SE, "FeatureTypeName"); seFTN.setTextContent(sldFTN.getTextContent()); sldFTN.getParentNode().replaceChild(seFTN, sldFTN); } } // Ignore namespaces to tackle both SLD 1.0.0 and SLD 1.1.0 // Add constraint to all NamedLayers, not only to the layer specified // in layers parameter NodeList namedLayers = sldXmlDoc.getElementsByTagNameNS(NS_SLD, "NamedLayer"); for (int i = 0; i < namedLayers.getLength(); i++) { Node namedLayer = namedLayers.item(i); // Search where to insert the FeatureTypeConstraint from our ftcDoc // Insert LayerFeatureConstraints after sld:Name, se:Name or se:Description // and before sld:NamedStyle or sld:UserStyle so search backwards. // If we find an existing LayerFeatureConstraints, use that NodeList childs = namedLayer.getChildNodes(); Node insertBefore = null; Node layerFeatureConstraints = null; int j = childs.getLength() - 1; do { Node child = childs.item(j); if ("LayerFeatureConstraints".equals(child.getLocalName())) { layerFeatureConstraints = child; break; } if ("Description".equals(child.getLocalName()) || "Name".equals(child.getLocalName())) { break; } insertBefore = child; j--; } while (j >= 0); Node featureTypeConstraint = sldXmlDoc.adoptNode(ftcDoc.getDocumentElement().cloneNode(true)); if (layerFeatureConstraints == null) { layerFeatureConstraints = sldXmlDoc.createElementNS(NS_SLD, "LayerFeatureConstraints"); layerFeatureConstraints.appendChild(featureTypeConstraint); namedLayer.insertBefore(layerFeatureConstraints, insertBefore); } else { layerFeatureConstraints.appendChild(featureTypeConstraint); } } TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(sldXmlDoc); bos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(bos); t.transform(source, result); sldXml = bos.toByteArray(); } }
From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java
/***** * Adds a new node or replaces an existing node in the Document * // w w w .j a v a 2 s. c om * @param doc Target document where the node will added * @param xmlEntity contains definition of the xml entity * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws XPathExpressionException */ public static void addNewNode(final Document doc, final XmlEntity xmlEntity) throws IOException, XPathExpressionException, SAXException, ParserConfigurationException { // Build up map per call to avoid issues with caching wrong version of the map. final LinkedHashMap<String, CacheElement> elementOrderMap = CacheElement.buildElementMap(doc); final Node newNode = createNode(doc, xmlEntity.getXmlDefinition()); final Node root = doc.getDocumentElement(); final int incomingElementOrder = getElementOrder(elementOrderMap, xmlEntity.getNamespace(), xmlEntity.getType()); boolean nodeAdded = false; NodeList nodes = root.getChildNodes(); final int length = nodes.getLength(); for (int i = 0; i < length; i++) { final Node node = nodes.item(i); if (node instanceof Element) { final Element childElement = (Element) node; final String type = childElement.getLocalName(); final String namespace = childElement.getNamespaceURI(); if (namespace.equals(xmlEntity.getNamespace()) && type.equals(xmlEntity.getType())) { // First check if the element has a name String nameOrId = getAttribute(childElement, "name"); // If not then check if the element has an Id if (nameOrId == null) { nameOrId = getAttribute(childElement, "id"); } if (nameOrId != null) { // If there is a match , then replace the existing node with the incoming node if (nameOrId.equals(xmlEntity.getNameOrId())) { root.replaceChild(newNode, node); nodeAdded = true; break; } } else { // This element does not have any name or id identifier for e.g PDX and gateway-receiver // If there is only one element of that type then replace it with the incoming node if (!isMultiple(elementOrderMap, namespace, type)) { root.replaceChild(newNode, node); nodeAdded = true; break; } } } else { if (incomingElementOrder < getElementOrder(elementOrderMap, namespace, type)) { root.insertBefore(newNode, node); nodeAdded = true; break; } } } } if (!nodeAdded) { root.appendChild(newNode); } }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMXMLSignature.java
public void marshal(Node parent, Node nextSibling, String dsPrefix, DOMCryptoContext context) throws MarshalException { ownerDoc = DOMUtils.getOwnerDocument(parent); sigElem = DOMUtils.createElement(ownerDoc, "Signature", XMLSignature.XMLNS, dsPrefix); // append xmlns attribute if (dsPrefix == null || dsPrefix.length() == 0) { sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", XMLSignature.XMLNS); } else {//from w ww .ja v a 2 s. c om sigElem.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + dsPrefix, XMLSignature.XMLNS); } // create and append SignedInfo element ((DOMSignedInfo) si).marshal(sigElem, dsPrefix, context); // create and append SignatureValue element ((DOMSignatureValue) sv).marshal(sigElem, dsPrefix, context); // create and append KeyInfo element if necessary if (ki != null) { ((DOMKeyInfo) ki).marshal(sigElem, null, dsPrefix, context); } // create and append Object elements if necessary for (int i = 0, size = objects.size(); i < size; i++) { ((DOMXMLObject) objects.get(i)).marshal(sigElem, dsPrefix, context); } // append Id attribute DOMUtils.setAttributeID(sigElem, "Id", id); parent.insertBefore(sigElem, nextSibling); }
From source file:org.apache.ofbiz.webtools.labelmanager.SaveLabelsToXmlFile.java
public static Map<String, Object> saveLabelsToXmlFile(DispatchContext dctx, Map<String, ? extends Object> context) { Locale locale = (Locale) context.get("locale"); String fileName = (String) context.get("fileName"); if (UtilValidate.isEmpty(fileName)) { Debug.logError("labelFileName cannot be empty", module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale)); }/*from w w w .jav a 2s . co m*/ String key = (String) context.get("key"); String keyComment = (String) context.get("keyComment"); String update_label = (String) context.get("update_label"); String confirm = (String) context.get("confirm"); String removeLabel = (String) context.get("removeLabel"); List<String> localeNames = UtilGenerics.cast(context.get("localeNames")); List<String> localeValues = UtilGenerics.cast(context.get("localeValues")); List<String> localeComments = UtilGenerics.cast(context.get("localeComments")); String apacheLicenseText = null; try { apacheLicenseText = FileUtil.readString("UTF-8", FileUtil.getFile("component://webtools/config/APACHE2_HEADER_FOR_XML")); } catch (IOException e) { Debug.logWarning(e, "Unable to read Apache License text file", module); } try { LabelManagerFactory factory = LabelManagerFactory.getInstance(); LabelFile labelFile = factory.getLabelFile(fileName); if (labelFile == null) { Debug.logError("Invalid file name: " + fileName, module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale)); } synchronized (SaveLabelsToXmlFile.class) { factory.findMatchingLabels(null, fileName, null, null, false); Map<String, LabelInfo> labels = factory.getLabels(); Set<String> labelsList = factory.getLabelsList(); Set<String> localesFound = factory.getLocalesFound(); for (String localeName : localeNames) { localesFound.add(localeName); } // Remove a Label if (UtilValidate.isNotEmpty(removeLabel)) { labels.remove(key + LabelManagerFactory.keySeparator + fileName); } else if (UtilValidate.isNotEmpty(confirm)) { LabelInfo label = labels.get(key + LabelManagerFactory.keySeparator + fileName); // Update a Label if (update_label.equalsIgnoreCase("Y")) { if (UtilValidate.isNotEmpty(label)) { factory.updateLabelValue(localeNames, localeValues, localeComments, label, key, keyComment, fileName); } // Insert a new Label } else { if (UtilValidate.isNotEmpty(label)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelExisting", UtilMisc.toMap("key", key, "fileName", fileName), locale)); } else { if (UtilValidate.isEmpty(key)) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelEmptyKey", locale)); } else { int notEmptyLabels = factory.updateLabelValue(localeNames, localeValues, localeComments, null, key, keyComment, fileName); if (notEmptyLabels == 0) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelEmpty", locale)); } } } } } Document resourceDocument = UtilXml.makeEmptyXmlDocument("resource"); Element resourceElem = resourceDocument.getDocumentElement(); resourceElem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); resourceElem.setAttribute("xsi:noNamespaceSchemaLocation", "http://ofbiz.apache.org/dtds/ofbiz-properties.xsd"); for (String labelKey : labelsList) { LabelInfo labelInfo = labels.get(labelKey); if (!(labelInfo.getFileName().equalsIgnoreCase(fileName))) { continue; } Element propertyElem = UtilXml.addChildElement(resourceElem, "property", resourceDocument); propertyElem.setAttribute("key", StringEscapeUtils.unescapeHtml(labelInfo.getLabelKey())); if (UtilValidate.isNotEmpty(labelInfo.getLabelKeyComment())) { Comment labelKeyComment = resourceDocument .createComment(StringEscapeUtils.unescapeHtml(labelInfo.getLabelKeyComment())); Node parent = propertyElem.getParentNode(); parent.insertBefore(labelKeyComment, propertyElem); } for (String localeFound : localesFound) { LabelValue labelValue = labelInfo.getLabelValue(localeFound); String valueString = null; if (labelValue != null) { valueString = labelValue.getLabelValue(); } if (UtilValidate.isNotEmpty(valueString)) { valueString = StringEscapeUtils.unescapeHtml(valueString); Element valueElem = UtilXml.addChildElementValue(propertyElem, "value", valueString, resourceDocument); valueElem.setAttribute("xml:lang", localeFound); if (UtilValidate.isNotEmpty(labelValue.getLabelComment())) { Comment labelComment = resourceDocument.createComment( StringEscapeUtils.unescapeHtml(labelValue.getLabelComment())); Node parent = valueElem.getParentNode(); parent.insertBefore(labelComment, valueElem); } } } FileOutputStream fos = new FileOutputStream(labelFile.file); try { if (apacheLicenseText != null) { fos.write(apacheLicenseText.getBytes()); } UtilXml.writeXmlDocument(resourceElem, fos, "UTF-8", !(apacheLicenseText == null), true, 4); } finally { fos.close(); // clear cache to see immediately the new labels and // translations in OFBiz UtilCache.clearCache("properties.UtilPropertiesBundleCache"); } } } } catch (Exception e) { Debug.logError(e, "Exception during save labels to xml file:", module); return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale)); } return ServiceUtil.returnSuccess(); }