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:com.ext.portlet.epsos.EpsosHelperService.java

/**
 * Add a tag of the form below under the given node:
 * //ww  w.  ja va  2 s  .c  o m
 * <product>
                <manufacturedProduct xmlns:epsos="urn:epsos-org:ep:medication" classCode="MANU">
                   <templateId root='1.3.6.1.4.1.19376.1.5.3.1.4.7.2'/>
                   <templateId root='2.16.840.1.113883.10.20.1.53'/>
                   <manufacturedMaterial classCode="MMAT" determinerCode="KIND">
                      <templateId root='1.3.6.1.4.1.12559.11.10.1.3.1.3.1'/>
                      <!-- Id  dispensed product--> 
                      <epsos:id root="222" extension="3213"/>
                      <code code="409120009" displayName="Metformin and rosiglitazone" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT">
                         <!-- Optional generic name -->
                         <originalText>
                            <reference value="reference"/>
                         </originalText>
                      </code>
                      <name>Metformina y rosiglitazona</name>
                      <!--Dose form  -->
                      <epsos:formCode code="10221000" displayName="Film-coated tablet" codeSystem="1.3.6.1.4.1.12559.11.10.1.3.1.42.2" codeSystemName="epSOS:DoseForm"/>
                              
                      <epsos:asContent classCode="CONT">
                         <!-- Package size-->
                         <epsos:quantity>
                            <epsos:numerator xsi:type="epsos:PQ" value="112" unit="1" />
                            <epsos:denominator xsi:type="epsos:PQ" value="1" unit="1"/>
                         </epsos:quantity>
                         <!-- Package -->
                         <epsos:containerPackagedMedicine classCode="CONT" determinerCode="INSTANCE">
                            <epsos:formCode code="30009000" displayName="Box" codeSystem="1.3.6.1.4.1.12559.11.10.1.3.1.42.3" codeSystemName="epSOS:Package"/>
                            <!-- A10BD03 Metformin and rosiglitazone -->
                            <epsos:name> Metformin and rosiglitazone</epsos:name>
                            <!-- random lot number has been assigned-->
                            <epsos:lotNumberText>1322231</epsos:lotNumberText>
                            <epsos:capacityQuantity value=' 112' unit='1'/>
                                    
                            <!-- child proof-->
                            <epsos:capTypeCode code="ChildProof"/>
                         </epsos:containerPackagedMedicine>
                      </epsos:asContent>
                      <epsos:ingredient classCode="ACTI">
                         <!--Strength, -->
                         <epsos:quantity>
                            <epsos:numerator xsi:type="epsos:PQ" value="500+2" unit="mg"/>
                            <epsos:denominator xsi:type="epsos:PQ" value="1" unit="1"/>
                         </epsos:quantity>
                         <epsos:ingredient classCode="MMAT" determinerCode="KIND">
                            <!-- ATC-code-->
                            <epsos:code code="A10BD03" codeSystem="2.16.840.1.113883.6.73" displayName="Metformin and rosiglitazone"/>
                            <epsos:name>Metformin and rosiglitazone</epsos:name>
                         </epsos:ingredient>
                      </epsos:ingredient>
                   </manufacturedMaterial>
                </manufacturedProduct>
             </product>
 * 
 * 
 * 
 * 
 * 
 * @param dom
 * @param node
 * @param doctor
 */
private void addProductTag(Document dom, Node node, ViewResult dispensedLine, Node prescriptionNode) {
    Node productNode = dom.createElement("product");
    Node product = dom.createElement("manufacturedProduct");
    addAttribute(dom, product, "xmlns:epsos", XML_DISPENSATION_PRODUCT_EPSOSNS);
    addAttribute(dom, product, "classCode", XML_DISPENSATION_PRODUCT_CLASSCODE);
    addTemplateId(dom, product, XML_DISPENSATION_PRODUCT_TEMPLATE1);
    addTemplateId(dom, product, XML_DISPENSATION_PRODUCT_TEMPLATE2);

    // change after September 29/30-2010 workshop: product tag must be the same as the one in prescription.
    // only changes allowed (if substituting) are the brand name and the package quantity tags
    Node materialNode = null;
    // use identical material info from prescription
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression materialExpr = xpath
                .compile("substanceAdministration/consumable/manufacturedProduct/manufacturedMaterial");
        Node oldMaterialNode = (Node) materialExpr.evaluate(prescriptionNode, XPathConstants.NODE);

        // fix to add epsos:id node

        XPathExpression code = xpath
                .compile("substanceAdministration/consumable/manufacturedProduct/manufacturedMaterial/code");
        Node codeNode = (Node) code.evaluate(prescriptionNode, XPathConstants.NODE);

        if (codeNode == null) {
            code = xpath.compile(
                    "substanceAdministration/consumable/manufacturedProduct/manufacturedMaterial/name");
            codeNode = (Node) code.evaluate(prescriptionNode, XPathConstants.NODE);
        }

        Node epsosID = dom.createElement("epsos:id");
        addAttribute(dom, epsosID, "root", XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE3);
        addAttribute(dom, epsosID, "extension", (String) dispensedLine.getField1());
        oldMaterialNode.insertBefore(epsosID, codeNode);

        materialNode = oldMaterialNode.cloneNode(true);

        if (dispensedLine.getField3() != null && ((Boolean) dispensedLine.getField3()).booleanValue()) {
            // substitute case, change brand name and quantity tags
            XPathExpression brandNameExpr = xpath.compile("name");
            Node nameNode = (Node) brandNameExpr.evaluate(materialNode, XPathConstants.NODE);
            nameNode.setTextContent((String) dispensedLine.getField2());

            XPathExpression packContentExpr = xpath.compile("asContent");
            Node contentNode = (Node) packContentExpr.evaluate(materialNode, XPathConstants.NODE);
            XPathExpression packQuantityExpr = xpath.compile("containerPackagedMedicine/capacityQuantity");
            Node oldQuant = (Node) packQuantityExpr.evaluate(contentNode, XPathConstants.NODE);
            NamedNodeMap attributes = oldQuant.getAttributes();
            Node unitNode = node.getOwnerDocument().createAttribute("unit");
            unitNode.setNodeValue((String) dispensedLine.getField12());
            attributes.setNamedItem(unitNode);
            Node attNode = node.getOwnerDocument().createAttribute("value");
            attNode.setNodeValue((String) dispensedLine.getField7());
            attributes.setNamedItem(attNode);

            //            Node quant = createEpsosCapacityQuantityNode(dom, (String)dispensedLine.getField7(),(String)dispensedLine.getField12());
            //            if (contentNode != null && oldQuant != null)
            //               contentNode.replaceChild(quant, oldQuant);
        }
    } catch (Exception e) {
        _log.error("error using identical material info from prescription");

    }
    product.appendChild(materialNode);
    productNode.appendChild(product);
    node.appendChild(productNode);
}

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

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

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

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

    return result;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:net.ymate.framework.commons.XPathHelper.java

public Node getNode(String expression) throws XPathExpressionException {
    return (Node) __doEvaluate(expression, null, XPathConstants.NODE);
}

From source file:net.ymate.framework.commons.XPathHelper.java

public Node getNode(Object item, String expression) throws XPathExpressionException {
    return (Node) __doEvaluate(expression, item, XPathConstants.NODE);
}

From source file:nl.b3p.imagetool.CombineArcIMSUrl.java

/**
 * Create a new CombineImageUrl with the given values
 * In this implementation the body is changed.
 * @param width width//  www  .j  av  a 2s .  c  o  m
 * @param height height
 * @param bbox bbox
 * @return new clone of this CombineImageUrl but with changed values.
 * @see CombineImageUrl#calculateNewUrl(java.lang.Integer, java.lang.Integer, nl.b3p.viewer.image.Bbox) 
 */
@Override
public List<CombineImageUrl> calculateNewUrl(ImageBbox bbox) {
    Integer width = bbox.getWidth();
    Integer height = bbox.getHeight();
    Bbox bb = bbox.getBbox();
    CombineArcIMSUrl ciu = new CombineArcIMSUrl(this);
    try {
        Document doc = bodyAsDocument();
        Node root = doc.getFirstChild();
        //change the bbox
        Node envelope = (Node) xPathEnvelope.evaluate(root, XPathConstants.NODE);
        NamedNodeMap nnm = envelope.getAttributes();
        nnm.getNamedItem("minx").setNodeValue("" + bb.getMinx());
        nnm.getNamedItem("maxx").setNodeValue("" + bb.getMaxx());
        nnm.getNamedItem("miny").setNodeValue("" + bb.getMiny());
        nnm.getNamedItem("maxy").setNodeValue("" + bb.getMaxy());
        //
        Node imageSize = (Node) xPathImageSize.evaluate(root, XPathConstants.NODE);
        nnm = imageSize.getAttributes();
        nnm.getNamedItem("width").setNodeValue(width.toString());
        nnm.getNamedItem("height").setNodeValue(height.toString());

        ciu.setBody(doc);
    } catch (Exception e) {
        log.warn("Error while changing body fragment", e);
    }
    List<CombineImageUrl> list = new ArrayList<CombineImageUrl>();
    list.add(ciu);
    return list;
}

From source file:nl.b3p.imagetool.CombineArcServerUrl.java

/**
 * Create a new CombineImageUrl with the given values
 * In this implementation the body is changed.
 * @param width width//from  ww w .  ja va2 s.  co m
 * @param height height
 * @param bbox bbox
 * @return new clone of this CombineImageUrl but with changed values.
 * @see CombineImageUrl#calculateNewUrl(java.lang.Integer, java.lang.Integer, nl.b3p.viewer.image.Bbox) 
 */
@Override
public List<CombineImageUrl> calculateNewUrl(ImageBbox imbbox) {
    Integer width = imbbox.getWidth();
    Integer height = imbbox.getHeight();
    Bbox bbox = imbbox.getBbox();

    CombineArcServerUrl ciu = new CombineArcServerUrl(this);
    try {
        Document doc = bodyAsDocument();
        Node root = doc.getFirstChild();
        //change the bbox
        Node extent = (Node) xPathExtent.evaluate(root, XPathConstants.NODE);
        NodeList nl = extent.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node child = nl.item(i);
            if ("XMin".equals(child.getLocalName())) {
                child.setTextContent("" + bbox.getMinx());
            } else if ("YMin".equals(child.getLocalName())) {
                child.setTextContent("" + bbox.getMiny());
            } else if ("XMax".equals(child.getLocalName())) {
                child.setTextContent("" + bbox.getMaxx());
            } else if ("YMax".equals(child.getLocalName())) {
                child.setTextContent("" + bbox.getMaxy());
            }
        }
        //image size
        Node imageSize = (Node) xPathImageDisplay.evaluate(root, XPathConstants.NODE);
        nl = imageSize.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node child = nl.item(i);
            if ("ImageHeight".equals(child.getLocalName())) {
                child.setTextContent(height.toString());
            } else if ("ImageWidth".equals(child.getLocalName())) {
                child.setTextContent(width.toString());
            }
        }
        ciu.setBody(doc);
    } catch (Exception e) {
        log.warn("Error while changing body fragment", e);
    }

    List<CombineImageUrl> list = new ArrayList<CombineImageUrl>();
    list.add(ciu);
    return list;
}

From source file:nl.b3p.ogc.sld.SldNamedStyle.java

public void setName(String name) throws XPathExpressionException {
    Node n = (Node) xpath_name.evaluate(node, XPathConstants.NODE);
    n.setNodeValue(name);//from  w  w w .  java2 s.c o m
}

From source file:nl.clockwork.mule.ebms.cxf.EbMSSecSignatureInInterceptor.java

private X509Certificate getCertificate(Document document) {
    try {/*from   ww w .  j  a  va2 s.  c  o m*/
        Node n = (Node) XMLUtils.executeXPathQuery(new EbXMLNamespaceContext(), document,
                "/soap:Envelope/soap:Header/ebxml:MessageHeader", XPathConstants.NODE);
        MessageHeader messageHeader = XMLMessageBuilder.getInstance(MessageHeader.class).handle(n);
        CollaborationProtocolAgreement cpa = ebMSDAO.getCPA(messageHeader.getCPAId());
        if (cpa != null) {
            PartyInfo partyInfo = CPAUtils.getPartyInfo(cpa, messageHeader.getFrom().getPartyId());
            if (partyInfo != null) {
                List<DeliveryChannel> channels = CPAUtils.getDeliveryChannels(partyInfo,
                        messageHeader.getFrom().getRole(), messageHeader.getService(),
                        messageHeader.getAction());
                if (channels.size() == 1) {
                    nl.clockwork.mule.ebms.model.cpp.cpa.Certificate c = CPAUtils
                            .getCertificate(channels.get(0));
                    if (c == null)
                        return null;
                    else
                        return CPAUtils.getX509Certificate(c);
                }
            }
        }
        return null;
    } catch (Exception e) {
        logger.warn("", e);
        return null;
    }
}

From source file:no.trank.openpipe.solr.step.SolrDocumentProcessor.java

private void loadIndexSchema(URL url)
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
    solrFields.clear();/*from   www  . j a  va2s.c  o  m*/
    solrDynamicFields.clear();

    InputStream sIn;
    if (url.getProtocol().equals("file")) {
        sIn = url.openStream();
    } else {
        GetMethod get = new GetMethod(url.toExternalForm());
        httpClient.executeMethod(get);
        sIn = get.getResponseBodyAsStream();
    }
    final InputStream in = new XmlInputStream(sIn);
    try {

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(in);

        final XPath xpath = XPathFactory.newInstance().newXPath();
        final NodeList nodes = (NodeList) xpath.evaluate("/schema/fields/field | /schema/fields/dynamicField",
                document, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            final Node node = nodes.item(i);
            final String name = ((Element) node).getAttribute("name");
            final String nodeName = node.getNodeName();
            if ("field".equals(nodeName)) {
                addField(name);
            } else if ("dynamicField".equals(nodeName)) {
                addDynamicField(name);
            }
        }

        if (idFieldName == null) {
            Node idNode = (Node) xpath.evaluate("/schema/uniqueKey", document, XPathConstants.NODE);
            idFieldName = idNode.getTextContent().trim();
        }

    } finally {
        try {
            in.close();
        } catch (Exception e) {
            // Do nothing
        }
    }
}