Example usage for org.w3c.dom Node cloneNode

List of usage examples for org.w3c.dom Node cloneNode

Introduction

In this page you can find the example usage for org.w3c.dom Node cloneNode.

Prototype

public Node cloneNode(boolean deep);

Source Link

Document

Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.

Usage

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private void mergeAttributes(Node source, Node target, Document targetDocument) {
    for (int i = 0, len = source.getAttributes().getLength(); i < len; i++) {
        final Node attrToMerge = source.getAttributes().item(i);
        final String attrName = attrToMerge.getNodeName();
        final String attrValue = attrToMerge.getNodeValue();
        final Optional<Node> existingAttr = findAttribute(target, attrToMerge);
        if (existingAttr.isPresent()) {
            final String[] existingValues = split(existingAttr.get().getNodeValue());

            if (attrName.endsWith(":schemaLocation") || attrName.equals("schemaLocation")) {
                final List<Pair> existingPairs = toPairs(existingValues);
                final List<Pair> newPairs = toPairs(split(attrValue));
                final String toAdd = newPairs.stream()
                        .filter(p -> existingPairs.stream().noneMatch(x -> x.sameFirst(p)))
                        .map(p -> p.first + " " + p.second).collect(Collectors.joining(" "));
                if (!toAdd.isEmpty()) {
                    existingAttr.get().setNodeValue(existingAttr.get().getNodeValue() + " " + toAdd);
                }//from  w w  w.j  ava 2  s.c o m
                continue;
            }

            // merge value
            if (Stream.of(existingValues).noneMatch(value -> value.equals(attrToMerge.getNodeValue()))) {
                if (existingValues.length == 0) {
                    debug("adding missing attribute value " + attrName + "=" + attrValue);
                    existingAttr.get().setNodeValue(attrValue);
                } else {
                    debug("Appending existing attribute " + existingAttr.get().getNodeName() + "=" + attrValue);
                    existingAttr.get().setNodeValue(existingAttr.get().getNodeValue() + " " + attrValue);
                }
            } else {
                debug("Already present: attribute " + existingAttr.get().getNodeName() + "=" + attrValue);
            }
        } else {
            debug("Adding new attribute " + attrName + "=" + attrValue);
            final Node cloned = targetDocument.adoptNode(attrToMerge.cloneNode(true));
            target.getAttributes().setNamedItem(cloned);
        }
    }
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

/**
 * Add a tag of the form below under the given node:
 * /*from w  w w . j a  v a  2  s.com*/
 * <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 {/*  w  w  w  .java2 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:org.adl.sequencer.ADLSeqUtilities.java

/**
 * Initializes one activity (<code>SeqActivity</code>) that will be added to
 * an activity tree./*  w ww . j a v  a 2  s  . c  o  m*/
 * 
 * @param iNode   A node from the DOM tree of an element containing
 *                sequencing information.
 * 
 * @param iColl   The collection of reusable sequencing information.
 * 
 * @return An initialized activity (<code>SeqActivity</code>), or <code>
 *         null</code> if there was an error initializing the activity.
 */
private static SeqActivity buildActivityNode(Node iNode, Node iColl) {

    if (_Debug) {
        System.out.println("  :: ADLSeqUtilities  --> BEGIN - " + "buildActivityNode");
    }

    SeqActivity act = new SeqActivity();

    boolean error = false;

    String tempVal = null;

    // Set the activity's ID -- this is a required attribute
    act.setID(ADLSeqUtilities.getAttribute(iNode, "identifier"));

    // Get the activity's resource ID -- if it exsits
    tempVal = ADLSeqUtilities.getAttribute(iNode, "identifierref");
    if (tempVal != null) {
        if (!isEmpty(tempVal)) {
            act.setResourceID(tempVal);
        }
    }

    // Check if the activity is visible
    tempVal = ADLSeqUtilities.getAttribute(iNode, "isvisible");
    if (tempVal != null) {
        if (!isEmpty(tempVal)) {
            act.setIsVisible((Boolean.valueOf(tempVal)).booleanValue());
        }
    }

    // Get the children elements of this activity 
    NodeList children = iNode.getChildNodes();

    // Initalize this activity from the information in the DOM  
    for (int i = 0; i < children.getLength(); i++) {
        Node curNode = children.item(i);

        // Check to see if this is an element node.
        if (curNode.getNodeType() == Node.ELEMENT_NODE) {
            if (curNode.getLocalName().equals("item")) {

                if (_Debug) {
                    System.out.println("  ::--> Found an <item> element");
                }

                // Initialize the nested activity
                SeqActivity nestedAct = ADLSeqUtilities.buildActivityNode(curNode, iColl);

                // Make sure this activity was created successfully
                if (nestedAct != null) {
                    if (_Debug) {
                        System.out.println("  ::--> Adding child");
                    }

                    act.addChild(nestedAct);

                } else {
                    error = true;
                }
            } else if (curNode.getLocalName().equals("title")) {

                if (_Debug) {
                    System.out.println("  ::--> Found the <title> element");
                }

                act.setTitle(ADLSeqUtilities.getElementText(curNode, null));
            } else if (curNode.getLocalName().equals("sequencing")) {

                if (_Debug) {
                    System.out.println("  ::--> Found the <sequencing> element");
                }

                Node seqInfo = curNode;

                // Check to see if the sequencing information is referenced in 
                // the <sequencingCollection>
                tempVal = ADLSeqUtilities.getAttribute(curNode, "IDRef");
                if (tempVal != null) {
                    // Combine local and global sequencing information
                    // Get the referenced Global sequencing information
                    String search = "imsss:sequencing[@ID='" + tempVal + "']";

                    if (_Debug) {
                        System.out.println("  ::--> Looking for XPATH --> " + search);
                    }

                    // Use the referenced set of sequencing information
                    Node seqGlobal = null;

                    XPathFactory pathFactory = XPathFactory.newInstance();
                    XPath path = pathFactory.newXPath();

                    try {
                        seqGlobal = (Node) path.evaluate(search, iColl, XPathConstants.NODE);
                        //XPathAPI.selectSingleNode(iColl, search);
                    } catch (Exception e) {
                        if (_Debug) {
                            System.out.println("  ::--> ERROR : In transform");
                            e.printStackTrace();
                        }
                    }

                    if (seqGlobal != null) {
                        if (_Debug) {
                            System.out.println("  ::--> FOUND");
                        }
                    } else {
                        if (_Debug) {
                            System.out.println("  ::--> ERROR: Not Found");
                        }

                        seqInfo = null;
                        error = true;
                    }

                    if (!error) {

                        // Clone the global node
                        seqInfo = seqGlobal.cloneNode(true);

                        // Loop through the local sequencing element
                        NodeList seqChildren = curNode.getChildNodes();
                        for (int j = 0; j < seqChildren.getLength(); j++) {

                            Node curChild = seqChildren.item(j);

                            // Check to see if this is an element node.
                            if (curChild.getNodeType() == Node.ELEMENT_NODE) {
                                if (_Debug) {
                                    System.out.println("  ::--> Local definition");
                                    System.out.println("  ::-->   " + j);
                                    System.out.println("  ::-->  <" + curChild.getLocalName() + ">");
                                }

                                // Add this to the global sequencing info
                                try {
                                    seqInfo.appendChild(curChild);
                                } catch (org.w3c.dom.DOMException e) {
                                    if (_Debug) {
                                        System.out.println("  ::--> ERROR: ");
                                        e.printStackTrace();
                                    }

                                    error = true;
                                    seqInfo = null;
                                }
                            }
                        }
                    }
                }

                // If we have an node to look at, extract its sequencing info
                if (seqInfo != null) {
                    // Record this activity's sequencing XML fragment
                    //                  XMLSerializer serializer = new XMLSerializer();

                    // -+- TODO -+-
                    //                  serializer.setNewLine("CR-LF");
                    //                  act.setXMLFragment(serializer.writeToString(seqInfo));

                    // Extract the sequencing information for this activity
                    error = !ADLSeqUtilities.extractSeqInfo(seqInfo, act);

                    if (_Debug) {
                        System.out.println("  ::--> Extracted Sequencing Info");
                    }
                }
            }
        }
    }

    // Make sure this activity either has an associated resource or children
    if (act.getResourceID() == null && !act.hasChildren(true)) {
        // This is not a vaild activity -- ignore it
        error = true;
    }

    // If the activity failed to initialize, clear the variable
    if (error) {
        act = null;
    }

    if (_Debug) {
        System.out.println("  ::--> error == " + error);
        System.out.println("  :: ADLSeqUtilities  --> END   - " + "buildActivityNode");
    }

    return act;
}

From source file:org.alfresco.web.forms.xforms.XFormsBean.java

public void handleSubmit(Node result) {
    final Document instanceData = this.getXformsSession().getFormInstanceData();
    Element documentElement = instanceData.getDocumentElement();
    if (documentElement != null) {
        instanceData.removeChild(documentElement);
    }//  w ww .ja v  a 2 s . c o  m
    if (result instanceof Document) {
        result = ((Document) result).getDocumentElement();
    }
    documentElement = (Element) instanceData.importNode(result.cloneNode(true), true);
    Schema2XForms.removePrototypeNodes(documentElement);
    instanceData.appendChild(documentElement);
    instanceData.normalizeDocument();
}

From source file:org.apache.any23.extractor.html.HCardExtractor.java

private void fixIncludes(HTMLDocument document, Node node, IssueReport report) {
    NamedNodeMap attributes = node.getAttributes();
    // header case test 32
    if ("TD".equals(node.getNodeName()) && (null != attributes.getNamedItem("headers"))) {
        String id = attributes.getNamedItem("headers").getNodeValue();
        Node header = document.findNodeById(id);
        if (null != header) {
            node.appendChild(header.cloneNode(true));
            attributes.removeNamedItem("headers");
        }//from  w ww  . ja  v a 2s . c om
    }

    // include pattern, test 31
    for (Node current : DomUtils.findAllByAttributeName(document.getDocument(), "class")) {
        if (!DomUtils.hasClassName(current, "include"))
            continue;
        // we have to remove the field soon to avoid infinite loops
        // no null check, we know it's there or we won't be in the loop
        current.getAttributes().removeNamedItem("class");
        ArrayList<TextField> res = new ArrayList<TextField>();
        HTMLDocument.readUrlField(res, current);
        TextField id = res.get(0);
        if (null == id)
            continue;
        TextField refId = new TextField(StringUtils.substringAfter(id.value(), "#"), id.source());
        Node included = document.findNodeById(refId.value());
        if (null == included)
            continue;
        if (DomUtils.isAncestorOf(included, current)) {
            final int[] nodeLocation = DomUtils.getNodeLocation(current);
            report.notifyIssue(IssueReport.IssueLevel.Warning,
                    "Current node tries to include an ancestor node.", nodeLocation[0], nodeLocation[1]);
            continue;
        }
        current.appendChild(included.cloneNode(true));
    }
}

From source file:org.apache.cocoon.forms.binding.TempRepeaterJXPathBinding.java

public void doLoad(Widget frmModel, JXPathContext jctx) throws BindingException {
    // (There should be a general widget type checker for all the bindings to use,
    // coupled with a general informative exception class to throw if the widget is
    // of the wrong type or null.)
    Repeater repeater = (Repeater) selectWidget(frmModel, this.repeaterId);
    if (repeater == null) {
        String fullId = frmModel.getRequestParameterName();
        if (fullId == null || fullId.length() == 0) {
            fullId = "";
        } else {//  www  .java2  s. co  m
            fullId = fullId + ".";
        }
        throw new RuntimeException("TempRepeaterJXPathBinding: Repeater \"" + fullId + this.repeaterId
                + "\" does not exist (" + frmModel.getLocation() + ")");
    }

    // Start by clearing the repeater, if necessary.
    if (this.clearOnLoad) {
        repeater.clear();
    }

    // Find the location of the repeater data.
    Pointer repeaterPointer = jctx.getPointer(this.repeaterPath);

    // Check if there is data present.
    //
    // (Otherwise, should we check the leniency config option
    // to decide whether to be silent or throw an exception?) 
    if (repeaterPointer != null) {

        // Narrow to repeater context.
        JXPathContext repeaterContext = jctx.getRelativeContext(repeaterPointer);

        // Build a jxpath iterator for the repeater row pointers.
        Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath);

        // Iterate through the rows of data.
        int rowNum = 0;
        while (rowPointers.hasNext()) {

            // Get or create a row widget.
            Repeater.RepeaterRow thisRow;
            if (repeater.getSize() > rowNum) {
                thisRow = repeater.getRow(rowNum);
            } else {
                thisRow = repeater.addRow();
            }
            rowNum++;

            // Narrow to the row context.
            Pointer rowPointer = (Pointer) rowPointers.next();
            JXPathContext rowContext = repeaterContext.getRelativeContext(rowPointer);

            // If virtual rows are requested, place a deep clone of the row data
            // into a temporary node, and narrow the context to this virtual row.
            //
            // (A clone of the data is used to prevent modifying the source document.
            // Otherwise, the appendChild method would remove the data from the source
            // document.  Is this protection worth the penalty of a deep clone?)
            //
            // (This implementation of virtual rows currently only supports DOM
            // bindings, but could easily be extended to support other bindings.)

            if (virtualRows == true) {
                Node repeaterNode = (Node) repeaterPointer.getNode();
                Node virtualNode = repeaterNode.getOwnerDocument().createElementNS(null, "virtual");
                Node node = (Node) rowPointer.getNode();
                Node clone = node.cloneNode(true);
                Node fakeDocElement = node.getOwnerDocument().getDocumentElement().cloneNode(false);
                virtualNode.appendChild(clone);
                fakeDocElement.appendChild(virtualNode);
                rowContext = JXPathContext.newContext(repeaterContext, fakeDocElement);
                rowContext = rowContext.getRelativeContext(rowContext.getPointer("virtual"));
            }

            // Finally, perform the load row binding.
            this.rowBinding.loadFormFromModel(thisRow, rowContext);
        }
    }

    if (getLogger().isDebugEnabled())
        getLogger().debug("done loading rows " + toString());
}

From source file:org.apache.cocoon.webapps.session.context.RequestSessionContext.java

/**
 * Build parameter XML/*from  w w  w .j  a va 2s .  c  o  m*/
 */
private void buildParameterXML(Element root, SAXParser parser) {
    Document doc = root.getOwnerDocument();
    // include all parameters
    // process "/parameter" and "/parametervalues" at the same time
    Element parameterElement = doc.createElementNS(null, "parameter");
    Element parameterValuesElement = doc.createElementNS(null, "parametervalues");
    root.appendChild(parameterElement);
    root.appendChild(parameterValuesElement);
    String parameterName = null;
    Enumeration pars = this.request.getParameterNames();
    Element parameter;
    Element element;
    Node valueNode;
    String[] values;
    String parValue;

    element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, PARAMETERS_ELEMENT);
    element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cinclude",
            CIncludeTransformer.CINCLUDE_NAMESPACE_URI);
    parameterValuesElement.appendChild(element);
    parameterValuesElement = element;

    while (pars.hasMoreElements() == true) {
        parameterName = (String) pars.nextElement();
        values = this.request.getParameterValues(parameterName);

        for (int i = 0; i < values.length; i++) {

            // this is a fast test, if the parameter value contains xml!
            parValue = values[i].trim();
            if (parValue.length() > 0 && parValue.charAt(0) == '<') {
                try {
                    valueNode = DOMUtil.getDocumentFragment(parser, new StringReader(parValue));
                    valueNode = doc.importNode(valueNode, true);
                } catch (Exception noXMLException) {
                    valueNode = doc.createTextNode(parValue);
                }
            } else {
                valueNode = doc.createTextNode(parValue);
            }
            // create "/parameter" entry for first value
            if (i == 0) {
                try {
                    parameter = doc.createElementNS(null, parameterName);
                    parameter.appendChild(valueNode);
                    parameterElement.appendChild(parameter);
                } catch (Exception local) {
                    // the exception is ignored and only this parameters is ignored
                }
            }

            try {
                // create "/parametervalues" entry
                element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, PARAMETER_ELEMENT);
                parameterValuesElement.appendChild(element);
                parameter = element;
                element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, NAME_ELEMENT);
                parameter.appendChild(element);
                element.appendChild(doc.createTextNode(parameterName));
                element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, VALUE_ELEMENT);
                parameter.appendChild(element);
                element.appendChild(valueNode.cloneNode(true));
            } catch (Exception local) {
                // the exception is ignored and only this parameters is ignored
            }
        }
    }
    // and now the query string
    element = doc.createElementNS(null, "querystring");
    root.appendChild(element);
    String value = request.getQueryString();
    if (value != null) {
        element.appendChild(doc.createTextNode('?' + value));
    }
}

From source file:org.apache.openaz.xacml.util.ObjUtil.java

/**
 * Determines if two XML Nodes are equivalent, including the case where both are <code>null</code>. For
 * XML Nodes the .equals() method does not work (the objects must actually be the same Node). In this
 * project we want to allow XML with different textual layout (newlines and spaces) to be equal because
 * the text formatting is not significant to the meaning of the content. Therefore the
 * (Node).isEqualNode() method is not appropriate either. This method looks at the Node elements and each
 * of their children: - ignoring empty text nodes - ignoring comment nodes - checking that all attributes
 * on the nodes are the same - checking that each non-empty-text child is in the same order
 *
 * @param node1 the first Node object to compare
 * @param node2 the second Node object to compare
 * @return true if both objects are null, or the first is non-null and <code>equals</code> the second as
 *         described in the method description.
 *//*www. j av a 2 s.com*/
public static boolean xmlEqualsAllowNull(Node node1, Node node2) {
    if (node1 == null) {
        return node2 == null;
    } else if (node2 == null) {
        return false;
    }

    // create deep copies of the nodes so we can manipulate them before testing
    Node clone1 = node1.cloneNode(true);
    cleanXMLNode(clone1);
    Node clone2 = node2.cloneNode(true);
    cleanXMLNode(clone2);

    boolean compareReturn = compareXML(clone1, clone2);
    return compareReturn;
}

From source file:org.apache.ws.security.message.ModifiedRequestTest.java

/**
 * Test that signs a SOAP body element "value". The SOAP request is then modified
 * so that the signed "value" element is put in the header, and the value of the
 * original element is changed. This test will fail as the request will contain
 * multiple elements with the same wsu:Id.
 *//*from   ww  w.jav  a  2s  .c o  m*/
@org.junit.Test
public void testMovedElement() throws Exception {
    WSSecSignature builder = new WSSecSignature();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
    LOG.info("Before Signing....");
    Document doc = SOAPUtil.toSOAPPart(SOAPMSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
    WSEncryptionPart encP = new WSEncryptionPart("value", "http://blah.com", "");
    parts.add(encP);
    builder.setParts(parts);

    Document signedDoc = builder.build(doc, crypto, secHeader);

    //
    // Replace the signed element with a modified element, and move the original
    // signed element into the SOAP header
    //
    org.w3c.dom.Element secHeaderElement = secHeader.getSecurityHeader();
    org.w3c.dom.Element envelopeElement = signedDoc.getDocumentElement();
    org.w3c.dom.Node valueNode = envelopeElement.getElementsByTagNameNS("http://blah.com", "value").item(0);
    org.w3c.dom.Node clonedValueNode = valueNode.cloneNode(true);
    secHeaderElement.appendChild(clonedValueNode);
    valueNode.getFirstChild().setNodeValue("250");

    if (LOG.isDebugEnabled()) {
        LOG.debug("After Signing....");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }

    try {
        verify(signedDoc);
        fail("Failure expected on multiple elements with the same wsu:Id");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}