Example usage for org.w3c.dom Node appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:com.fiorano.openesb.application.aps.ServiceInstance.java

/**
 *  Returns the XML string equivalent of this object.
 *
 * @param document the input Document object
 * @return element node/*from   www . j  a v a 2  s.  c o  m*/
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 */
Node toJXMLString(Document document) throws FioranoException {
    Node root0 = (Node) document.createElement("ServiceInstance");

    ((Element) root0).setAttribute("isManualLaunch", "" + m_isManualLaunch);
    ((Element) root0).setAttribute("isStateful", "" + m_isStateful);
    ((Element) root0).setAttribute("isDelayedLaunch", "" + m_isDelayedLaunch);
    ((Element) root0).setAttribute("delayedPort", "" + m_delayedPortName);
    ((Element) root0).setAttribute("maxRetries", "" + m_maxRetries);
    ((Element) root0).setAttribute("isTransacted", "" + m_isTransacted);
    ((Element) root0).setAttribute("isErrorHandlingEnabled", "" + m_isErrorHandlingEnabled);
    ((Element) root0).setAttribute("isInMemoryLaunch", "" + m_isInMemoryLaunch);
    ((Element) root0).setAttribute("isEndOfWorkflow", "" + m_isEndOfWorkflow);
    ((Element) root0).setAttribute("preferLaunchOnHigherLevelNode", "" + m_bPreferLaunchOnHigherLevelNode);
    //((Element) root0).setAttribute("durableSubscription", "" + m_bIsDurableSubscription);
    //((Element) root0).setAttribute("durableConnection", "" + m_bIsDurableConnection);
    ((Element) root0).setAttribute("killPrimaryOnSecondaryLaunch", "" + m_bKillPrimaryOnSecondaryLaunch);
    ((Element) root0).setAttribute("isDebugMode", "" + m_bIsDebugMode);
    ((Element) root0).setAttribute("debugPort", "" + m_iDebugPort);
    ((Element) root0).setAttribute("isTransportLPC", "" + m_isTransportLPC);
    ((Element) root0).setAttribute("profile", "" + m_profile);

    Node node = XMLDmiUtil.getNodeObject("ServiceInstanceName", m_servInstName, document);

    if (node != null)
        root0.appendChild(node);

    Node node1 = XMLDmiUtil.getNodeObject("ServiceGUID", m_servGUID, document);

    if (node1 != null)
        root0.appendChild(node1);

    Node nodeN = XMLDmiUtil.getNodeObject("BufferSizePerPort", m_dBufferSizePerPort + "", document);

    if (nodeN != null)
        root0.appendChild(nodeN);

    Element child = null;

    if (m_version != null) {
        child = document.createElement("Version");
        ((Element) child).setAttribute("isLocked", "" + m_isVersionLocked);

        Node pcData = (Node) document.createTextNode(m_version);

        child.appendChild(pcData);
        root0.appendChild(child);
    }
    if (m_nodes != null && m_nodes.size() > 0) {
        Enumeration nodeNameEnum = m_nodes.keys();
        Enumeration nodeLevelEnum = m_nodes.elements();

        while (nodeNameEnum.hasMoreElements()) {
            String nodeName = (String) nodeNameEnum.nextElement();
            String nodeLevel = (String) nodeLevelEnum.nextElement();

            child = document.createElement("Node");
            ((Element) child).setAttribute("level", nodeLevel);

            Node pcData = (Node) document.createTextNode(nodeName);

            child.appendChild(pcData);
            root0.appendChild(child);
        }
    }
    if (m_eventHandler > 0) {
        child = document.createElement("EventHandler");
        ((Element) child).setAttribute("deliveryMode", "" + m_eventDeliveryMode);
        ((Element) child).setAttribute("expiryTime", "" + m_eventExpiryTime);

        Node pcData = (Node) document.createTextNode("" + m_eventHandler);

        child.appendChild(pcData);
        root0.appendChild(child);
    }
    if (m_runtimeDependencies != null && m_runtimeDependencies.size() > 0) {
        Enumeration _enum = m_runtimeDependencies.elements();

        while (_enum.hasMoreElements()) {
            RuntimeDependency runtimeDependency = (RuntimeDependency) _enum.nextElement();
            Node serviceDepNode = runtimeDependency.toJXMLString(document);

            root0.appendChild(serviceDepNode);
        }
    }
    if (m_runtimeArgs != null) {
        Node argsNode = m_runtimeArgs.toJXMLString(document);

        root0.appendChild(argsNode);
    }
    if (m_portInstDescriptor != null) {
        Node argsNode = m_portInstDescriptor.toJXMLString(document);

        root0.appendChild(argsNode);
    }

    if (!StringUtils.isEmpty(m_longDescription)) {
        Node node2 = XMLDmiUtil.getNodeObject("LongDescription", m_longDescription, document);

        if (node2 != null)
            root0.appendChild(node2);
    }
    if (!StringUtils.isEmpty(m_shortDescription)) {
        Node node3 = XMLDmiUtil.getNodeObject("ShortDescription", m_shortDescription, document);

        if (node3 != null)
            root0.appendChild(node3);
    }
    // Log Manager
    if (m_logManager != null) {
        Node node12 = (Node) document.createElement("LogManager");

        if (node12 != null) {
            Node nameNode = XMLDmiUtil.getNodeObject("Name", m_logManager, document);

            node12.appendChild(nameNode);

            if (m_logParams != null && m_logParams.size() > 0) {
                Enumeration enums = m_logParams.elements();

                while (enums.hasMoreElements()) {
                    Param param = (Param) enums.nextElement();
                    if (!StringUtils.isEmpty(param.getParamName())
                            && !StringUtils.isEmpty(param.getParamValue()))
                        node12.appendChild(param.toJXMLString(document));
                }
            }
            root0.appendChild(node12);
        }
    }

    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue()))
                root0.appendChild(param.toJXMLString(document));
        }
    }
    if (m_statusTracking != null) {
        Node pcData = m_statusTracking.toJXMLString(document);

        root0.appendChild(pcData);
    }

    if (m_vecEndStates != null) {
        for (int i = 0; i < m_vecEndStates.size(); i++) {
            EndState endState = (EndState) m_vecEndStates.get(i);
            Node pcData = endState.toJXMLString(document);

            root0.appendChild(pcData);
        }
    }
    if (m_monitor != null) {
        Node pcData = m_monitor.toJXMLString(document);

        root0.appendChild(pcData);
    }
    if (m_logModules != null) {
        Node pcData = m_logModules.toJXMLString(document);

        root0.appendChild(pcData);
    }
    return root0;
}

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   w  w  w  .  j a  v a2s.c  o  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: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  ww w .j  a  v  a 2 s  . co 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:com.ext.portlet.epsos.EpsosHelperService.java

private Node createEpsosQuantityNode(Document dom, String quantityString) {
    Node quantity = dom.createElement("epsos:capacityQuantity");
    if (quantityString != null && quantityString.length() > 0) {
        int slash = quantityString.lastIndexOf('/');
        String numeratorString = quantityString;
        String denominatorString = null;
        if (slash != -1) {
            numeratorString = quantityString.substring(0, slash).trim();
            denominatorString = quantityString.substring(slash + 1).trim();
        }//from   w  w  w  . ja  v a  2 s .  co  m

        Node numerator = createEpsosValueUnitNode(dom, true, numeratorString);
        Node denominator = createEpsosValueUnitNode(dom, false, denominatorString);

        quantity.appendChild(numerator);
        quantity.appendChild(denominator);
    }

    return quantity;
}

From source file:ca.digitalface.jasperoo.JasperooOperationsImpl.java

/**
 * Modifies the "List" report template to add all of the fields in the 
 * entity being listed./*  w ww .j  a v a 2  s  . c  om*/
 * 
 * @param javaType The JavaType of the entity being listed.
 * @param entityName The name of the entity being listed.
 */
private void modifyListTagx(String reportFormat) {
    String docPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/tags/form/list.tagx");

    MutableFile mutableDocXml = null;
    Document targetDoc;
    try {
        if (fileManager.exists(docPath)) {
            mutableDocXml = fileManager.updateFile(docPath);
            targetDoc = XmlUtils.getDocumentBuilder().parse(mutableDocXml.getInputStream());
        } else {
            throw new IllegalStateException("Could not acquire " + docPath);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Node target = XmlUtils.findFirstElementByName("jsp:doBody", targetDoc.getDocumentElement()).getParentNode();

    /*
     *   <c:catch>
     *       <c:if test="${not empty object.reportable}">
     *           <span>
     *               <spring:url value="/reports/${fn:toLowerCase(typeName)}List/${itemId}/pdf" var="report_url" />
     *               <spring:url value="/resources/images/report.png" var="report_image_url" />
     *               <spring:message arguments="${typeName}" code="entity_list_report" var="report_label" htmlEscape="false" />
     *               <a href="${fn:escapeXml(report_url)}" alt="${fn:escapeXml(report_label)}" title="${fn:escapeXml(report_label)}">
     *                 <img alt="${fn:escapeXml(report_label)}" class="image" src="${fn:escapeXml(report_image_url)}" title="${fn:escapeXml(report_label)}" />
     *               </a>
     *           </span>
     *       </c:if>
     *   </c:catch>
     */

    Element catchNode = new XmlElementBuilder("c:catch", targetDoc)
            .addChild(
                    new XmlElementBuilder("c:if", targetDoc)
                            .addAttribute("test", "${not empty items[0].reportable}")
                            .addChild(new XmlElementBuilder("span", targetDoc)
                                    .addAttribute("style", "text-align:right;").build())
                            .addChild(
                                    new XmlElementBuilder("spring:url", targetDoc)
                                            .addAttribute("value",
                                                    "/reports/${fn:toLowerCase(label)}List/" + reportFormat)
                                            .addAttribute("var", "report_url").build())
                            .addChild(new XmlElementBuilder("spring:url", targetDoc)
                                    .addAttribute("value", "/resources/images/report-" + reportFormat + ".png")
                                    .addAttribute("var", "report_image_url").build())
                            .addChild(new XmlElementBuilder("spring:message", targetDoc)
                                    .addAttribute("arguments", "${label}")
                                    .addAttribute("code", "entity_list_report")
                                    .addAttribute("var", "report_label").addAttribute("htmlEscape", "false")
                                    .build())
                            .addChild(new XmlElementBuilder("a", targetDoc)
                                    .addAttribute("href", "${fn:escapeXml(report_url)}")
                                    .addAttribute("alt", "${fn:escapeXml(report_label)}")
                                    .addAttribute("title", "${fn:escapeXml(report_label)}")
                                    .addChild(new XmlElementBuilder("img", targetDoc)
                                            .addAttribute("class", "image")
                                            .addAttribute("alt", "${fn:escapeXml(report_label)}")
                                            .addAttribute("title", "${fn:escapeXml(report_label)}")
                                            .addAttribute("src", "${fn:escapeXml(report_image_url)}").build())
                                    .build())
                            .build())
            .build();

    target.appendChild(catchNode);

    XmlUtils.writeXml(mutableDocXml.getOutputStream(), targetDoc);

}

From source file:ca.digitalface.jasperoo.JasperooOperationsImpl.java

/**
 * Modifies the "List" report template to add all of the fields in the 
 * entity being listed.//  ww  w.j  a  v a 2s  . co  m
 * 
 * @param javaType The JavaType of the entity being listed.
 * @param entityName The name of the entity being listed.
 */
private void modifyDetailReportTemplate(JavaType javaType, String entityName) {
    String reportPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP,
            "WEB-INF/reports/" + entityName.toLowerCase() + "ReportDetail.jrxml");

    MutableFile mutableReportXml = null;
    Document reportDoc;
    try {
        if (fileManager.exists(reportPath)) {
            mutableReportXml = fileManager.updateFile(reportPath);
            reportDoc = XmlUtils.getDocumentBuilder().parse(mutableReportXml.getInputStream());
        } else {
            throw new IllegalStateException("Could not acquire " + reportPath);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element detailNode = (Element) reportDoc.getDocumentElement().getElementsByTagName("detail").item(0);
    Node detailBand = XmlUtils.findFirstElementByName("band", detailNode);

    // The id field is 20 px high, so we start there and add the field width on each pass.
    int offsetY = 20;

    // determine the total number of fields
    int fieldCount = getJavaTypeDetails(javaType).getDeclaredFields().size();
    MutableClassOrInterfaceTypeDetails details = getJavaTypeDetails(javaType);
    List<JavaType> extendsTypes = details.getExtendsTypes();

    // We need to know how many fields can be accessed from the hierarchy of this class.
    // Unfortunately, the list that comes back from getDeclaredFields is an "unmodifiableList", 
    // so we can't just concatenate all lists and iterate through a super-list.
    boolean bExtender = extendsTypes != null && extendsTypes.size() > 0;
    while (bExtender) {
        JavaType tempType = details.getExtendsTypes().get(0);
        List<? extends FieldMetadata> fields = getJavaTypeDetails(tempType).getDeclaredFields();
        fieldCount = fieldCount + fields.size();

        details = getJavaTypeDetails(tempType);
        extendsTypes = details.getExtendsTypes();
        bExtender = extendsTypes != null && extendsTypes.size() > 0;
    }

    details = getJavaTypeDetails(javaType);
    List<? extends FieldMetadata> fields = getJavaTypeDetails(javaType).getDeclaredFields();
    bExtender = true;
    while (bExtender) {
        int fieldHeight = (641 - 20) / fieldCount;
        if (fieldHeight > 20) {
            fieldHeight = 20;
        }

        for (FieldMetadata fieldMetadata : fields) {
            JavaType fieldType = fieldMetadata.getFieldType();
            boolean bValidType = Arrays.asList(jasperFacetValidTypes)
                    .contains(fieldType.getFullyQualifiedTypeName());

            JavaSymbolName fieldName = fieldMetadata.getFieldName();
            insertJasperooMessages("jasperoo." + getPlural(entityName) + "." + fieldName.getSymbolName(),
                    fieldName.getReadableSymbolName());

            Element pageHeaderNode = XmlUtils.findFirstElementByName("pageHeader",
                    reportDoc.getDocumentElement());

            Element fieldNode = new XmlElementBuilder("field", reportDoc)
                    .addAttribute("name", fieldName.getSymbolName())
                    .addAttribute("class", fieldType.getFullyQualifiedTypeName()).build();

            reportDoc.getDocumentElement().insertBefore(fieldNode, pageHeaderNode);

            if (!bValidType) {
                Element firstFieldNode = XmlUtils.findFirstElementByName("field",
                        reportDoc.getDocumentElement());

                Element importNode = new XmlElementBuilder("import", reportDoc)
                        .addAttribute("value", fieldType.getFullyQualifiedTypeName()).build();

                reportDoc.getDocumentElement().insertBefore(importNode, firstFieldNode);
            }

            Element headerTextfield = new XmlElementBuilder("textField", reportDoc)
                    .addChild(new XmlElementBuilder("reportElement", reportDoc).addAttribute("x", "0")
                            .addAttribute("y", String.valueOf(offsetY)).addAttribute("width", "125")
                            .addAttribute("height", String.valueOf(fieldHeight)).build())
                    .addChild(new XmlElementBuilder("textElement", reportDoc).build())
                    .addChild(
                            new XmlElementBuilder("textFieldExpression", reportDoc)
                                    .addAttribute("class", "java.lang.String").setText("$R{jasperoo."
                                            + getPlural(entityName) + "." + fieldName.getSymbolName() + "}")
                                    .build())
                    .build();

            detailBand.appendChild(headerTextfield);

            Element detailTextfield = null;
            if (bValidType) {
                detailTextfield = new XmlElementBuilder("textField", reportDoc)
                        .addChild(new XmlElementBuilder("reportElement", reportDoc).addAttribute("x", "126")
                                .addAttribute("y", String.valueOf(offsetY)).addAttribute("width", "446")
                                .addAttribute("height", String.valueOf(fieldHeight)).build())
                        .addChild(new XmlElementBuilder("textElement", reportDoc).build())
                        .addChild(new XmlElementBuilder("textFieldExpression", reportDoc)
                                .addAttribute("class", fieldType.getFullyQualifiedTypeName())
                                .setText("$F{" + fieldName.getSymbolName() + "}").build())
                        .build();
            } else {
                detailTextfield = new XmlElementBuilder("textField", reportDoc)
                        .addChild(new XmlElementBuilder("reportElement", reportDoc).addAttribute("x", "126")
                                .addAttribute("y", String.valueOf(offsetY)).addAttribute("width", "446")
                                .addAttribute("height", String.valueOf(fieldHeight)).build())
                        .addChild(new XmlElementBuilder("textElement", reportDoc).build())
                        .addChild(new XmlElementBuilder("textFieldExpression", reportDoc)
                                .addAttribute("class", "java.lang.String")
                                .setText("$F{" + fieldName.getSymbolName() + "}.toString()").build())
                        .build();
            }

            detailBand.appendChild(detailTextfield);

            offsetY += fieldHeight;
        }

        // Do we keep going?
        extendsTypes = details.getExtendsTypes();
        bExtender = extendsTypes != null && extendsTypes.size() > 0;
        if (bExtender) {
            JavaType tempType = details.getExtendsTypes().get(0);
            details = getJavaTypeDetails(tempType);
            fields = details.getDeclaredFields();
        }
    }

    XmlUtils.writeXml(mutableReportXml.getOutputStream(), reportDoc);

}

From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse,
        Map<String, Serializable> arguments) throws CatalogTransformerException {

    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");

    long grandTotal = -1;

    try {//from w ww .  ja v a2  s  . co m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.newDocument();

        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));

        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();

        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            String thisMetacard = metacard.getMetadata();
            if (metacard != null && thisMetacard != null) {
                Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                if (metacard.getId() != null) {
                    metacardElement
                            .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                }
                if (metacard.getMetacardType().toString() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type",
                            metacard.getMetacardType().getName()));
                }
                if (metacard.getTitle() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                }
                if (result.getRelevanceScore() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score",
                            result.getRelevanceScore().toString()));
                }
                if (result.getDistanceInMeters() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance",
                            result.getDistanceInMeters().toString()));
                }
                if (metacard.getSourceId() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                }
                if (metacard.getContentTypeName() != null) {
                    String contentType = metacard.getContentTypeName();
                    Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type",
                            contentType);
                    // TODO revisit what to put in the qualifier
                    typeElement.setAttribute("qualifier", "content-type");
                    metacardElement.appendChild(typeElement);
                }
                if (metacard.getResourceURI() != null) {
                    try {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product",
                                metacard.getResourceURI().toString()));
                    } catch (DOMException e) {
                        LOGGER.warn(" Unable to create resource uri element", e);
                    }
                }
                if (metacard.getThumbnail() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail",
                            Base64.encodeBase64String(metacard.getThumbnail())));
                    try {
                        String mimeType = URLConnection
                                .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                        metacardElement
                                .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        metacardElement.appendChild(
                                createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                    }
                }
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                if (metacard.getCreatedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created",
                            fmt.print(metacard.getCreatedDate().getTime())));
                }
                // looking at the date last modified
                if (metacard.getModifiedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated",
                            fmt.print(metacard.getModifiedDate().getTime())));
                }
                if (metacard.getEffectiveDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective",
                            fmt.print(metacard.getEffectiveDate().getTime())));
                }
                if (metacard.getLocation() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                }
                Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                metacardElement.appendChild(documentElement);
                resultsElement.appendChild(metacardElement);

                Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(),
                        true);
                documentElement.appendChild(importedNode);
            } else {
                LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                continue;
            }
        }

        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }

        LOGGER.debug("Starting responsequeue xslt transform.");

        Transformer transformer;

        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }

        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);

        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                    tce.getCause());
        }

        if (mergedMap != null && !mergedMap.isEmpty()) {
            for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}");
                }
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause());
            throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(),
                    te.getCause());
        } finally {
            // transformer.reset();
            // don't need to do that unless we are putting it back into a
            // pool -- which we should do, but that can wait until later.
        }

        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause());
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}

From source file:ca.digitalface.jasperoo.JasperooOperationsImpl.java

/**
 * Modifies the "List" report template to add all of the fields in the 
 * entity being listed.//from   w  w w . j a v a 2  s.  c om
 * 
 * @param javaType The JavaType of the entity being listed.
 * @param entityName The name of the entity being listed.
 */
private void modifyListReportTemplate(JavaType javaType, String entityName) {
    String reportPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP,
            "WEB-INF/reports/" + entityName.toLowerCase() + "ReportList.jrxml");

    MutableFile mutableReportXml = null;
    Document reportDoc;
    try {
        if (fileManager.exists(reportPath)) {
            mutableReportXml = fileManager.updateFile(reportPath);
            reportDoc = XmlUtils.getDocumentBuilder().parse(mutableReportXml.getInputStream());
        } else {
            throw new IllegalStateException("Could not acquire " + reportPath);
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    Element columnHeaderNode = (Element) reportDoc.getDocumentElement().getElementsByTagName("columnHeader")
            .item(0);
    Element columnHeaderBand = XmlUtils.findFirstElementByName("band", columnHeaderNode);
    Element detailNode = (Element) reportDoc.getDocumentElement().getElementsByTagName("detail").item(0);
    Node detailBand = XmlUtils.findFirstElementByName("band", detailNode);

    // The id field is 30 px wide, so we start there and add the field width on each pass.
    int offsetX = 30;

    // determine the total number of fields
    int fieldCount = getJavaTypeDetails(javaType).getDeclaredFields().size();
    MutableClassOrInterfaceTypeDetails details = getJavaTypeDetails(javaType);
    List<JavaType> extendsTypes = details.getExtendsTypes();

    // We need to know how many fields can be accessed from the hierarchy of this class.
    // Unfortunately, the list that comes back from getDeclaredFields is an "unmodifiableList", 
    // so we can't just concatenate all lists and iterate through a super-list.
    boolean bExtender = extendsTypes != null && extendsTypes.size() > 0;
    while (bExtender) {
        JavaType tempType = details.getExtendsTypes().get(0);
        List<? extends FieldMetadata> fields = getJavaTypeDetails(tempType).getDeclaredFields();
        fieldCount = fieldCount + fields.size();

        details = getJavaTypeDetails(tempType);
        extendsTypes = details.getExtendsTypes();
        bExtender = extendsTypes != null && extendsTypes.size() > 0;
    }

    details = getJavaTypeDetails(javaType);
    List<? extends FieldMetadata> fields = getJavaTypeDetails(javaType).getDeclaredFields();
    bExtender = true;
    while (bExtender) {
        int fieldWidth = (752 - 30) / fieldCount;

        for (FieldMetadata fieldMetadata : fields) {
            JavaType fieldType = fieldMetadata.getFieldType();
            boolean bValidType = Arrays.asList(jasperFacetValidTypes)
                    .contains(fieldType.getFullyQualifiedTypeName());

            JavaSymbolName fieldName = fieldMetadata.getFieldName();
            insertJasperooMessages("jasperoo." + getPlural(entityName) + "." + fieldName.getSymbolName(),
                    fieldName.getReadableSymbolName());

            Element pageHeaderNode = XmlUtils.findFirstElementByName("pageHeader",
                    reportDoc.getDocumentElement());

            Element fieldNode = new XmlElementBuilder("field", reportDoc)
                    .addAttribute("name", fieldName.getSymbolName())
                    .addAttribute("class", fieldType.getFullyQualifiedTypeName()).build();

            reportDoc.getDocumentElement().insertBefore(fieldNode, pageHeaderNode);

            if (!bValidType) {
                Element firstFieldNode = XmlUtils.findFirstElementByName("field",
                        reportDoc.getDocumentElement());

                Element importNode = new XmlElementBuilder("import", reportDoc)
                        .addAttribute("value", fieldType.getFullyQualifiedTypeName()).build();

                reportDoc.getDocumentElement().insertBefore(importNode, firstFieldNode);
            }

            Element headerTextfield = new XmlElementBuilder("textField", reportDoc)
                    .addChild(new XmlElementBuilder("reportElement", reportDoc)
                            .addAttribute("x", String.valueOf(offsetX)).addAttribute("y", "0")
                            .addAttribute("width", String.valueOf(fieldWidth)).addAttribute("height", "20")
                            .build())
                    .addChild(new XmlElementBuilder("textElement", reportDoc).build())
                    .addChild(
                            new XmlElementBuilder("textFieldExpression", reportDoc)
                                    .addAttribute("class", "java.lang.String").setText("$R{jasperoo."
                                            + getPlural(entityName) + "." + fieldName.getSymbolName() + "}")
                                    .build())
                    .build();

            columnHeaderBand.appendChild(headerTextfield);

            Element detailTextfield = null;
            if (bValidType) {
                detailTextfield = new XmlElementBuilder("textField", reportDoc)
                        .addChild(new XmlElementBuilder("reportElement", reportDoc)
                                .addAttribute("x", String.valueOf(offsetX)).addAttribute("y", "0")
                                .addAttribute("width", String.valueOf(fieldWidth)).addAttribute("height", "20")
                                .build())
                        .addChild(new XmlElementBuilder("textElement", reportDoc).build())
                        .addChild(new XmlElementBuilder("textFieldExpression", reportDoc)
                                .addAttribute("class", fieldType.getFullyQualifiedTypeName())
                                .setText("$F{" + fieldName.getSymbolName() + "}").build())
                        .build();
            } else {
                detailTextfield = new XmlElementBuilder("textField", reportDoc)
                        .addChild(new XmlElementBuilder("reportElement", reportDoc)
                                .addAttribute("x", String.valueOf(offsetX)).addAttribute("y", "0")
                                .addAttribute("width", String.valueOf(fieldWidth)).addAttribute("height", "20")
                                .build())
                        .addChild(new XmlElementBuilder("textElement", reportDoc).build())
                        .addChild(new XmlElementBuilder("textFieldExpression", reportDoc)
                                .addAttribute("class", "java.lang.String")
                                .setText("$F{" + fieldName.getSymbolName() + "}.toString()").build())
                        .build();
            }

            detailBand.appendChild(detailTextfield);

            offsetX += fieldWidth;
        }

        // Do we keep going?
        extendsTypes = details.getExtendsTypes();
        bExtender = extendsTypes != null && extendsTypes.size() > 0;
        if (bExtender) {
            JavaType tempType = details.getExtendsTypes().get(0);
            details = getJavaTypeDetails(tempType);
            fields = details.getDeclaredFields();
        }
    }

    XmlUtils.writeXml(mutableReportXml.getOutputStream(), reportDoc);

}

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

/**
 * Add a tag of the form below under the given node:
 * /*  www .  ja va2s  . 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.portfolio.data.provider.MysqlAdminProvider.java

@Override
public String getTypeData(int userId, Integer type) {
    String sql = "";
    PreparedStatement st;//from   ww w.ja va 2 s .co  m

    HashMap<Integer, Node> resolve = new HashMap<Integer, Node>();
    /// Node -> parent
    ArrayList<Object[]> entries = new ArrayList<Object[]>();

    ResultSet res = null;
    try {
        sql = "SELECT node_id, asm_type, xsi_type, parent_node, node_data, instance_rule "
                + "FROM definition_type " + "WHERE def_id=?";
        st = connection.prepareStatement(sql);
        st.setInt(1, type);
        res = st.executeQuery();

        /// Time to create data
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;

        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();

        Element root = document.createElement("type");
        root.setAttribute("typeid", type.toString());
        document.appendChild(root);

        while (res.next()) {
            Integer id = res.getInt("node_id");
            String asmtype = res.getString("asm_type");
            String xsitype = res.getString("xsi_type");
            Integer parent = res.getInt("parent_node");
            if (res.wasNull())
                parent = null;
            String data = res.getString("node_data");
            Integer instance = res.getInt("instance_rule");

            Element nodeData = null;
            if (data != null) // Une ressource
            {
                data = "<asmResource>" + data + "</asmResource>";
                Document frag = documentBuilder.parse(new ByteArrayInputStream(data.getBytes("UTF-8")));
                nodeData = frag.getDocumentElement();
                nodeData.setAttribute("id", id.toString());
                nodeData.setAttribute("instance", instance.toString());
                document.adoptNode(nodeData);
                nodeData.setAttribute("xsi_type", xsitype);
            } else // Un bout de structure
            {
                nodeData = document.createElement(asmtype);
            }

            /// Info pour reconstruire l'arbre
            resolve.put(id, nodeData);
            Object[] obj = { nodeData, parent };
            entries.add(obj);
        }
        res.close();
        st.close();

        /// Reconstruction
        Iterator<Object[]> iter = entries.iterator();
        while (iter.hasNext()) {
            Object obj[] = iter.next();
            Node node = (Node) obj[0];
            Integer parent = (Integer) obj[1];
            if (parent != null) {
                Node parentNode = resolve.get(parent);
                parentNode.appendChild(node);
            } else
                root.appendChild(node);
        }

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));
        return stw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}