Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java

/**
 * Generates the premis for amdSec/* ww w. ja v  a 2s  .c  om*/
 *
 * @param metsElement
 * @param datastream
 * @param md5Info
 * @param created
 * @param formatVersion
 * @return
 * @throws MetsExportException
 */
private Node getPremisFile(IMetsElement metsElement, String datastream, FileMD5Info md5Info)
        throws MetsExportException {
    PremisComplexType premis = new PremisComplexType();
    ObjectFactory factory = new ObjectFactory();
    JAXBElement<PremisComplexType> jaxbPremix = factory.createPremis(premis);
    cz.cas.lib.proarc.premis.File file = factory.createFile();
    premis.getObject().add(file);
    ObjectIdentifierComplexType objectIdentifier = new ObjectIdentifierComplexType();
    objectIdentifier.setObjectIdentifierType("ProArc_URI");
    objectIdentifier.setObjectIdentifierValue(
            Const.FEDORAPREFIX + metsElement.getOriginalPid() + "/" + Const.dataStreamToModel.get(datastream));
    file.getObjectIdentifier().add(objectIdentifier);
    PreservationLevelComplexType preservation = new PreservationLevelComplexType();
    if ("RAW".equals(datastream)) {
        preservation.setPreservationLevelValue("deleted");
    } else {
        preservation.setPreservationLevelValue("preservation");
    }
    file.getPreservationLevel().add(preservation);
    ObjectCharacteristicsComplexType characteristics = new ObjectCharacteristicsComplexType();
    characteristics.setCompositionLevel(BigInteger.ZERO);
    file.getObjectCharacteristics().add(characteristics);
    FixityComplexType fixity = new FixityComplexType();
    fixity.setMessageDigest(md5Info.getMd5());
    fixity.setMessageDigestAlgorithm("MD5");
    fixity.setMessageDigestOriginator("ProArc");
    characteristics.getFixity().add(fixity);
    characteristics.setSize(md5Info.getSize());
    FormatComplexType format = new FormatComplexType();
    characteristics.getFormat().add(format);
    FormatDesignationComplexType formatDesignation = new FormatDesignationComplexType();
    formatDesignation.setFormatName(md5Info.getMimeType());
    formatDesignation.setFormatVersion(md5Info.getFormatVersion());
    JAXBElement<FormatDesignationComplexType> jaxbDesignation = factory
            .createFormatDesignation(formatDesignation);
    format.getContent().add(jaxbDesignation);
    FormatRegistryComplexType formatRegistry = new FormatRegistryComplexType();
    formatRegistry.setFormatRegistryName("PRONOM");
    formatRegistry.setFormatRegistryKey(Const.mimeToFmtMap.get(md5Info.getMimeType()));
    JAXBElement<FormatRegistryComplexType> jaxbRegistry = factory.createFormatRegistry(formatRegistry);
    format.getContent().add(jaxbRegistry);

    CreatingApplicationComplexType creatingApplication = new CreatingApplicationComplexType();
    characteristics.getCreatingApplication().add(creatingApplication);
    creatingApplication.getContent().add(factory.createCreatingApplicationName("ProArc"));

    creatingApplication.getContent()
            .add(factory.createCreatingApplicationVersion(metsElement.getMetsContext().getProarcVersion()));
    creatingApplication.getContent()
            .add(factory.createDateCreatedByApplication(MetsUtils.getCurrentDate().toXMLFormat()));

    RelationshipComplexType relationShip = new RelationshipComplexType();

    if (!("RAW").equals(datastream)) {
        relationShip.setRelationshipType("derivation");
        relationShip.setRelationshipSubType("created from");
        RelatedObjectIdentificationComplexType relatedObject = new RelatedObjectIdentificationComplexType();
        relationShip.getRelatedObjectIdentification().add(relatedObject);
        relatedObject.setRelatedObjectIdentifierType("ProArc_URI");
        relatedObject.setRelatedObjectIdentifierValue(
                Const.FEDORAPREFIX + metsElement.getOriginalPid() + "/" + Const.dataStreamToModel.get("RAW"));
        RelatedEventIdentificationComplexType eventObject = new RelatedEventIdentificationComplexType();
        relationShip.getRelatedEventIdentification().add(eventObject);
        eventObject.setRelatedEventIdentifierType("ProArc_EventID");
        eventObject.setRelatedEventIdentifierValue(Const.dataStreamToEvent.get(datastream));
        eventObject.setRelatedEventSequence(BigInteger.ONE);
        file.getRelationship().add(relationShip);
    } else {
        relationShip.setRelationshipType("creation");
        relationShip.setRelationshipSubType("created from");
        LinkingEventIdentifierComplexType eventIdentifier = new LinkingEventIdentifierComplexType();
        file.getLinkingEventIdentifier().add(eventIdentifier);
        eventIdentifier.setLinkingEventIdentifierType("ProArc_EventID");
        eventIdentifier.setLinkingEventIdentifierValue(Const.dataStreamToEvent.get(datastream));
    }

    String originalFile = MetsUtils.xPathEvaluateString(metsElement.getRelsExt(),
            "*[local-name()='RDF']/*[local-name()='Description']/*[local-name()='importFile']");
    OriginalNameComplexType originalName = factory.createOriginalNameComplexType();
    originalName.setValue(originalFile);
    file.setOriginalName(originalName);

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance(PremisComplexType.class);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();

        // Marshal the Object to a Document
        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(jaxbPremix, document);
        XPath xpath = XPathFactory.newInstance().newXPath();
        Node premisNode = (Node) xpath.compile("*[local-name()='premis']/*[local-name()='object']")
                .evaluate(document, XPathConstants.NODE);
        return premisNode;
    } catch (Exception e) {
        throw new MetsExportException(metsElement.getOriginalPid(), "Error while generating premis data", false,
                e);
    }
}

From source file:dk.statsbiblioteket.doms.central.CentralWebserviceImpl.java

@Override
public SearchResultList findObjects(@WebParam(name = "query", targetNamespace = "") String query,
        @WebParam(name = "offset", targetNamespace = "") int offset,
        @WebParam(name = "pageSize", targetNamespace = "") int pageSize) throws MethodFailedException {
    try {//from ww  w  .  j a  va2  s  . com
        log.trace("Entering findObjects with param query=" + query + ", offset=" + offset + ", pageSize="
                + pageSize);

        JSONObject jsonQuery = new JSONObject();
        jsonQuery.put("search.document.resultfields", "recordID, domsshortrecord");
        jsonQuery.put("search.document.query", query);
        jsonQuery.put("search.document.startindex", offset);
        jsonQuery.put("search.document.maxrecords", pageSize);

        SearchWS summaSearch = getSearchWSService();
        String searchResultString = summaSearch.directJSON(jsonQuery.toString());

        Document searchResultDOM = DOM.stringToDOM(searchResultString);
        XPath xPath = XPathFactory.newInstance().newXPath();

        NodeList nodeList = (NodeList) xPath.evaluate("//responsecollection/response/documentresult/record",
                searchResultDOM.getDocumentElement(), XPathConstants.NODESET);

        java.lang.Long hitCount = java.lang.Long
                .parseLong((String) (xPath.evaluate("//responsecollection/response/documentresult/@hitCount",
                        searchResultDOM.getDocumentElement(), XPathConstants.STRING)));

        SearchResultList searchResultList = new SearchResultList();
        searchResultList.setHitCount(hitCount);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            SearchResult searchResult = new SearchResult();

            Node shortRecordNode = (Node) xPath.evaluate("field[@name='domsshortrecord']", node,
                    XPathConstants.NODE);

            if (shortRecordNode != null) {
                Node shortRecord = DOM.stringToDOM(shortRecordNode.getTextContent()).getDocumentElement();
                String pid = xPath.evaluate("pid", shortRecord);
                String title = xPath.evaluate("title", shortRecord);
                searchResult.setPid(pid);
                if (title != null && !title.equals("")) {
                    searchResult.setTitle(title);
                } else {
                    searchResult.setTitle(pid);
                }
                searchResult.setType(xPath.evaluate("type", shortRecord));
                searchResult.setSource(xPath.evaluate("source", shortRecord));
                searchResult.setTime(xPath.evaluate("time", shortRecord));
                searchResult.setDescription(xPath.evaluate("description", shortRecord));
                searchResult.setState(xPath.evaluate("state", shortRecord));

                try {
                    searchResult.setCreatedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("createdDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
                try {
                    searchResult.setModifiedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("modifiedDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
            } else {
                String pid = xPath.evaluate("field[@name='recordID']/text()", node);
                pid = pid.substring(pid.indexOf(':') + 1);
                searchResult.setPid(pid);
                searchResult.setTitle(pid);
                searchResult.setDescription("");
                searchResult.setSource("");
                searchResult.setState("");
                searchResult.setTime("");
                searchResult.setType("");
            }

            searchResultList.getSearchResult().add(searchResult);
        }

        return searchResultList;

    } catch (XPathExpressionException e) {
        log.warn("Failed to execute method", e);
        throw new MethodFailedException("Method failed to execute", "Method failed to execute", e);
    } catch (Exception e) {
        log.warn("Caught Unknown Exception", e);
        throw new MethodFailedException("Server error", "Server error", e);
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 *
 * @param samlMsg the saml response as a string
 * @return a string representing the Assertion
 *//*  www  .j  ava 2  s  .  c  o  m*/
public static String extractAssertionAsString(String samlMsg) {
    String assertion = NO_ASSERTION;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(samlMsg)));

        XPath xPath = XPathFactory.newInstance().newXPath();
        Node node = (Node) xPath.evaluate(ASSERTION_XPATH, doc, XPathConstants.NODE);
        if (node != null) {
            assertion = domnodeToString(node);
        }
    } catch (ParserConfigurationException pce) {
        LOG.error("cannot parse response {}", pce);
    } catch (SAXException saxe) {
        LOG.error("cannot parse response {}", saxe);

    } catch (IOException ioe) {
        LOG.error("cannot parse response {}", ioe);

    } catch (XPathExpressionException xpathe) {
        LOG.error("cannot find the assertion {}", xpathe);

    } catch (TransformerException trfe) {
        LOG.error("cannot output the assertion {}", trfe);

    }

    return assertion;
}

From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java

@Override
public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject, final String query,
        final String select, final String order) throws Exception {
    logger.debug("----Inside getObjects, query: " + query + " & select: " + select + " & order: " + order);

    /* Transfer the call to second method */
    if (query != null && query.toUpperCase().startsWith(queryPhoneFieldConst.toUpperCase())) {

        ScribeCommandObject returnObject = null;

        try {/* www  . j  ava 2  s  .c o  m*/
            /* Query CRM object by Phone field */
            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order, "Phone");

        } catch (final ScribeException firstE) {

            /* Check if record is not found */
            if (firstE.getMessage().contains(ScribeResponseCodes._1004)) {

                try {
                    /* Query CRM object by Home Phone field */
                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order,
                            "Mobile Phone");
                } catch (final ScribeException secondE) {

                    /* Check if record is again not found */
                    if (secondE.getMessage().contains(ScribeResponseCodes._1004)) {

                        try {
                            /* Query CRM object by Home Phone field */
                            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order,
                                    "Home Phone");
                        } catch (final ScribeException thirdE) {

                            /* Check if record is again not found */
                            if (thirdE.getMessage().contains(ScribeResponseCodes._1004)) {

                                try {
                                    /* Query CRM object by Home Phone field */
                                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select,
                                            order, "Other Phone");
                                } catch (final ScribeException fourthE) {

                                    /* Throw the error to user */
                                    throw fourthE;
                                }
                            }
                        }
                    }
                }
            }
        }

        return returnObject;
    } else {

        /* Get user from session manager */
        final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager
                .getSessionInfo(cADCommandObject.getCrmUserId());

        PostMethod postMethod = null;
        try {

            /* Get CRM information from user */
            final String serviceURL = user.getScribeMetaObject().getCrmServiceURL();
            final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol();
            final String sessionId = user.getScribeMetaObject().getCrmSessionId();

            /* Create Zoho URL */
            final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/"
                    + cADCommandObject.getObjectType() + "s/getSearchRecords";

            logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId);

            /* Instantiate post method */
            postMethod = new PostMethod(zohoURL);

            /* Set request parameters */
            postMethod.setParameter("authtoken", sessionId.trim());
            postMethod.setParameter("scope", "crmapi");

            if (!query.equalsIgnoreCase("NONE")) {

                /* Create ZH query */
                final String zhQuery = ZHCRMMessageFormatUtils.createZHQuery(query);

                if (zhQuery != null && !"".equals(zhQuery)) {

                    /* Set search parameter in request */
                    postMethod.setParameter("searchCondition", "(" + zhQuery + ")");
                }
            } else {

                /* Without query param this method is not applicable */
                return this.getObjects(cADCommandObject);
            }

            if (!select.equalsIgnoreCase("ALL")) {

                /* Create ZH select CRM fields information */
                final String zhSelect = ZHCRMMessageFormatUtils.createZHSelect(cADCommandObject, select);

                /* Validate query */
                if (zhSelect != null && !"".equals(zhSelect)) {

                    /* Set request param to select fields */
                    postMethod.setParameter("selectColumns", zhSelect);
                }
            } else {

                /* Set request param to select all fields */
                postMethod.setParameter("selectColumns", "All");
            }

            /* Validate query */
            if (order != null && !"".equals(order)) {

                /* Validate ordering information */
                ZHCRMMessageFormatUtils.parseAndValidateOrderClause(order, orderFieldsSeparator);

                /* Set request param to select fields */
                postMethod.setParameter("sortColumnString",
                        ZHCRMMessageFormatUtils.createZHSortColumnString(order, orderFieldsSeparator));

                /* Set request param to select fields */
                postMethod.setParameter("sortOrderString",
                        ZHCRMMessageFormatUtils.createZHSortOrderString(order, orderFieldsSeparator));
            }

            final HttpClient httpclient = new HttpClient();

            /* Execute method */
            int result = httpclient.executeMethod(postMethod);
            logger.debug("----Inside getObjects response code: " + result + " & body: "
                    + postMethod.getResponseBodyAsString());

            /* Check if response if SUCCESS */
            if (result == HttpStatus.SC_OK) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing all nodes value */
                final XPathExpression expr = xpath
                        .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row");

                /* Get node list from response document */
                final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

                /* Check if records founds */
                if (nodeList != null && nodeList.getLength() == 0) {

                    /* XPath Query for showing error message */
                    XPathExpression errorExpression = xpath.compile("/response/error/message");

                    /* Get erroe message from response document */
                    Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                    /* Check if error message is found */
                    if (errorMessage != null) {

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    } else {

                        /* XPath Query for showing error message */
                        errorExpression = xpath.compile("/response/nodata/message");

                        /* Get erroe message from response document */
                        errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    }
                } else {

                    /* Create new Scribe object list */
                    final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

                    /* Iterate over node list */
                    for (int i = 0; i < nodeList.getLength(); i++) {

                        /* Create list of elements */
                        final List<Element> elementList = new ArrayList<Element>();

                        /* Get node from node list */
                        final Node node = nodeList.item(i);

                        /* Create new Scribe object */
                        final ScribeObject cADbject = new ScribeObject();

                        /* Check if node has child nodes */
                        if (node.hasChildNodes()) {

                            final NodeList subNodeList = node.getChildNodes();

                            /* Create new map for attributes */
                            final Map<String, String> attributeMap = new HashMap<String, String>();

                            /*
                             * Iterate over sub node list and create elements
                             */
                            for (int j = 0; j < subNodeList.getLength(); j++) {

                                final Node subNode = subNodeList.item(j);

                                /* This trick is to avoid empty nodes */
                                if (!subNode.getNodeName().contains("#text")) {

                                    /* Create element from response */
                                    final Element element = (Element) subNode;

                                    /* Populate label map */
                                    attributeMap.put("label", element.getAttribute("val"));

                                    /* Get node name */
                                    final String nodeName = element.getAttribute("val").replace(" ",
                                            spaceCharReplacement);

                                    /* Validate the node name */
                                    if (XMLChar.isValidName(nodeName)) {

                                        /* Add element in list */
                                        elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName,
                                                element.getTextContent(), attributeMap));
                                    } else {
                                        logger.debug(
                                                "----Inside getObjects, found invalid XML node; ignoring field: "
                                                        + element.getAttribute("val"));
                                    }
                                }
                            }
                        }

                        /* Add all CRM fields */
                        cADbject.setXmlContent(elementList);

                        /* Set type information in object */
                        cADbject.setObjectType(cADCommandObject.getObjectType());

                        /* Add Scribe object in list */
                        cADbjectList.add(cADbject);
                    }

                    /* Check if no record found */
                    if (cADbjectList.size() == 0) {
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM");
                    }

                    /* Set the final object in command object */
                    cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
                }
            } else if (result == HttpStatus.SC_FORBIDDEN) {
                throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM");
            } else if (result == HttpStatus.SC_BAD_REQUEST) {
                throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
            } else if (result == HttpStatus.SC_UNAUTHORIZED) {
                throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM");
            } else if (result == HttpStatus.SC_NOT_FOUND) {
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
            } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing error message */
                final XPathExpression errorExpression = xpath.compile("/response/error/message");

                /* Get erroe message from response document */
                final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                if (errorMessage != null) {

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004
                            + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent());
                } else {

                    /* Send user error */
                    throw new ScribeException(
                            ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
                }
            }
        } catch (final ScribeException exception) {
            throw exception;
        } catch (final ParserConfigurationException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final SAXException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final IOException exception) {
            throw new ScribeException(
                    ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM");
        } finally {
            /* Release connection socket */
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }

        return cADCommandObject;
    }
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

@Override
public String getAttributeValueByPathAndAttributeName(String path, final String originalXml,
        String attributeName) throws XPathExpressionException, SAXException, IOException {

    Document document = parse(originalXml);

    XPath xPath = getXPathInstance();

    Element element = (Element) (xPath.evaluate(path, document, XPathConstants.NODE));

    String attributeValue = "";

    if (element != null) {
        if (element.getAttribute(attributeName) != null) {
            attributeValue = element.getAttribute(attributeName);
        }/*from   ww  w  . j av  a 2s.  co  m*/
    }

    return attributeValue;
}

From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java

/**
 * /*from www . jav a 2 s . c  o  m*/
 * @param cADCommandObject
 * @param query
 * @param select
 * @param order
 * @return
 * @throws Exception
 */
private final ScribeCommandObject getObjectsByPhoneField(final ScribeCommandObject cADCommandObject,
        final String query, final String select, final String order, final String phoneFieldName)
        throws Exception {
    logger.debug("----Inside getObjectsByAllPhoneNumbers, query: " + query + " & select: " + select
            + " & order: " + order + " & phoneFieldName: " + phoneFieldName);

    /* Get user from session manager */
    final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager
            .getSessionInfo(cADCommandObject.getCrmUserId());

    PostMethod postMethod = null;
    try {

        /* Get CRM information from user */
        final String serviceURL = user.getScribeMetaObject().getCrmServiceURL();
        final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol();
        final String sessionId = user.getScribeMetaObject().getCrmSessionId();

        /* Create Zoho URL */
        final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/"
                + cADCommandObject.getObjectType() + "s/getSearchRecords";

        logger.debug(
                "----Inside getObjectsByAllPhoneNumbers zohoURL: " + zohoURL + " & sessionId: " + sessionId);

        /* Instantiate post method */
        postMethod = new PostMethod(zohoURL);

        /* Set request parameters */
        postMethod.setParameter("authtoken", sessionId.trim());
        postMethod.setParameter("scope", "crmapi");

        if (!query.equalsIgnoreCase("NONE")) {

            /* Create ZH query */
            final String zhQuery = ZHCRMMessageFormatUtils.createZHQueryForPhoneFields(query, phoneFieldName);

            if (zhQuery != null && !"".equals(zhQuery)) {

                /* Set search parameter in request */
                postMethod.setParameter("searchCondition", "(" + zhQuery + ")");
            }
        } else {

            /* Without query param this method is not applicable */
            return this.getObjects(cADCommandObject);
        }

        if (select != null && !select.equalsIgnoreCase("ALL")) {

            /* Create ZH select CRM fields information */
            final String zhSelect = ZHCRMMessageFormatUtils.createZHSelect(cADCommandObject, select);

            /* Validate query */
            if (zhSelect != null && !"".equals(zhSelect)) {

                /* Set request param to select fields */
                postMethod.setParameter("selectColumns", zhSelect);
            }
        } else {

            /* Set request param to select all fields */
            postMethod.setParameter("selectColumns", "All");
        }

        /* Validate query */
        if (order != null && !"".equals(order)) {

            /* Validate ordering information */
            ZHCRMMessageFormatUtils.parseAndValidateOrderClause(order, orderFieldsSeparator);

            /* Set request param to select fields */
            postMethod.setParameter("sortColumnString",
                    ZHCRMMessageFormatUtils.createZHSortColumnString(order, orderFieldsSeparator));

            /* Set request param to select fields */
            postMethod.setParameter("sortOrderString",
                    ZHCRMMessageFormatUtils.createZHSortOrderString(order, orderFieldsSeparator));
        }

        final HttpClient httpclient = new HttpClient();

        /* Execute method */
        int result = httpclient.executeMethod(postMethod);
        logger.debug("----Inside getObjectsByAllPhoneNumbers response code: " + result + " & body: "
                + postMethod.getResponseBodyAsString());

        /* Check if response if SUCCESS */
        if (result == HttpStatus.SC_OK) {

            /* Create XML document from response */
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(postMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing all nodes value */
            final XPathExpression expr = xpath
                    .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row");

            /* Get node list from response document */
            final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

            /* Check if records founds */
            if (nodeList != null && nodeList.getLength() == 0) {

                /* XPath Query for showing error message */
                XPathExpression errorExpression = xpath.compile("/response/error/message");

                /* Get erroe message from response document */
                Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                /* Check if error message is found */
                if (errorMessage != null) {

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                            + errorMessage.getTextContent());
                } else {

                    /* XPath Query for showing error message */
                    errorExpression = xpath.compile("/response/nodata/message");

                    /* Get erroe message from response document */
                    errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                            + errorMessage.getTextContent());
                }
            } else {

                /* Create new Scribe object list */
                final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

                /* Iterate over node list */
                for (int i = 0; i < nodeList.getLength(); i++) {

                    /* Create list of elements */
                    final List<Element> elementList = new ArrayList<Element>();

                    /* Get node from node list */
                    final Node node = nodeList.item(i);

                    /* Create new Scribe object */
                    final ScribeObject cADbject = new ScribeObject();

                    /* Check if node has child nodes */
                    if (node.hasChildNodes()) {

                        final NodeList subNodeList = node.getChildNodes();

                        /* Create new map for attributes */
                        final Map<String, String> attributeMap = new HashMap<String, String>();

                        /* Iterate over sub node list and create elements */
                        for (int j = 0; j < subNodeList.getLength(); j++) {

                            final Node subNode = subNodeList.item(j);

                            /* This trick is to avoid empty nodes */
                            if (!subNode.getNodeName().contains("#text")) {

                                /* Create element from response */
                                final Element element = (Element) subNode;

                                /* Populate label map */
                                attributeMap.put("label", element.getAttribute("val"));

                                /* Get node name */
                                final String nodeName = element.getAttribute("val").replace(" ",
                                        spaceCharReplacement);

                                /* Validate the node name */
                                if (XMLChar.isValidName(nodeName)) {

                                    /* Add element in list */
                                    elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName,
                                            element.getTextContent(), attributeMap));
                                } else {
                                    logger.debug(
                                            "----Inside getObjectsByAllPhoneNumbers, found invalid XML node; ignoring field: "
                                                    + element.getAttribute("val"));
                                }
                            }
                        }
                    }

                    /* Add all CRM fields */
                    cADbject.setXmlContent(elementList);

                    /* Set type information in object */
                    cADbject.setObjectType(cADCommandObject.getObjectType());

                    /* Add Scribe object in list */
                    cADbjectList.add(cADbject);
                }

                /* Check if no record found */
                if (cADbjectList.size() == 0) {
                    throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM");
                }

                /* Set the final object in command object */
                cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
            }
        } else if (result == HttpStatus.SC_FORBIDDEN) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM");
        } else if (result == HttpStatus.SC_BAD_REQUEST) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
        } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

            /* Create XML document from response */
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(postMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing error message */
            final XPathExpression errorExpression = xpath.compile("/response/error/message");

            /* Get erroe message from response document */
            final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

            if (errorMessage != null) {

                /* Send user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM : "
                        + errorMessage.getTextContent());
            } else {

                /* Send user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
            }
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM");
    } finally {
        /* Release connection socket */
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java

@Override
public final ScribeCommandObject createObject(final ScribeCommandObject cADCommandObject) throws Exception {
    logger.debug("----Inside createObject");

    /* Get user from session manager */
    final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager
            .getSessionInfo(cADCommandObject.getCrmUserId());

    PostMethod postMethod = null;/*w  ww  .j a va  2 s  .c  o m*/
    try {

        /* Get CRM information from user */
        final String serviceURL = user.getScribeMetaObject().getCrmServiceURL();
        final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol();
        final String sessionId = user.getScribeMetaObject().getCrmSessionId();

        /* Create Zoho URL */
        final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/"
                + cADCommandObject.getObjectType() + "s/insertRecords";

        logger.debug("----Inside createObject, zohoURL: " + zohoURL + " & sessionId: " + sessionId);

        /* Instantiate post method */
        postMethod = new PostMethod(zohoURL);

        final String xmlData = ZHCRMMessageFormatUtils.createRequestString(cADCommandObject,
                spaceCharReplacement, permittedDateFormats, zohoInputDateFormat);

        /* Validate xmlData */
        if (xmlData != null && !"".equals(xmlData)) {

            /* Set request param to send request data */
            postMethod.setParameter("xmlData", xmlData);
        }

        /* Set request parameters */
        postMethod.setParameter("authtoken", sessionId.trim());
        postMethod.setParameter("scope", "crmapi");

        final HttpClient httpclient = new HttpClient();

        /* Execute method */
        int result = httpclient.executeMethod(postMethod);
        logger.debug("----Inside createObject response code: " + result + " & body: "
                + postMethod.getResponseBodyAsString());

        /* Check if response if SUCCESS */
        if (result == HttpStatus.SC_OK) {

            /* Create XML document from response */
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(postMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing all nodes value */
            final XPathExpression expr = xpath.compile("/response/result/recorddetail");

            /* Get node list from response document */
            final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

            /* Check if records founds */
            if (nodeList.getLength() == 0) {

                /* XPath Query for showing error message */
                final XPathExpression errorExpression = xpath.compile("/response/error/message");

                /* Get erroe message from response document */
                final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                /* Send user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "Not able to create record at Zoho CRM : "
                        + errorMessage.getTextContent());

            } else {

                /* Iterate over node list */
                for (int i = 0; i < nodeList.getLength(); i++) {

                    /* Get node from node list */
                    final Node node = nodeList.item(i);

                    /* Check if node has child nodes */
                    if (node.hasChildNodes()) {

                        final NodeList subNodeList = node.getChildNodes();

                        /* Iterate over sub node list and create elements */
                        for (int j = 0; j < subNodeList.getLength(); j++) {

                            final Node subNode = subNodeList.item(j);

                            /* This trick is to avoid empty nodes */
                            if (!subNode.getNodeName().contains("#text")) {

                                /* Create element from response */
                                final Element element = (Element) subNode;

                                if (element.getAttribute("val").equalsIgnoreCase(("ID"))) {

                                    /* Set object id in request object */
                                    cADCommandObject.getObject()[0] = ZHCRMMessageFormatUtils.addNode("Id",
                                            element.getTextContent(), cADCommandObject.getObject()[0]);
                                }
                            }
                        }
                    }
                }
            }
        } else if (result == HttpStatus.SC_FORBIDDEN) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM");
        } else if (result == HttpStatus.SC_BAD_REQUEST) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
        } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

            /* Create XML document from response */
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder builder = factory.newDocumentBuilder();
            final Document document = builder.parse(postMethod.getResponseBodyAsStream());

            /* Create new XPath object to query XML document */
            final XPath xpath = XPathFactory.newInstance().newXPath();

            /* XPath Query for showing error message */
            final XPathExpression errorExpression = xpath.compile("/response/error/message");

            /* Get erroe message from response document */
            final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

            if (errorMessage != null) {

                /* Send user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "Not able to create record at Zoho CRM : "
                        + errorMessage.getTextContent());
            } else {

                /* Send user error */
                throw new ScribeException(ScribeResponseCodes._1004 + "Not able to create record at Zoho CRM");
            }
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM", exception);
    } finally {
        /* Release connection socket */
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

private List<Subscription> importSubscription(@NotNull String publishSettingsFilePath)
        throws AzureCmdException {
    try {/*  w ww  . ja  v  a2  s .c o  m*/
        StringBuilder sb = new StringBuilder();

        BufferedReader br = new BufferedReader(new FileReader(publishSettingsFilePath));
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        //            String subscriptionFile = OpenSSLHelper.processCertificate(sb.toString());

        String publishSettingsFile = sb.toString();

        String managementCertificate = null;
        String serviceManagementUrl = null;
        boolean isPublishSettings2 = true;
        Node publishProfile = (Node) XmlHelper.getXMLValue(publishSettingsFile, "//PublishProfile",
                XPathConstants.NODE);
        if (XmlHelper.getAttributeValue(publishProfile, "SchemaVersion") == null
                || !XmlHelper.getAttributeValue(publishProfile, "SchemaVersion").equals("2.0")) {
            isPublishSettings2 = false;
            managementCertificate = XmlHelper.getAttributeValue(publishProfile, "ManagementCertificate");
            serviceManagementUrl = XmlHelper.getAttributeValue(publishProfile, "Url");
        }
        NodeList subscriptionNodes = (NodeList) XmlHelper.getXMLValue(publishSettingsFile, "//Subscription",
                XPathConstants.NODESET);

        List<Subscription> subscriptions = new ArrayList<Subscription>();

        for (int i = 0; i < subscriptionNodes.getLength(); i++) {
            Node subscriptionNode = subscriptionNodes.item(i);
            Subscription subscription = new Subscription();
            subscription.setName(XmlHelper.getAttributeValue(subscriptionNode, "Name"));
            subscription.setId(XmlHelper.getAttributeValue(subscriptionNode, "Id"));
            if (isPublishSettings2) {
                subscription.setManagementCertificate(
                        XmlHelper.getAttributeValue(subscriptionNode, "ManagementCertificate"));
                subscription.setServiceManagementUrl(
                        XmlHelper.getAttributeValue(subscriptionNode, "ServiceManagementUrl"));
            } else {
                subscription.setManagementCertificate(managementCertificate);
                subscription.setServiceManagementUrl(serviceManagementUrl);
            }
            subscription.setSelected(true);

            Configuration config = AzureSDKHelper.getConfiguration(new File(publishSettingsFilePath),
                    subscription.getId());
            SubscriptionGetResponse response = WindowsAzureRestUtils.getSubscription(config);
            com.microsoftopentechnologies.azuremanagementutil.model.Subscription sub = SubscriptionTransformer
                    .transform(response);
            subscription.setMaxStorageAccounts(sub.getMaxStorageAccounts());
            subscription.setMaxHostedServices(sub.getMaxHostedServices());

            subscriptions.add(subscription);
        }

        return subscriptions;
    } catch (Exception ex) {
        if (ex instanceof AzureCmdException) {
            throw (AzureCmdException) ex;
        }

        throw new AzureCmdException("Error importing subscriptions from publish settings file", ex);
    }
}

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

public List<ViewResult> parsePrescriptionDocumentForPrescriptionLines(byte[] bytes) {
    ArrayList<ViewResult> lines = new ArrayList<ViewResult>();
    try {// w ww .j  av  a  2s .  com
        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:com.ext.portlet.epsos.EpsosHelperService.java

public byte[] generateDispensationDocumentFromPrescription(byte[] bytes, List<ViewResult> lines,
        List<ViewResult> dispensedLines, SpiritUserClientDto doctor, User user) {
    byte[] bytesED = null;
    try {/*  w w  w.  j  a  v a2 s .  c o  m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(new ByteArrayInputStream(bytes));

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

        // TODO change effective time
        // TODO change language code to fit dispenser
        // TODO change OID, have to use country b OID
        // TODO author must be the dispenser not the prescriber
        // TODO custodian and legal authenticator should be not copied from ep doc
        // TODO

        // fixes 
        // First I have to check if exists in order not to create it
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "state", "N/A");

        // add telecom to patient role
        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "state",
                "N/A");

        // add street Address Line
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "streetAddressLine", "N/A");

        // add City
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "city", "N/A");
        // add postalcode
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "postalCode", "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr",
                "streetAddressLine", "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "city",
                "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr",
                "postalCode", "N/A");

        changeNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization", "name",
                "N/A");

        fixNode(dom, xpath,
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/author/assignedAuthor/representedOrganization/addr",
                "postalCode", "N/A");

        String ful_ext = "";
        String ful_root = "";
        XPathExpression ful1 = xpath.compile("/ClinicalDocument/component/structuredBody/component/section/id");
        NodeList fulRONodes = (NodeList) ful1.evaluate(dom, XPathConstants.NODESET);

        if (fulRONodes.getLength() > 0) {
            for (int t = 0; t < fulRONodes.getLength(); t++) {
                Node AddrNode = fulRONodes.item(t);
                try {
                    ful_ext = AddrNode.getAttributes().getNamedItem("extension").getNodeValue() + "";
                    ful_root = AddrNode.getAttributes().getNamedItem("root").getNodeValue() + "";
                } catch (Exception e) {
                }
            }
        }

        // fix infullfillment
        XPathExpression rootNodeExpr = xpath.compile("/ClinicalDocument");
        Node rootNode = (Node) rootNodeExpr.evaluate(dom, XPathConstants.NODE);

        try {
            Node infulfilment = null;
            XPathExpression salRO = xpath.compile("/ClinicalDocument/inFulfillmentOf");
            NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET);
            if (salRONodes.getLength() == 0) {
                XPathExpression salAddr = xpath.compile("/ClinicalDocument/relatedDocument");
                NodeList salAddrNodes = (NodeList) salAddr.evaluate(dom, XPathConstants.NODESET);
                if (salAddrNodes.getLength() > 0) {
                    for (int t = 0; t < salAddrNodes.getLength(); t++) {
                        Node AddrNode = salAddrNodes.item(t);
                        Node order = dom.createElement("inFulfillmentOf");
                        //legalNode.appendChild(order);
                        /*
                         * <relatedDocument typeCode="XFRM">
                        *      <parentDocument>
                        *      <id extension="2601010002.pdf.ep.52105899467.52105899468:39" root="2.16.840.1.113883.2.24.2.30"/>
                        *                     </parentDocument>
                        *                  </relatedDocument>
                         * 
                         * 
                         */
                        //Node order1 = dom.createElement("order");
                        Node order1 = dom.createElement("relatedDocument");
                        Node parentDoc = dom.createElement("parentDocument");
                        addAttribute(dom, parentDoc, "typeCode", "XFRM");
                        order1.appendChild(parentDoc);

                        Node orderNode = dom.createElement("id");
                        addAttribute(dom, orderNode, "extension", ful_ext);
                        addAttribute(dom, orderNode, "root", ful_root);
                        parentDoc.appendChild(orderNode);
                        rootNode.insertBefore(order, AddrNode);
                        infulfilment = rootNode.cloneNode(true);

                    }
                }
            }
        } catch (Exception e) {
            _log.error("Error fixing node inFulfillmentOf ...");
        }

        XPathExpression Telecom = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization");
        NodeList TelecomNodes = (NodeList) Telecom.evaluate(dom, XPathConstants.NODESET);
        if (TelecomNodes.getLength() == 0) {
            for (int t = 0; t < TelecomNodes.getLength(); t++) {
                Node TelecomNode = TelecomNodes.item(t);
                Node telecom = dom.createElement("telecom");
                addAttribute(dom, telecom, "use", "WP");
                addAttribute(dom, telecom, "value", "mailto:demo@epsos.eu");
                TelecomNode.insertBefore(telecom, TelecomNodes.item(0));
            }
        }

        // header xpaths
        XPathExpression clinicalDocExpr = xpath.compile("/ClinicalDocument");
        Node clinicalDocNode = (Node) clinicalDocExpr.evaluate(dom, XPathConstants.NODE);
        if (clinicalDocNode != null) {
            addAttribute(dom, clinicalDocNode, "xmlns", "urn:hl7-org:v3");
            addAttribute(dom, clinicalDocNode, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            addAttribute(dom, clinicalDocNode, "xsi:schemaLocation",
                    "urn:hl7-org:v3 CDASchema/CDA_extended.xsd");
            addAttribute(dom, clinicalDocNode, "classCode", "DOCCLIN");
            addAttribute(dom, clinicalDocNode, "moodCode", "EVN");
        }

        XPathExpression docTemplateIdExpr = xpath.compile("/ClinicalDocument/templateId");
        XPathExpression docCodeExpr = xpath.compile("/ClinicalDocument/code[@codeSystemName='"
                + XML_LOINC_SYSTEM + "' and @codeSystem='" + XML_LOINC_CODESYSTEM + "']");
        XPathExpression docTitleExpr = xpath.compile("/ClinicalDocument/title");

        // change templateId / LOINC code / title to dispensation root code
        NodeList templateIdNodes = (NodeList) docTemplateIdExpr.evaluate(dom, XPathConstants.NODESET);
        if (templateIdNodes != null) {
            for (int t = 0; t < templateIdNodes.getLength(); t++) {
                Node templateIdNode = templateIdNodes.item(t);
                templateIdNode.getAttributes().getNamedItem("root").setNodeValue(XML_DISPENSATION_TEMPLATEID);

                if (t > 0)
                    templateIdNode.getParentNode().removeChild(templateIdNode); // remove extra templateId nodes
            }
        }
        Node codeNode = (Node) docCodeExpr.evaluate(dom, XPathConstants.NODE);
        if (codeNode != null) {
            if (codeNode.getAttributes().getNamedItem("code") != null)
                codeNode.getAttributes().getNamedItem("code").setNodeValue(XML_DISPENSATION_LOINC_CODE);
            if (codeNode.getAttributes().getNamedItem("displayName") != null)
                codeNode.getAttributes().getNamedItem("displayName").setNodeValue("eDispensation");
            if (codeNode.getAttributes().getNamedItem("codeSystemName") != null)
                codeNode.getAttributes().getNamedItem("codeSystemName")
                        .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEMNAME);
            if (codeNode.getAttributes().getNamedItem("codeSystem") != null)
                codeNode.getAttributes().getNamedItem("codeSystem")
                        .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEM);
        }
        Node titleNode = (Node) docTitleExpr.evaluate(dom, XPathConstants.NODE);
        if (titleNode != null) {
            titleNode.setTextContent(XML_DISPENSATION_TITLE);
        }

        XPathExpression sectionExpr = xpath
                .compile("/ClinicalDocument/component/structuredBody/component/section[templateId/@root='"
                        + XML_PRESCRIPTION_ENTRY_TEMPLATEID + "']");
        XPathExpression substanceExpr = xpath.compile("entry/substanceAdministration");
        XPathExpression idExpr = xpath.compile("id");
        NodeList prescriptionNodes = (NodeList) sectionExpr.evaluate(dom, XPathConstants.NODESET);

        //   substanceAdministration.appendChild(newAuthorNode);

        if (prescriptionNodes != null && prescriptionNodes.getLength() > 0) {

            // calculate list of prescription ids to keep
            // calculate list of prescription lines to keep
            Set<String> prescriptionIdsToKeep = new HashSet<String>();
            Set<String> materialIdsToKeep = new HashSet<String>();
            HashMap<String, Node> materialReferences = new HashMap<String, Node>();
            if (dispensedLines != null && dispensedLines.size() > 0) {
                for (int i = 0; i < dispensedLines.size(); i++) {
                    ViewResult d_line = dispensedLines.get(i);
                    materialIdsToKeep.add((String) d_line.getField10());
                    prescriptionIdsToKeep.add((String) d_line.getField9());
                }
            }

            Node structuredBodyNode = null;
            for (int p = 0; p < prescriptionNodes.getLength(); p++) {
                // for each one of the prescription nodes (<component> tags) check if their id belongs to the list of prescription Ids to keep in dispensation document
                Node sectionNode = prescriptionNodes.item(p);
                Node idNode = (Node) idExpr.evaluate(sectionNode, XPathConstants.NODE);
                String prescrId = idNode.getAttributes().getNamedItem("extension").getNodeValue();
                if (prescriptionIdsToKeep.contains(prescrId)) {
                    NodeList substanceAdministrationNodes = (NodeList) substanceExpr.evaluate(sectionNode,
                            XPathConstants.NODESET);
                    if (substanceAdministrationNodes != null && substanceAdministrationNodes.getLength() > 0) {
                        for (int s = 0; s < substanceAdministrationNodes.getLength(); s++) {
                            // for each of the entries (substanceAdministration tags) within this prescription node
                            // check if the materialid in question is one of the dispensed ones, else do nothing
                            Node substanceAdministration = (Node) substanceAdministrationNodes.item(s);
                            Node substanceIdNode = (Node) idExpr.evaluate(substanceAdministration,
                                    XPathConstants.NODE);
                            String materialid = "";
                            try {
                                materialid = substanceIdNode.getAttributes().getNamedItem("extension")
                                        .getNodeValue();
                            } catch (Exception e) {
                                _log.error("error setting materialid");
                            }

                            if (materialIdsToKeep.contains(materialid)) {
                                // if the materialid is one of the dispensed ones, keep the substanceAdminstration node intact,
                                // as it will be used as an entryRelationship in the dispensation entry we will create
                                Node entryRelationshipNode = dom.createElement("entryRelationship");
                                addAttribute(dom, entryRelationshipNode, "typeCode", "REFR");
                                addTemplateId(dom, entryRelationshipNode, XML_DISPENSTATION_ENTRY_REFERENCEID);

                                entryRelationshipNode.appendChild(substanceAdministration);
                                materialReferences.put(materialid, entryRelationshipNode);

                            }
                        }
                    }
                }

                //    Then delete this node, dispensed lines will be written afterwards
                Node componentNode = sectionNode.getParentNode(); // component
                structuredBodyNode = componentNode.getParentNode(); // structuredBody
                structuredBodyNode.removeChild(componentNode);

            }

            // at the end of this for loop, prescription lines are removed from the document, and materialReferences hashmap contains
            // a mapping from materialId to ready nodes containing the entry relationship references to the corresponding prescription lines
            Node dispComponent = dom.createElement("component");
            Node dispSection = dom.createElement("section");

            addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_PARENT_TEMPLATEID);
            addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_TEMPLATEID);

            Node dispIdNode = dom.createElement("id");
            //addAttribute(dom, dispIdNode, "root", prescriptionIdsToKeep.iterator().next());
            addAttribute(dom, dispIdNode, "root", ful_root);
            addAttribute(dom, dispIdNode, "extension", ful_ext);
            dispSection.appendChild(dispIdNode);

            Node sectionCodeNode = dom.createElement("code");
            addAttribute(dom, sectionCodeNode, "code", "60590-7");
            addAttribute(dom, sectionCodeNode, "displayName", XML_DISPENSATION_TITLE);
            addAttribute(dom, sectionCodeNode, "codeSystem", XML_DISPENSATION_LOINC_CODESYSTEM);
            addAttribute(dom, sectionCodeNode, "codeSystemName", XML_DISPENSATION_LOINC_CODESYSTEMNAME);
            dispSection.appendChild(sectionCodeNode);

            Node title = dom.createElement("title");
            title.setTextContent(XML_DISPENSATION_TITLE);
            dispSection.appendChild(title);

            Node text = dom.createElement("text");
            Node textContent = this.generateDispensedLinesHtml(dispensedLines, db);
            textContent = textContent.cloneNode(true);
            dom.adoptNode(textContent);
            text.appendChild(textContent);
            dispSection.appendChild(text);
            dispComponent.appendChild(dispSection);

            structuredBodyNode.appendChild(dispComponent);

            for (int i = 0; i < dispensedLines.size(); i++) {
                ViewResult d_line = dispensedLines.get(i);
                String materialid = (String) d_line.getField10();
                // for each dispensed line create a dispensation entry in the document, and use the entryRelationship calculated above
                Node entry = dom.createElement("entry");
                Node supply = dom.createElement("supply");
                addAttribute(dom, supply, "classCode", "SPLY");
                addAttribute(dom, supply, "moodCode", "EVN");

                // add templateId tags
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE1);
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE2);
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE3);

                // add id tag
                Node supplyId = dom.createElement("id");
                addAttribute(dom, supplyId, "root", XML_DISPENSATION_ENTRY_SUPPLY_ID_ROOT);
                addAttribute(dom, supplyId, "extension", (String) d_line.getField1());
                supply.appendChild(supplyId);

                // add quantity tag
                Node quantity = dom.createElement("quantity");
                String nrOfPacks = (String) d_line.getField8();
                nrOfPacks = nrOfPacks.trim();
                String value = nrOfPacks;
                String unit = "1";
                if (nrOfPacks.indexOf(" ") != -1) {
                    value = nrOfPacks.substring(0, nrOfPacks.indexOf(" "));
                    unit = nrOfPacks.substring(nrOfPacks.indexOf(" ") + 1);
                }
                addAttribute(dom, quantity, "value", (String) d_line.getField7());
                addAttribute(dom, quantity, "unit", (String) d_line.getField12());
                supply.appendChild(quantity);

                // add product tag
                addProductTag(dom, supply, d_line, materialReferences.get(materialid));

                // add performer tag
                addPerformerTag(dom, supply, doctor);

                // add entryRelationship tag
                supply.appendChild(materialReferences.get(materialid));

                // add substitution relationship tag
                if (d_line.getField3() != null && ((Boolean) d_line.getField3()).booleanValue()) {
                    Node substitutionNode = dom.createElement("entryRelationship");
                    addAttribute(dom, substitutionNode, "typeCode", "COMP");
                    Node substanceAdminNode = dom.createElement("substanceAdministration");
                    addAttribute(dom, substanceAdminNode, "classCode", "SBADM");
                    addAttribute(dom, substanceAdminNode, "moodCode", "INT");

                    Node seqNode = dom.createElement("doseQuantity");
                    addAttribute(dom, seqNode, "value", "1");
                    addAttribute(dom, seqNode, "unit", "1");
                    substanceAdminNode.appendChild(seqNode);
                    substitutionNode.appendChild(substanceAdminNode);
                    // changed quantity
                    if (lines.get(0).getField21().equals(d_line.getField7())) {

                    }
                    // changed name
                    if (lines.get(0).getField11().equals(d_line.getField2())) {

                    }
                    supply.appendChild(substitutionNode);
                }
                entry.appendChild(supply);
                dispSection.appendChild(entry);
            }

        }

        // copy author tag from eprescription
        XPathExpression authorExpr = xpath.compile("/ClinicalDocument/author");
        Node oldAuthorNode = (Node) authorExpr.evaluate(dom, XPathConstants.NODE);
        Node newAuthorNode = oldAuthorNode.cloneNode(true);

        XPathExpression substExpr = xpath.compile(
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration");
        NodeList substNodes = (NodeList) substExpr.evaluate(dom, XPathConstants.NODESET);

        XPathExpression entryRelExpr = xpath.compile(
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/entryRelationship");
        NodeList entryRelNodes = (NodeList) entryRelExpr.evaluate(dom, XPathConstants.NODESET);
        Node entryRelNode = (Node) entryRelExpr.evaluate(dom, XPathConstants.NODE);

        if (substNodes != null) {
            //            for (int t=0; t<substNodes.getLength(); t++)
            //            {         
            int t = 0;
            Node substNode = substNodes.item(t);
            substNode.insertBefore(newAuthorNode, entryRelNode);
            //            }
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(dom);
        transformer.transform(source, result);

        String xmlString = result.getWriter().toString();
        bytesED = xmlString.getBytes();
        System.out.println(xmlString);

    } catch (Exception e) {
        _log.error(e.getMessage());
    }

    return bytesED;
}