Example usage for org.w3c.dom Node setTextContent

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

Introduction

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

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:com.francelabs.datafari.servlets.admin.FieldWeight.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response) Checks if the files still exist Used to modify the weight of
 *      a field// www .j  a  va 2 s  .co  m
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        if ((config == null) || !new File(env + File.separator + "solrconfig.xml").exists()) {// If
            // the
            // files
            // did
            // not
            // existed
            // when
            // the
            // constructor
            // was
            // runned
            if (!new File(env + File.separator + "solrconfig.xml").exists()) {
                LOGGER.error(
                        "Error while opening the configuration file, solrconfig.xml, in FieldWeight doPost, please make sure this file exists at "
                                + env + "conf/ . Error 69029"); // If
                // not
                // an
                // error
                // is
                // printed
                final PrintWriter out = response.getWriter();
                out.append(
                        "Error while opening the configuration file, please retry, if the problem persists contact your system administrator. Error Code : 69029");
                out.close();
                return;
            } else {
                config = new File(env + File.separator + "solrconfig.xml");
            }
        }

        if (customSearchHandler == null) {
            if (new File(
                    env + File.separator + "customs_solrconfig" + File.separator + "custom_search_handler.incl")
                            .exists()) {
                customSearchHandler = new File(env + File.separator + "customs_solrconfig" + File.separator
                        + "custom_search_handler.incl");
            }
        }

        try {
            final String type = request.getParameter("type");

            if (searchHandler == null) {
                findSearchHandler();
            }

            if (!usingCustom) { // The custom search handler is not used.
                // That means that the current config must
                // be commented in the solrconfig.xml file
                // and the modifications must be saved in
                // the custom search handler file

                // Get the content of solrconfig.xml file as a string
                String configContent = FileUtils.getFileContent(config);

                // Retrieve the searchHandler from the configContent
                final Node originalSearchHandler = XMLUtils.getSearchHandlerNode(config);
                final String strSearchHandler = XMLUtils.nodeToString(originalSearchHandler);

                // Create a commented equivalent of the strSearchHandler
                final String commentedSearchHandler = "<!--" + strSearchHandler + "-->";

                // Replace the searchHandler in the solrconfig.xml file by
                // the commented version
                configContent = configContent.replace(strSearchHandler, commentedSearchHandler);
                FileUtils.saveStringToFile(config, configContent);

                // create the new custom_search_handler document
                doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

                // Import the search handler node from the solrconfig doc to
                // the custom search handler doc
                searchHandler = doc.importNode(searchHandler, true);

                // Make the new node an actual item in the target document
                searchHandler = doc.appendChild(searchHandler);

                final Node n = run(searchHandler.getChildNodes(), type);
                childList = n.getParentNode().getChildNodes();

                // Save the custom_search_handler.incl file
                XMLUtils.docToFile(doc, customSearchHandler);
            }

            if (childList == null) {
                final Node n = run(searchHandler.getChildNodes(), type);
                childList = n.getParentNode().getChildNodes();
            }

            for (int i = 0; i < childList.getLength(); i++) { // Get the str
                // node
                final Node n = childList.item(i);
                if (n.getNodeName().equals("str")) {
                    String name = ""; // Get it's attributes
                    final NamedNodeMap map = n.getAttributes();
                    for (int j = 0; j < map.getLength(); j++) {
                        if (map.item(j).getNodeName().equals("name")) {// Get
                            // the
                            // name
                            name = map.item(j).getNodeValue();
                        }
                    }
                    if (name.equals(type)) { // If it's pf or qf according
                        // to what the user selected
                        // Get the parameters
                        final String field = request.getParameter("field").toString();
                        final String value = request.getParameter("value").toString();
                        final String text = n.getTextContent(); // Get the
                        // value of
                        // the node,
                        // Search for the requested field, if it is there
                        // return the weight, if not return 0
                        final int index = text.indexOf(field + "^");
                        if (index != -1) { // If the field is already
                            // weighted
                            final int pas = field.length() + 1;
                            final String textCut = text.substring(index + pas);
                            if (value.equals("0")) { // If the user entered
                                // 0
                                if (textCut.indexOf(" ") == -1) {
                                    // field is
                                    // the last
                                    // one then
                                    // we just
                                    // cut the
                                    // end of
                                    // the text
                                    // content
                                    n.setTextContent((text.substring(0, index)).trim());
                                } else {
                                    // the field and the part after
                                    n.setTextContent((text.substring(0, index)
                                            + text.substring(index + pas + textCut.indexOf(" "))).trim());
                                }
                            } else { // If the user typed any other values
                                if (textCut.indexOf(" ") == -1) {
                                    n.setTextContent(text.substring(0, index + pas) + value);
                                } else {
                                    n.setTextContent(text.substring(0, index + pas) + value
                                            + text.substring(index + pas + textCut.indexOf(" ")));
                                }
                            }
                        } else { // If it's not weighted
                            if (!value.equals("0")) {
                                // append the field and
                                // it's value
                                n.setTextContent((n.getTextContent() + " " + field + "^" + value).trim());
                            }
                        }
                        break;
                    }
                }
            }
            // Apply the modifications
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            final DOMSource source = new DOMSource(searchHandler);
            final StreamResult result = new StreamResult(customSearchHandler);
            transformer.transform(source, result);

        } catch (final TransformerException e) {
            LOGGER.error(
                    "Error while modifying the solrconfig.xml, in FieldWeight doPost, pls make sure the file is valid. Error 69030",
                    e);
            final PrintWriter out = response.getWriter();
            out.append(
                    "Error while modifying the config file, please retry, if the problem persists contact your system administrator. Error Code : 69030");
            out.close();
            return;
        }

    } catch (final Exception e) {
        final PrintWriter out = response.getWriter();
        out.append(
                "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69511");
        out.close();
        LOGGER.error("Unindentified error in FieldWeight doPost. Error 69511", e);
    }
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Substitute the element selected by the xPath in the given node with the new value.
 * //from w  ww . ja  v a 2 s. c  o m
 * @param node
 *            The node.
 * @param xPath
 *            The xPath.
 * @param newValue
 *            The newValue.
 * @return The resulting node after the substitution.
 * @throws Exception
 *             If anything fails.
 */
public static Node substitute(final Node node, final String xPath, final String newValue) throws Exception {
    Node result = node;
    Node replace = selectSingleNode(result, xPath);
    assertNotNull("No node found for specified xpath [" + xPath + "]", replace);
    // if (replace.getNodeType() == Node.ELEMENT_NODE) {
    replace.setTextContent(newValue);
    // }
    // else if (replace.getNodeType() == Node.ATTRIBUTE_NODE) {
    // replace.setNodeValue(newValue);
    // }
    // else {
    // throw new Exception("Unsupported node type '"
    // + replace.getNodeType() + "' in EscidocTestBase.substitute.");
    // }
    return result;
}

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

/**
 * Add a tag of the form below, under node
 *                      <performer typeCode="PRF">
                <time value="20100702"/>
                <assignedEntity>/*from ww w  .j a v a  2 s.co m*/
                   <id root="2" extension="12345678"/>
                   <code codeSystem="2" code="Speciality" displayName="Speciality"/>
                   <assignedPerson>
                      <name>
                         <family>Jodar de Jodar</family>
                         <given>Paco</given>
                      </name>
                   </assignedPerson>
                   <representedOrganization>
                      <id root="2.16.840.1.113883.19.5"/>
                      <name>Farmacia de La Puerta de la Carne</name>
                      <addr>
                         <state>Sevilla</state>
                         <city>Sevilla</city>
                         <precinct>Sevilla</precinct>
                         <country>ES</country>
                         <postalCode>41003</postalCode>
                         <streetAddressLine>Calle Demetrio de los Rios, 3</streetAddressLine>
                      </addr>
                   </representedOrganization>
                </assignedEntity>
             </performer>
 * @param dom
 * @param node
 * @param doctor
 */
private void addPerformerTag(Document dom, Node node, SpiritUserClientDto doctor) {
    Node performer = dom.createElement("performer");
    addAttribute(dom, performer, "typeCode", "PRF");

    // time tag
    //String timeString = xmlEncodeDate(new Date());
    String timeString = dateMetaDataFormat.format(new Date());
    Node time = dom.createElement("time");
    addAttribute(dom, time, "value", timeString);
    performer.appendChild(time);

    // assignedEntity tag
    Node assignedEntity = dom.createElement("assignedEntity");
    Node id = dom.createElement("id");
    addAttribute(dom, id, "root", XML_DISPENSATION_PERFORMER_ID_ROOT);
    addAttribute(dom, id, "extension", xmlNotNullString(doctor.getUid().get(0)));
    assignedEntity.appendChild(id);
    // assignedPerson and name tags                                     
    Node assignedPerson = dom.createElement("assignedPerson");
    Node name = dom.createElement("name");
    Node family = dom.createElement("family");
    family.setTextContent(xmlNotNullString(doctor.getSurname().get(0)));
    name.appendChild(family);
    Node given = dom.createElement("given");
    if (Validator.isNotNull(xmlNotNullString(doctor.getGivenName().get(0))))
        given.setTextContent(xmlNotNullString(doctor.getGivenName().get(0)));
    else
        given.setTextContent(xmlNotNullString(doctor.getSurname().get(0)));
    name.appendChild(given);
    assignedPerson.appendChild(name);
    assignedEntity.appendChild(assignedPerson);

    //representedOrganization tag
    SpiritOrganisationClientDto org = doctor.getHomeOrganisation();
    Node representedOrganization = dom.createElement("representedOrganization");
    Node orgid = dom.createElement("id");
    addAttribute(dom, orgid, "root", XML_DISPENSATION_PERFORMER_ID_ROOT);
    addAttribute(dom, orgid, "extension", xmlNotNullString(org.getOrganisationDN()));
    representedOrganization.appendChild(orgid);
    Node orgName = dom.createElement("name");
    orgName.setTextContent(xmlNotNullString(org.getOrganisationName()));
    representedOrganization.appendChild(orgName);
    Node address = dom.createElement("addr");
    Node state = dom.createElement("state");
    state.setTextContent(xmlNotNullString(org.getState()));
    Node city = dom.createElement("city");
    city.setTextContent(xmlNotNullString(org.getLocality()));
    Node country = dom.createElement("country");
    country.setTextContent(xmlNotNullString(org.getLocality()));
    Node zip = dom.createElement("postalCode");
    zip.setTextContent(xmlNotNullString(org.getPostalCode()));
    Node street = dom.createElement("streetAddressLine");
    street.setTextContent(xmlNotNullString(org.getStreet()));
    address.appendChild(street);
    address.appendChild(city);
    address.appendChild(state);
    address.appendChild(zip);
    address.appendChild(country);
    representedOrganization.appendChild(address);
    assignedEntity.appendChild(representedOrganization);
    performer.appendChild(assignedEntity);

    node.appendChild(performer);

}

From source file:de.escidoc.core.test.aa.AaTestBase.java

/**
 * Inserts a unique label into the provided document by adding the current timestamp to the contained label.
 * // w ww  .  j a va  2s  .c  om
 * @param document
 *            The document.
 * @return The inserted login name.
 * @throws Exception
 *             If anything fails.
 */
protected String insertUniqueLabel(final Document document) throws Exception {

    assertXmlExists("No label found in template data. ", document, "/user-group/properties/label");
    final Node labelNode = selectSingleNode(document, "/user-group/properties/label");
    String label = labelNode.getTextContent().trim();
    label += System.currentTimeMillis();

    labelNode.setTextContent(label);

    return label;
}

From source file:de.escidoc.core.test.aa.AaTestBase.java

/**
 * Prepares the data for an user-account.
 * /*from   w w w. j a v  a  2 s.c  om*/
 * @return Returns the xml representation of an user-account. The data is created by using the template file
 *         escidoc_useraccount_for_create.xml
 * @throws Exception
 *             If anything fails.
 */
private String prepareUserAccountData() throws Exception {

    final Document document = EscidocAbstractTest.getTemplateAsDocument(TEMPLATE_USER_ACCOUNT_PATH,
            "escidoc_useraccount_for_create.xml");
    assertXmlExists("No login-name found in template data. ", document, XPATH_USER_ACCOUNT_LOGINNAME);
    final Node loginNameNode = selectSingleNode(document, XPATH_USER_ACCOUNT_LOGINNAME);
    String loginname = loginNameNode.getTextContent().trim();
    loginname += System.currentTimeMillis();
    loginNameNode.setTextContent(loginname);
    final String userAccountXml = toString(document, true);
    return userAccountXml;
}

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

/**
 * Add a tag of the form below under the given node:
 * //w  w  w .  j ava 2s .c  o 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.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.  j  ava  2s  . 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:de.escidoc.core.test.EscidocTestBase.java

/**
 * Makes the value of the provided node unique by adding a timestamp to it.
 * //from  ww  w . j  a  va  2  s. co m
 * @param node
 *            The node to find the "name" element in and make it unique.
 * @return Returns the unique value.
 */
public String setUniqueName(final Node node) {

    final String uniqueName = getUniqueName(node.getTextContent().trim());
    node.setTextContent(uniqueName);
    return uniqueName;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Substitute the element selected by the xPath in the given node with the new value.
 * //  w  w  w  . j  a v a 2  s.  c om
 * @param node
 *            The node.
 * @param xPath
 *            The xPath.
 * @param newValue
 *            The newValue.
 * @return The resulting node after the substitution.
 * @throws Exception
 *             If anything fails.
 */
public Node substituteId(final Node node, final String xPath, final String newValue) throws Exception {
    Node result = node;
    Node replace = null;
    String path = "";
    replace = selectSingleNode(result, xPath + "/@href");
    path = replace.getTextContent().substring(0, replace.getTextContent().lastIndexOf("/") + 1);

    assertNotNull("No node found for specified xpath [" + xPath + "]", replace);
    // if (replace.getNodeType() == Node.ELEMENT_NODE) {
    replace.setTextContent(path + newValue);
    // }
    // else if (replace.getNodeType() == Node.ATTRIBUTE_NODE) {
    // replace.setNodeValue(newValue);
    // }
    // else {
    // throw new Exception("Unsupported node type '"
    // + replace.getNodeType() + "' in EscidocTestBase.substitute.");
    // }
    return result;
}

From source file:com.mirth.connect.model.util.ImportConverter.java

private static void convertEmailConnectorFor2_2(Document document, Element connectorRoot) throws Exception {
    // convert Email Sender to the new SMTP Sender
    Node transportNode = getConnectorTransportNode(connectorRoot);
    String transportNameText = transportNode.getTextContent();
    String attribute = "";
    String value = "";
    Element propertiesElement = getPropertiesElement(connectorRoot);

    // Default Properties
    Map<String, String> propertyDefaults = new HashMap<String, String>();

    // Properties to be added if missing, or reset if present
    Map<String, String> propertyChanges = new HashMap<String, String>();

    // logic to deal with SMTP Sender settings
    if (transportNameText.equals("Email Sender")) {
        // get properties
        NodeList properties = connectorRoot.getElementsByTagName("property");

        // set defaults
        ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();

        propertyDefaults.put("DataType", "SMTP Sender");
        propertyDefaults.put("smtpHost", "");
        propertyDefaults.put("smtpPort", "25");
        propertyDefaults.put("timeout", "5000");
        propertyDefaults.put("encryption", "none");
        propertyDefaults.put("authentication", "0");
        propertyDefaults.put("username", "");
        propertyDefaults.put("password", "");
        propertyDefaults.put("to", "");
        propertyDefaults.put("from", "");
        propertyDefaults.put("headers", serializer.serialize(new LinkedHashMap<String, String>()));
        propertyDefaults.put("subject", "");
        propertyDefaults.put("charsetEncoding", CharsetUtils.DEFAULT_ENCODING);
        propertyDefaults.put("html", "0");
        propertyDefaults.put("body", "");
        propertyDefaults.put("attachments", "<list/>");

        List<String> attachmentNames = null;
        List<String> attachmentContents = null;
        List<String> attachmentTypes = null;
        for (int i = 0; i < properties.getLength(); i++) {
            // get the current attribute and current value
            attribute = properties.item(i).getAttributes().item(0).getTextContent();
            value = properties.item(i).getTextContent();

            // Now rename attributes
            if (attribute.equals("hostname")) {
                propertyChanges.put("smtpHost", value);
            } else if (attribute.equals("emailSecure")) {
                propertyChanges.put("encryption", value);
            } else if (attribute.equals("useAuthentication")) {
                propertyChanges.put("authentication", value);
            } else if (attribute.equals("toAddresses")) {
                propertyChanges.put("to", value);
            } else if (attribute.equals("fromAddress")) {
                propertyChanges.put("from", value);
            } else if (attribute.equals("contentType")) {
                if (value.equalsIgnoreCase("text/plain")) {
                    propertyChanges.put("html", "0");
                } else {
                    propertyChanges.put("html", "1");
                }/* w w w.j a va 2  s. co  m*/
            } else if (attribute.equals("attachmentNames")) {
                attachmentNames = serializer.deserializeList(value, String.class);
            } else if (attribute.equals("attachmentContents")) {
                attachmentContents = serializer.deserializeList(value, String.class);
            } else if (attribute.equals("attachmentTypes")) {
                attachmentTypes = serializer.deserializeList(value, String.class);
            } else if (attribute.equals("useServerSettings")) {
                // Disable the channel or connector if useServerSettings was set
                if (value.equalsIgnoreCase("1")) {
                    document.getElementsByTagName("enabled").item(0).setTextContent("false");
                }
            }
        }

        DonkeyElement attachmentList = new DonkeyElement("<list/>");

        if (attachmentNames != null) {
            for (int i = 0; i < attachmentNames.size(); i++) {
                DonkeyElement attachment = attachmentList
                        .addChildElement("com.mirth.connect.connectors.smtp.Attachment");
                attachment.addChildElement("name", attachmentNames.get(i));
                attachment.addChildElement("content", attachmentContents.get(i));
                attachment.addChildElement("mimeType", attachmentTypes.get(i));
            }
        }

        propertyChanges.put("attachments", attachmentList.toXml());

        propertyChanges.put("DataType", "SMTP Sender");

        // set new name of transport node
        transportNode.setTextContent("SMTP Sender");

        updateProperties(document, propertiesElement, propertyDefaults, propertyChanges);
    }
}