Example usage for javax.xml.xpath XPathExpression evaluate

List of usage examples for javax.xml.xpath XPathExpression evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpression evaluate.

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

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

public byte[] extractPdfPartOfPatientSummaryDocument(byte[] bytes) {
    byte[] result = bytes;

    try {// w  w w .  j ava  2 s.co m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(new ByteArrayInputStream(bytes));

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression pdfTag = xpath.compile("//component/nonXMLBody/text[@mediaType='application/pdf']");
        Node pdfNode = (Node) pdfTag.evaluate(dom, XPathConstants.NODE);
        if (pdfNode != null) {
            String base64EncodedPdfString = pdfNode.getTextContent().trim();
            result = decode.decode(base64EncodedPdfString.getBytes());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

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

/**
 * Add a tag of the form below under the given node:
 * //from w ww  . j  a v  a 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  ww  .  j  ava  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.portfolio.rest.RestServicePortfolio.java

@Path("/nodes/node/{node-id}/rights")
@POST//  w  ww . jav  a2  s . c o  m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes(MediaType.APPLICATION_XML)
public String postNodeRights(String xmlNode, @CookieParam("user") String user,
        @CookieParam("credential") String token, @QueryParam("group") int groupId,
        @PathParam("node-id") String nodeUuid, @Context ServletConfig sc,
        @Context HttpServletRequest httpServletRequest, @HeaderParam("Accept") String accept,
        @QueryParam("user") Integer userId) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(new ByteArrayInputStream(xmlNode.getBytes("UTF-8")));

        XPath xPath = XPathFactory.newInstance().newXPath();
        String xpathRole = "//role";
        XPathExpression findRole = xPath.compile(xpathRole);
        NodeList roles = (NodeList) findRole.evaluate(doc, XPathConstants.NODESET);

        /// For all roles we have to change
        for (int i = 0; i < roles.getLength(); ++i) {
            Node rolenode = roles.item(i);
            String rolename = rolenode.getAttributes().getNamedItem("name").getNodeValue();
            Node right = rolenode.getFirstChild();

            //
            if ("user".equals(rolename)) {
                /// username as role
            }

            if ("#text".equals(right.getNodeName()))
                right = right.getNextSibling();

            if ("right".equals(right.getNodeName())) // Changing node rights
            {
                NamedNodeMap rights = right.getAttributes();

                NodeRight noderight = new NodeRight(null, null, null, null, null, null);

                String val = rights.getNamedItem("RD").getNodeValue();
                if (val != null)
                    noderight.read = "Y".equals(val) ? true : false;
                val = rights.getNamedItem("WR").getNodeValue();
                if (val != null)
                    noderight.write = "Y".equals(val) ? true : false;
                val = rights.getNamedItem("DL").getNodeValue();
                if (val != null)
                    noderight.delete = "Y".equals(val) ? true : false;
                val = rights.getNamedItem("SB").getNodeValue();
                if (val != null)
                    noderight.submit = "Y".equals(val) ? true : false;

                // change right
                dataProvider.postRights(ui.userId, nodeUuid, rolename, noderight);
            } else if ("action".equals(right.getNodeName())) // Using an action on node
            {
                // reset right
                dataProvider.postMacroOnNode(ui.userId, nodeUuid, "reset");
            }
        }

        //         returnValue = dataProvider.postRRGCreate(ui.userId, xmlNode);
        logRestRequest(httpServletRequest, xmlNode, "Change rights", Status.OK.getStatusCode());
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (NullPointerException ex) {
        logRestRequest(httpServletRequest, null, null, Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Node " + nodeUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        dataProvider.disconnect();
    }

    return "";
}

From source file:com.portfolio.rest.RestServicePortfolio.java

/********************************************************/

@Path("/rights")
@POST//from  w w w  . java 2s. c o m
@Produces(MediaType.APPLICATION_XML)
public String postChangeRights(String xmlNode, @Context ServletConfig sc,
        @Context HttpServletRequest httpServletRequest) {
    UserInfo ui = checkCredential(httpServletRequest, null, null, null);

    String returnValue = "";
    try {
        /**
         * <node uuid="">
         *   <role name="">
         *     <right RD="" WR="" DL="" />
         *     <action>reset</action>
         *   </role>
         * </node>
         *======
         * <portfolio uuid="">
         *   <xpath>XPATH</xpath>
         *   <role name="">
         *     <right RD="" WR="" DL="" />
         *     <action>reset</action>
         *   </role>
         * </portfolio>
         *======
         * <portfoliogroup name="">
         *   <xpath>XPATH</xpath>
         *   <role name="">
         *     <right RD="" WR="" DL="" />
         *     <action>reset</action>
         *   </role>
         * </portfoliogroup>
         **/

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(new ByteArrayInputStream(xmlNode.getBytes("UTF-8")));

        XPath xPath = XPathFactory.newInstance().newXPath();
        ArrayList<String> portfolio = new ArrayList<String>();
        String xpathRole = "/role";
        XPathExpression findRole = xPath.compile(xpathRole);
        String xpathNodeFilter = "/xpath";
        XPathExpression findXpath = xPath.compile(xpathNodeFilter);
        String nodefilter = "";
        NodeList roles = null;

        /// Fetch portfolio(s)
        String portfolioNode = "//portfoliogroup";
        Node portgroupnode = (Node) xPath.compile(portfolioNode).evaluate(doc, XPathConstants.NODE);
        if (portgroupnode == null) {
            String portgroupname = portgroupnode.getAttributes().getNamedItem("name").getNodeValue();
            // Query portfolio group for list of uuid

            // while( res.next() )
            // portfolio.add(portfolio);

            Node xpathNode = (Node) findXpath.evaluate(portgroupnode, XPathConstants.NODE);
            nodefilter = xpathNode.getNodeValue();
            roles = (NodeList) findRole.evaluate(portgroupnode, XPathConstants.NODESET);
        } else {
            // Or add the single one
            portfolioNode = "//portfolio[@uuid]";
            Node portnode = (Node) xPath.compile(portfolioNode).evaluate(doc, XPathConstants.NODE);
            portfolio.add(portnode.getNodeValue());

            Node xpathNode = (Node) findXpath.evaluate(portnode, XPathConstants.NODE);
            nodefilter = xpathNode.getNodeValue();
            roles = (NodeList) findRole.evaluate(portnode, XPathConstants.NODESET);
        }

        ArrayList<String> nodes = new ArrayList<String>();
        XPathExpression xpathFilter = xPath.compile(nodefilter);
        for (int i = 0; i < portfolio.size(); ++i) // For all portfolio
        {
            String portfolioUuid = portfolio.get(i);
            String portfolioStr = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId,
                    0, this.label, null, null, ui.subId).toString();
            Document docPort = documentBuilder.parse(new ByteArrayInputStream(portfolioStr.getBytes("UTF-8")));

            /// Fetch nodes inside those portfolios
            NodeList portNodes = (NodeList) xpathFilter.evaluate(docPort, XPathConstants.NODESET);
            for (int j = 0; j < portNodes.getLength(); ++j) {
                Node node = portNodes.item(j);
                String nodeuuid = node.getAttributes().getNamedItem("id").getNodeValue();

                nodes.add(nodeuuid); // Keep those we have to change rights
            }
        }

        /// Fetching single node
        if (nodes.isEmpty()) {
            String singleNode = "/node";
            Node sNode = (Node) xPath.compile(singleNode).evaluate(doc, XPathConstants.NODE);
            String uuid = sNode.getAttributes().getNamedItem("uuid").getNodeValue();
            nodes.add(uuid);
            roles = (NodeList) findRole.evaluate(sNode, XPathConstants.NODESET);
        }

        /// For all roles we have to change
        for (int i = 0; i < roles.getLength(); ++i) {
            Node rolenode = roles.item(i);
            String rolename = rolenode.getAttributes().getNamedItem("name").getNodeValue();
            Node right = rolenode.getFirstChild();

            //
            if ("user".equals(rolename)) {
                /// username as role
            }

            if ("#text".equals(right.getNodeName()))
                right = right.getNextSibling();

            if ("right".equals(right.getNodeName())) // Changing node rights
            {
                NamedNodeMap rights = right.getAttributes();

                NodeRight noderight = new NodeRight(null, null, null, null, null, null);

                String val = rights.getNamedItem("RD").getNodeValue();
                if (val != null)
                    noderight.read = Boolean.parseBoolean(val);
                val = rights.getNamedItem("WR").getNodeValue();
                if (val != null)
                    noderight.write = Boolean.parseBoolean(val);
                val = rights.getNamedItem("DL").getNodeValue();
                if (val != null)
                    noderight.delete = Boolean.parseBoolean(val);
                val = rights.getNamedItem("SB").getNodeValue();
                if (val != null)
                    noderight.submit = Boolean.parseBoolean(val);

                /// Apply modification for all nodes
                for (int j = 0; j < nodes.size(); ++j) {
                    String nodeid = nodes.get(j);

                    // change right
                    dataProvider.postRights(ui.userId, nodeid, rolename, noderight);
                }
            } else if ("action".equals(right.getNodeName())) // Using an action on node
            {
                /// Apply modification for all nodes
                for (int j = 0; j < nodes.size(); ++j) {
                    String nodeid = nodes.get(j);

                    // TODO: check for reset keyword
                    // reset right
                    dataProvider.postMacroOnNode(ui.userId, nodeid, "reset");
                }
            }
        }

        //         returnValue = dataProvider.postRRGCreate(ui.userId, xmlNode);
        logRestRequest(httpServletRequest, xmlNode, returnValue, Status.OK.getStatusCode());

        if (returnValue == "faux") {
            throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits d'acces");
        }

        return returnValue;
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, xmlNode,
                ex.getMessage() + "\n\n" + javaUtils.getCompleteStackTrace(ex),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());
        dataProvider.disconnect();
        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        dataProvider.disconnect();
    }
}

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

public List<ViewResult> parsePrescriptionDocumentForPrescriptionLines(byte[] bytes) {
    ArrayList<ViewResult> lines = new ArrayList<ViewResult>();
    try {//  w  w w  .  j  a  v  a 2s.  c  o m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(new ByteArrayInputStream(bytes));

        XPath xpath = XPathFactory.newInstance().newXPath();

        // header xpaths
        //         XPathExpression performerPrefixExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/assignedPerson/name/prefix");
        //         XPathExpression performerSurnameExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/assignedPerson/name/family");
        //         XPathExpression performerGivenNameExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/assignedPerson/name/given");
        //         XPathExpression professionExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/functionCode");
        //         XPathExpression facilityNameExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/representedOrganization/name");
        //         XPathExpression facilityAddressStreetExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/representedOrganization/addr/streetAddressLine");
        //         XPathExpression facilityAddressZipExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/representedOrganization/addr/postalCode");
        //         XPathExpression facilityAddressCityExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/representedOrganization/addr/city");
        //         XPathExpression facilityAddressCountryExpr = xpath.compile("/ClinicalDocument/documentationOf/serviceEvent/performer/assignedEntity/representedOrganization/addr/country");

        XPathExpression performerPrefixExpr = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/assignedPerson/name/prefix");
        XPathExpression performerSurnameExpr = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/assignedPerson/name/family");
        XPathExpression performerGivenNameExpr = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/assignedPerson/name/given");
        XPathExpression professionExpr = xpath.compile("/ClinicalDocument/author/functionCode");
        XPathExpression facilityNameExpr = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization/name");
        XPathExpression facilityAddressStreetExpr = xpath.compile(
                "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr/streetAddressLine");
        XPathExpression facilityAddressZipExpr = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization/addr/postalCode");
        XPathExpression facilityAddressCityExpr = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization/addr/city");
        XPathExpression facilityAddressCountryExpr = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization/addr/country");
        XPathExpression prescriptionIDExpr = xpath.compile(
                "/ClinicalDocument/component/structuredBody/component/section[templateId/@root='1.3.6.1.4.1.12559.11.10.1.3.1.2.1']");

        String performer = "";
        Node performerPrefix = (Node) performerPrefixExpr.evaluate(dom, XPathConstants.NODE);
        if (performerPrefix != null) {
            performer += performerPrefix.getTextContent().trim() + " ";
        }
        Node performerSurname = (Node) performerSurnameExpr.evaluate(dom, XPathConstants.NODE);
        if (performerSurname != null) {
            performer += performerSurname.getTextContent().trim();
        }
        Node performerGivenName = (Node) performerGivenNameExpr.evaluate(dom, XPathConstants.NODE);
        if (performerGivenName != null) {
            performer += " " + performerGivenName.getTextContent().trim();
        }

        String profession = "";
        Node professionNode = (Node) professionExpr.evaluate(dom, XPathConstants.NODE);
        if (professionNode != null) {
            profession += professionNode.getAttributes().getNamedItem("displayName").getNodeValue();
        }

        String facility = "";
        Node facilityNode = (Node) facilityNameExpr.evaluate(dom, XPathConstants.NODE);
        if (facilityNode != null) {
            facility += facilityNode.getTextContent().trim();
        }

        String address = "";
        Node street = (Node) facilityAddressStreetExpr.evaluate(dom, XPathConstants.NODE);
        if (street != null) {
            address += street.getTextContent().trim();
        }
        Node zip = (Node) facilityAddressZipExpr.evaluate(dom, XPathConstants.NODE);
        if (zip != null) {
            address += ", " + zip.getTextContent().trim();
        }
        Node city = (Node) facilityAddressCityExpr.evaluate(dom, XPathConstants.NODE);
        if (city != null) {
            address += ", " + city.getTextContent().trim();
        }
        Node country = (Node) facilityAddressCountryExpr.evaluate(dom, XPathConstants.NODE);
        if (country != null) {
            address += ", " + country.getTextContent().trim();
        }

        // for each prescription component, search for its entries and make up the list
        String prescriptionID = "";
        NodeList prescriptionIDNodes = (NodeList) prescriptionIDExpr.evaluate(dom, XPathConstants.NODESET);
        if (prescriptionIDNodes != null && prescriptionIDNodes.getLength() > 0) {
            XPathExpression idExpr = xpath.compile("id");
            XPathExpression entryExpr = xpath.compile("entry/substanceAdministration");
            XPathExpression nameExpr = xpath
                    .compile("consumable/manufacturedProduct/manufacturedMaterial/name");

            XPathExpression freqExpr = xpath.compile("effectiveTime[@type='PIVL_TS']/period");
            XPathExpression doseExpr = xpath.compile("doseQuantity");
            XPathExpression doseExprLow = xpath.compile("low");
            XPathExpression doseExprHigh = xpath.compile("high");
            XPathExpression doseFormExpr = xpath
                    .compile("consumable/manufacturedProduct/manufacturedMaterial/formCode");
            XPathExpression packQuantityExpr = xpath.compile(
                    "consumable/manufacturedProduct/manufacturedMaterial/asContent/quantity/numerator[@type='epsos:PQ']");
            XPathExpression packQuantityExpr2 = xpath.compile(
                    "consumable/manufacturedProduct/manufacturedMaterial/asContent/quantity/denominator[@type='epsos:PQ']");
            XPathExpression packTypeExpr = xpath.compile(
                    "consumable/manufacturedProduct/manufacturedMaterial/asContent/containerPackagedMedicine/formCode");

            XPathExpression packageExpr = xpath.compile(
                    "consumable/manufacturedProduct/manufacturedMaterial/asContent/containerPackagedMedicine/capacityQuantity");

            XPathExpression ingredientExpr = xpath.compile(
                    "consumable/manufacturedProduct/manufacturedMaterial/ingredient[@classCode='ACTI']/ingredient/code");
            XPathExpression strengthExpr = xpath.compile(
                    "consumable/manufacturedProduct/manufacturedMaterial/ingredient[@classCode='ACTI']/quantity/numerator[@type='epsos:PQ']");
            XPathExpression strengthExpr2 = xpath.compile(
                    "consumable/manufacturedProduct/manufacturedMaterial/ingredient[@classCode='ACTI']/quantity/denominator[@type='epsos:PQ']");

            XPathExpression nrOfPacksExpr = xpath.compile("entryRelationship/supply/quantity");
            //XPathExpression nrOfPacksExpr = xpath.compile("consumable/manufacturedProduct/manufacturedMaterial/asContent/quantity/denominator[@type='epsos:PQ']");

            XPathExpression routeExpr = xpath.compile("routeCode");
            XPathExpression lowExpr = xpath.compile("effectiveTime[@type='IVL_TS']/low");
            XPathExpression highExpr = xpath.compile("effectiveTime[@type='IVL_TS']/high");
            XPathExpression patientInstrEexpr = xpath
                    .compile("entryRelationship/act/code[@code='PINSTRUCT']/../text/reference[@value]");
            XPathExpression fillerInstrEexpr = xpath
                    .compile("entryRelationship/act/code[@code='FINSTRUCT']/../text/reference[@value]");
            XPathExpression substituteInstrExpr = xpath.compile(
                    "entryRelationship[@typeCode='SUBJ'][@inversionInd='true']/observation[@classCode='OBS']/value");

            XPathExpression prescriberPrefixExpr = xpath
                    .compile("author/assignedAuthor/assignedPerson/name/prefix");
            XPathExpression prescriberSurnameExpr = xpath
                    .compile("author/assignedAuthor/assignedPerson/name/family");
            XPathExpression prescriberGivenNameExpr = xpath
                    .compile("author/assignedAuthor/assignedPerson/name/given");

            for (int p = 0; p < prescriptionIDNodes.getLength(); p++) {
                Node sectionNode = prescriptionIDNodes.item(p);
                Node pIDNode = (Node) idExpr.evaluate(sectionNode, XPathConstants.NODE);
                if (pIDNode != null)
                    try {
                        prescriptionID = pIDNode.getAttributes().getNamedItem("extension").getNodeValue();
                        //   prescriptionID = pIDNode.getAttributes().getNamedItem("root").getNodeValue();
                    } catch (Exception e) {

                    }
                else
                    prescriptionID = "";

                String prescriber = "";
                Node prescriberPrefix = (Node) prescriberPrefixExpr.evaluate(sectionNode, XPathConstants.NODE);
                if (prescriberPrefix != null) {
                    prescriber += prescriberPrefix.getTextContent().trim() + " ";
                }
                Node prescriberSurname = (Node) prescriberSurnameExpr.evaluate(sectionNode,
                        XPathConstants.NODE);
                if (prescriberSurname != null) {
                    prescriber += prescriberSurname.getTextContent().trim();
                }
                Node prescriberGivenName = (Node) prescriberGivenNameExpr.evaluate(sectionNode,
                        XPathConstants.NODE);
                if (prescriberGivenName != null) {
                    prescriber += " " + prescriberGivenName.getTextContent().trim();
                }

                if (Validator.isNull(prescriber))
                    prescriber = performer;

                // PRESCRIPTION ITEMS
                NodeList entryList = (NodeList) entryExpr.evaluate(sectionNode, XPathConstants.NODESET);
                if (entryList != null && entryList.getLength() > 0) {
                    for (int i = 0; i < entryList.getLength(); i++) {
                        ViewResult line = new ViewResult(i);

                        Node entryNode = entryList.item(i);

                        String materialID = "";
                        Node materialIDNode = (Node) idExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (materialIDNode != null) {
                            try {
                                materialID = materialIDNode.getAttributes().getNamedItem("extension")
                                        .getNodeValue();
                            } catch (Exception e) {
                                System.out.println("Error getting material");
                            }
                        }

                        Node materialName = (Node) nameExpr.evaluate(entryNode, XPathConstants.NODE);
                        String name = materialName.getTextContent().trim();

                        String packsString = "";
                        Node doseForm = (Node) doseFormExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (doseForm != null)
                            packsString = doseForm.getAttributes().getNamedItem("displayName").getNodeValue();

                        Node packageExpr1 = (Node) packageExpr.evaluate(entryNode, XPathConstants.NODE);
                        Node packType = (Node) packTypeExpr.evaluate(entryNode, XPathConstants.NODE);
                        Node packQuant = (Node) packQuantityExpr.evaluate(entryNode, XPathConstants.NODE);
                        Node packQuant2 = (Node) packQuantityExpr2.evaluate(entryNode, XPathConstants.NODE);

                        String dispensedPackage = "";
                        String dispensedPackageUnit = "";
                        if (packageExpr1 != null) {
                            dispensedPackage = packageExpr1.getAttributes().getNamedItem("value")
                                    .getNodeValue();
                            dispensedPackageUnit = packageExpr1.getAttributes().getNamedItem("unit")
                                    .getNodeValue();
                        }
                        if (packQuant != null && packType != null && packQuant2 != null) {
                            packsString += "#"
                                    + packType.getAttributes().getNamedItem("displayName").getNodeValue() + "#"
                                    + packQuant.getAttributes().getNamedItem("value").getNodeValue();
                            String unit = packQuant.getAttributes().getNamedItem("unit").getNodeValue();
                            if (unit != null && !unit.equals("1"))
                                packsString += " " + unit;
                            String denom = packQuant2.getAttributes().getNamedItem("value").getNodeValue();
                            if (denom != null && !denom.equals("1")) {
                                packsString += " / " + denom;
                                unit = packQuant2.getAttributes().getNamedItem("unit").getNodeValue();
                                if (unit != null && !unit.equals("1"))
                                    packsString += " " + unit;
                            }

                        }

                        String ingredient = "";
                        Node ingrNode = (Node) ingredientExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (ingrNode != null) {
                            ingredient += ingrNode.getAttributes().getNamedItem("code").getNodeValue() + " - "
                                    + ingrNode.getAttributes().getNamedItem("displayName").getNodeValue();
                        }

                        String strength = "";
                        Node strengthExprNode = (Node) strengthExpr.evaluate(entryNode, XPathConstants.NODE);
                        Node strengthExprNode2 = (Node) strengthExpr2.evaluate(entryNode, XPathConstants.NODE);
                        if (strengthExprNode != null && strengthExprNode2 != null) {
                            try {
                                strength = strengthExprNode.getAttributes().getNamedItem("value")
                                        .getNodeValue();
                            } catch (Exception e) {
                                _log.error("Error parsing strength");
                                strength = "";
                            }
                            String unit = "";
                            String unit2 = "";
                            try {
                                unit = strengthExprNode.getAttributes().getNamedItem("unit").getNodeValue();
                            } catch (Exception e) {
                                _log.error("Error parsing unit");
                            }
                            if (unit != null && !unit.equals("1"))
                                strength += " " + unit;
                            String denom = "";
                            try {
                                denom = strengthExprNode2.getAttributes().getNamedItem("value").getNodeValue();
                            } catch (Exception e) {
                                _log.error("Error parsing denom");
                            }
                            if (denom != null) // && !denom.equals("1"))
                            {
                                strength += " / " + denom;
                                try {
                                    unit2 = strengthExprNode2.getAttributes().getNamedItem("unit")
                                            .getNodeValue();
                                } catch (Exception e) {
                                    _log.error("Error parsing unit 2");
                                }
                                if (unit2 != null && !unit2.equals("1"))
                                    strength += " " + unit2;
                            }

                        }

                        String nrOfPacks = "";
                        Node nrOfPacksNode = (Node) nrOfPacksExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (nrOfPacksNode != null) {
                            if (nrOfPacksNode.getAttributes().getNamedItem("value") != null)
                                nrOfPacks = nrOfPacksNode.getAttributes().getNamedItem("value").getNodeValue();
                            if (nrOfPacksNode.getAttributes().getNamedItem("unit") != null) {
                                String unit = nrOfPacksNode.getAttributes().getNamedItem("unit").getNodeValue();
                                if (unit != null && !unit.equals("1"))
                                    nrOfPacks += " " + unit;
                            }
                        }

                        String doseString = "";
                        Node dose = (Node) doseExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (dose != null) {
                            if (dose.getAttributes().getNamedItem("value") != null) {
                                doseString = dose.getAttributes().getNamedItem("value").getNodeValue();
                                if (dose.getAttributes().getNamedItem("unit") != null) {
                                    String unit = dose.getAttributes().getNamedItem("unit").getNodeValue();
                                    if (unit != null && !unit.equals("1"))
                                        doseString += " " + unit;
                                }
                            } else {
                                String lowString = "", highString = "";
                                Node lowDoseNode = (Node) doseExprLow.evaluate(dose, XPathConstants.NODE);
                                if (lowDoseNode != null
                                        && lowDoseNode.getAttributes().getNamedItem("value") != null) {
                                    lowString = lowDoseNode.getAttributes().getNamedItem("value")
                                            .getNodeValue();
                                    if (lowDoseNode.getAttributes().getNamedItem("unit") != null) {
                                        String unit = lowDoseNode.getAttributes().getNamedItem("unit")
                                                .getNodeValue();
                                        if (unit != null && !unit.equals("1"))
                                            lowString += " " + unit;
                                    }
                                }
                                Node highDoseNode = (Node) doseExprHigh.evaluate(dose, XPathConstants.NODE);
                                if (highDoseNode != null
                                        && highDoseNode.getAttributes().getNamedItem("value") != null) {
                                    highString = highDoseNode.getAttributes().getNamedItem("value")
                                            .getNodeValue();
                                    if (highDoseNode.getAttributes().getNamedItem("unit") != null) {
                                        String unit = highDoseNode.getAttributes().getNamedItem("unit")
                                                .getNodeValue();
                                        if (unit != null && !unit.equals("1"))
                                            highString += " " + unit;
                                    }
                                }

                                doseString = Validator.isNotNull(lowString) ? lowString : "";
                                if (Validator.isNotNull(highString) && !lowString.equals(highString)) {
                                    doseString = Validator.isNotNull(doseString)
                                            ? doseString + " - " + highString
                                            : highString;
                                }
                            }
                        }

                        String freqString = "";
                        Node period = (Node) freqExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (period != null) {
                            try {
                                freqString = getSafeString(
                                        period.getAttributes().getNamedItem("value").getNodeValue()
                                                + period.getAttributes().getNamedItem("unit").getNodeValue());
                            } catch (Exception e) {
                                _log.error("### Error getting freqstring");
                            }
                        }

                        String routeString = "";
                        Node route = (Node) routeExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (route != null)
                            try {
                                routeString = getSafeString(
                                        route.getAttributes().getNamedItem("displayName").getNodeValue());
                            } catch (Exception e) {
                                _log.error("error getting route string");
                            }

                        String patientString = "";
                        Node patientInfo = (Node) patientInstrEexpr.evaluate(entryNode, XPathConstants.NODE);
                        if (patientInfo != null)
                            try {
                                patientString = getSafeString(
                                        patientInfo.getAttributes().getNamedItem("value").getNodeValue());
                            } catch (Exception e) {
                                _log.error("error getting route string");
                            }

                        String fillerString = "";
                        Node fillerInfo = (Node) fillerInstrEexpr.evaluate(entryNode, XPathConstants.NODE);
                        if (fillerInfo != null)
                            try {
                                fillerString = getSafeString(
                                        fillerInfo.getAttributes().getNamedItem("value").getNodeValue());
                            } catch (Exception e) {
                                _log.error("error getting route string");
                            }

                        String lowString = "";
                        Node lowNode = (Node) lowExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (lowNode != null) {
                            try {
                                lowString = lowNode.getAttributes().getNamedItem("value").getNodeValue();
                                lowString = dateDecorate(lowString);
                            } catch (Exception e) {
                                _log.error("Error parsing low node ...");
                            }

                        }

                        String highString = "";
                        Node highNode = (Node) highExpr.evaluate(entryNode, XPathConstants.NODE);
                        if (highNode != null) {
                            try {
                                highString = highNode.getAttributes().getNamedItem("value").getNodeValue();
                                highString = dateDecorate(highString);
                            } catch (Exception e) {
                                _log.error("Error parsing high node ...");
                            }
                        }

                        Boolean substitutionPermitted = Boolean.TRUE;
                        Node substituteNode = (Node) substituteInstrExpr.evaluate(entryNode,
                                XPathConstants.NODE);
                        if (substituteNode != null) {
                            String substituteValue = "";
                            try {
                                substituteValue = substituteNode.getAttributes().getNamedItem("code")
                                        .getNodeValue();
                            } catch (Exception e) {
                                substituteValue = "N";
                            }
                            if (substituteValue.equals("N")) {
                                substitutionPermitted = false;
                            }
                            if (substituteValue.equals("EC")) {
                                substitutionPermitted = true;
                            }
                            if (!substituteValue.equals("N") && !substituteValue.equals("EC")) {
                                substitutionPermitted = false;
                            }

                            //                        try {
                            //                           substitutionPermitted = new Boolean(substituteValue);
                            //                        } catch (Exception e) {
                            //                           substitutionPermitted=false;
                            //                        }
                        }

                        line.setField1(name);
                        line.setField2(ingredient);
                        line.setField3(strength);
                        line.setField4(packsString);

                        line.setField5(doseString);
                        line.setField6(freqString);
                        line.setField7(routeString);
                        line.setField8(nrOfPacks);

                        line.setField9(lowString);
                        line.setField10(highString);

                        line.setField11(patientString);
                        line.setField12(fillerString);

                        line.setField13(prescriber);

                        // entry header information
                        line.setField14(prescriptionID);

                        // prescription header information
                        line.setField15(performer);
                        line.setField16(profession);
                        line.setField17(facility);
                        line.setField18(address);

                        line.setField19(materialID);

                        line.setField20(substitutionPermitted);
                        line.setField21(dispensedPackage);
                        line.setField22(dispensedPackageUnit);
                        line.setMainid(lines.size());

                        lines.add(line);
                    }
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return lines;
}

From source file:nl.b3p.ogc.utils.OGCResponse.java

protected NodeList getNodeListFromXPath(Node currentNode, String xPathFrag) throws Exception {
    if (xPathFrag == null || xPathFrag.length() == 0) {
        return null;
    }/*from ww w  .  ja  v a 2 s  .  c o  m*/
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(getNamespaceContext());

    XPathExpression expr = xpath.compile(xPathFrag);
    Object result = expr.evaluate(currentNode, XPathConstants.NODESET);
    return (NodeList) result;
}

From source file:nl.b3p.viewer.admin.stripes.ServiceUsageMatrixActionBean.java

public static XSSFWorkbook createWorkBook(String theXml) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, XPathFactoryConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(theXml)));

    XSSFWorkbook workbook = new XSSFWorkbook();
    String tempProperty = null;//w w  w .  j  av  a2s  .c  o  m
    try {
        Element root = doc.getDocumentElement();
        /* JSTL XML is setting the system property to use the jstl xpath facotry.
         * Remove the setting temporary:
         * see: https://java.net/jira/browse/JSTL-1
         */
        tempProperty = System
                .getProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI);
        if (tempProperty != null) {
            System.clearProperty(
                    XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI);
        }

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression exprFeatureSource = xpath.compile("//featureSource");
        XPathExpression exprFeatureType = xpath.compile("featureType");
        XPathExpression exprApplication = xpath.compile("applications/application");
        XPathExpression exprLayer = xpath.compile("layers/layer");
        XPathExpression exprAppLayer = xpath.compile("applayers/applayer");
        XPathExpression exprId = xpath.compile("id/text()");
        XPathExpression exprAlias = xpath.compile("alias/text()");
        XPathExpression exprName = xpath.compile("name/text()");
        XPathExpression exprVersion = xpath.compile("version/text()");
        XPathExpression exprProtocol = xpath.compile("protocol/text()");
        XPathExpression exprUrl = xpath.compile("url/text()");

        XSSFSheet sheet = workbook.createSheet("Sheet 1");
        int rowNum = 0;

        Row head = sheet.createRow(rowNum++);
        String[] headValues = { "Bron", "Featuretype", "Applicatie", "Layernaam van service",
                "Application layer (kaart)" };
        for (int c = 0; c < headValues.length; c++) {
            Cell cell = head.createCell(c);
            cell.setCellValue(headValues[c]);
        }
        List<String> columns = new ArrayList<String>();
        for (int i = 0; i < headValues.length; i++) {
            columns.add("");
        }
        NodeList featureSources = (NodeList) exprFeatureSource.evaluate(root, XPathConstants.NODESET);

        for (int fs = 0; fs < featureSources.getLength(); fs++) {
            Node featureSource = featureSources.item(fs);

            String fsString = (String) exprName.evaluate(featureSource, XPathConstants.STRING);
            fsString += " (" + (String) exprProtocol.evaluate(featureSource, XPathConstants.STRING);
            fsString += ":: " + (String) exprUrl.evaluate(featureSource, XPathConstants.STRING);
            fsString += " id: " + (String) exprId.evaluate(featureSource, XPathConstants.STRING);
            fsString += ")";
            columns.set(0, fsString);
            NodeList featureTypes = (NodeList) exprFeatureType.evaluate(featureSource, XPathConstants.NODESET);
            for (int ft = 0; ft < featureTypes.getLength(); ft++) {
                Node featureType = featureTypes.item(ft);
                //String ftId = (String) exprId.evaluate(featureType,XPathConstants.STRING);
                String ftName = (String) exprName.evaluate(featureType, XPathConstants.STRING);
                //String ftString = ""+ftName;
                columns.set(1, ftName);
                NodeList applications = (NodeList) exprApplication.evaluate(featureType,
                        XPathConstants.NODESET);
                for (int app = 0; app < applications.getLength(); app++) {
                    Node application = applications.item(app);
                    String appVersion = (String) exprVersion.evaluate(application, XPathConstants.STRING);

                    String appString = (String) exprName.evaluate(application, XPathConstants.STRING);
                    if (appVersion != null) {
                        appString += ", version: " + appVersion;
                    }
                    appString += " (" + (String) exprId.evaluate(application, XPathConstants.STRING) + ")";
                    columns.set(2, appString);
                    NodeList layers = (NodeList) exprLayer.evaluate(application, XPathConstants.NODESET);
                    for (int lay = 0; lay < layers.getLength(); lay++) {
                        Node layer = layers.item(lay);
                        String layerString = "";
                        layerString += (String) exprName.evaluate(layer, XPathConstants.STRING);
                        columns.set(3, layerString);
                        NodeList appLayers = (NodeList) exprAppLayer.evaluate(layer, XPathConstants.NODESET);
                        for (int al = 0; al < appLayers.getLength(); al++) {
                            Node appLayer = appLayers.item(al);
                            String alString = (String) exprAlias.evaluate(appLayer, XPathConstants.STRING);
                            alString += " (" + (String) exprId.evaluate(appLayer, XPathConstants.STRING) + ")";
                            columns.set(4, alString);
                            Row row = sheet.createRow(rowNum++);
                            for (int c = 0; c < columns.size(); c++) {
                                Cell cell = row.createCell(c);
                                cell.setCellValue(columns.get(c));
                            }
                        }
                    }
                }
            }
        }
    } finally {
        if (tempProperty != null) {
            System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME + ":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI,
                    tempProperty);
        }
    }
    return workbook;
}

From source file:nl.imvertor.common.file.XmlFile.java

/**
 * Benader de inhoud dmv. een Xpath expressie.  
 * //from  w  w  w. ja  v a  2  s. co m
 * @param outfile
 * @param xslFilePath
 * @throws Exception
 */
public Object xpathToObject(String expression, HashMap<String, String> parms, QName returnType)
        throws Exception {
    if (dom == null)
        dom = this.buildDom();
    XPathFactoryImpl xpf = new XPathFactoryImpl();
    XPath xpe = xpf.newXPath();
    XPathExpression find = xpe.compile(expression);
    return find.evaluate(dom, returnType);
}

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static Collection<String> evaluateXPathNodeSet(String input, String xpathExpr)
        throws DomBuilderException, XPathExpressionException {
    String msg = XmlUtils.removeNamespaces(input);

    Collection<String> c = new LinkedList<String>();
    Document doc = buildDomDocument(msg, true, true);
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(xpathExpr);
    Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        if (nodes.item(i).getNodeType() == Node.ATTRIBUTE_NODE) {
            c.add(nodes.item(i).getNodeValue());
        } else {//from  w w w. java  2  s  .  c  o m
            //c.add(nodes.item(i).getTextContent());
            c.add(nodes.item(i).getFirstChild().getNodeValue());
        }
    }
    if (c != null && c.size() > 0) {
        return c;
    }
    return null;
}