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:jef.tools.XMLUtils.java

/**
 * XPATH/*from  w  ww  .  java  2  s  .c  o  m*/
 * 
 * @param startPoint
 *            
 * @param expr
 *            xpath?
 * @return xpath
 * @throws XPathExpressionException
 */
public static Node selectNode(Object startPoint, String expr) throws XPathExpressionException {
    XPath xpath = xp.newXPath();
    return (Node) xpath.evaluate(expr, startPoint, XPathConstants.NODE);
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testCreateLargeRecordSet() throws Exception {
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);
    Element entityContainerElement = (Element) xp.evaluate(
            "/merge:EntityMergeRequestMessage/merge:MergeParameters/er-ext:EntityContainer", testRequestMessage,
            XPathConstants.NODE);
    assertNotNull(entityContainerElement);
    Element entityElement = (Element) xp.evaluate("er-ext:Entity[1]", entityContainerElement,
            XPathConstants.NODE);
    assertNotNull(entityElement);// ww  w . j av a  2  s . co m
    int entityCount = ((NodeList) xp.evaluate("er-ext:Entity", entityContainerElement, XPathConstants.NODESET))
            .getLength();
    int expectedInitialEntityCount = 6;
    assertEquals(expectedInitialEntityCount, entityCount);
    int recordIncrement = 500;
    for (int i = 0; i < recordIncrement; i++) {
        Element newEntityElement = (Element) entityElement.cloneNode(true);
        entityContainerElement.appendChild(newEntityElement);
    }
    entityCount = ((NodeList) xp.evaluate("er-ext:Entity", entityContainerElement, XPathConstants.NODESET))
            .getLength();
    assertEquals(expectedInitialEntityCount + recordIncrement, entityCount);

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);
    assertNotNull(entityContainerNode);

    NodeList entityNodeList = ((Element) entityContainerNode)
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity");
    List<RecordWrapper> records = entityResolutionMessageHandler.createRecordsFromRequestMessage(entityNodeList,
            null);
    assertEquals(expectedInitialEntityCount + recordIncrement, records.size());
}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

static public String getIndexBasedXPathForGeneralXPath(String xpathString, String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {//  w ww  . j  a va  2s .  co  m
        factory.setNamespaceAware(false); // ignore the horrible issues of namespacing
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Node root = doc.getFirstChild();
        XPathExpression expr = xpath.compile(xpathString);
        Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        return nodeToSimpleXPath(node, root);
    } catch (SAXException ex) {
    } catch (IOException ex) {
    } catch (XPathExpressionException ex) {
    } catch (ParserConfigurationException ex) {
    }
    return null;
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void updateFileElementsInPlace(Document targetDocument, Document updateDocument,
        List<FileUpdateOperation> fileUpdateOperations, Element targetRoot, Element updateRoot,
        List<String> purgeDatastreamList) throws XPathExpressionException, FedoraClientException, IOException {
    List<Node> targetFileNodes = getChildNodesByName(targetRoot, "File");
    List<Node> updateFileNodes = getChildNodesByName(updateRoot, "File");
    for (Node targetNode : targetFileNodes) {
        Node idAttr = targetNode.getAttributes().getNamedItem("id");
        if (idAttr != null) {
            String idAttrValue = idAttr.getTextContent();
            if (!idAttrValue.isEmpty() && !((Boolean) xPath.evaluate("//File[@id='" + idAttrValue + "']",
                    updateDocument, XPathConstants.BOOLEAN))) {
                purgeDatastreamList.add(DSID_QUCOSA_ATT.concat(idAttrValue));
            }/*from w ww  .j  a v a2s .c  o  m*/
        }
    }
    for (Node updateNode : updateFileNodes) {
        Node idAttr = updateNode.getAttributes().getNamedItem("id");
        if (idAttr == null) {
            targetDocument.adoptNode(updateNode);
            targetRoot.appendChild(updateNode);
        } else {
            String idAttrValue = idAttr.getTextContent();
            Node targetNode = (Node) xPath.evaluate("//File[@id='" + idAttrValue + "']", targetDocument,
                    XPathConstants.NODE);
            FileUpdateOperation fupo = updateFileNodeWith((Element) targetNode, (Element) updateNode);
            fupo.setDsid(DSID_QUCOSA_ATT.concat(idAttrValue));
            fileUpdateOperations.add(fupo);
        }
    }
}

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

private Node getAgent(IMetsElement metsElement) throws MetsExportException {
    AgentComplexType agent = new AgentComplexType();
    ObjectFactory factory = new ObjectFactory();
    JAXBElement<AgentComplexType> jaxbPremix = factory.createAgent(agent);
    AgentIdentifierComplexType agentIdentifier = new AgentIdentifierComplexType();
    agent.getAgentIdentifier().add(agentIdentifier);
    agentIdentifier.setAgentIdentifierType("ProArc_AgentID");
    agentIdentifier.setAgentIdentifierValue("ProArc");
    agent.setAgentType("software");
    agent.getAgentName().add("ProArc");

    JAXBContext jc;/*from  w w  w .  j  a  v a 2s. c o  m*/
    try {
        jc = JAXBContext.newInstance(AgentComplexType.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 agentNode = (Node) xpath.compile("*[local-name()='agent']").evaluate(document,
                XPathConstants.NODE);
        return agentNode;
    } catch (Exception e) {
        throw new MetsExportException(metsElement.getOriginalPid(), "Error while generating premis data", false,
                e);
    }

}

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

@Override
public String getElementByPathById(String path, final String originalXml, String elementId)
        throws XPathExpressionException, SAXException, IOException {

    Assert.hasText(path);//w  ww  . jav a  2 s.c o m
    Assert.hasText(originalXml);
    Assert.hasText(elementId);

    Document originalDom = parse(originalXml);

    path = path + "[@id='" + elementId + "']";

    XPath xPath = getXPathInstance();

    Element element = (Element) (xPath.evaluate(path, originalDom, XPathConstants.NODE));
    Assert.notNull(element);

    return DomUtils.elementToString(element);
}

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) throws Exception {
    logger.debug("----Inside getObjects, query: " + query + " & select: " + select);

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

        ScribeCommandObject returnObject = null;

        try {/*www .ja  v a2 s  . c  o m*/
            /* Query CRM object by Phone field */
            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Phone");

        } catch (final ScribeException firstE) {

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

                try {
                    /* Query CRM object by Mobile field */
                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Mobile");
                } 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, null,
                                    "Home Phone");
                        } catch (final ScribeException thirdE) {

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

                                try {
                                    /* Query CRM object by Other Phone field */
                                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select,
                                            null, "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");
            }

            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:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java

private Node getPremisEvent(IMetsElement metsElement, String datastream, FileMD5Info md5Info,
        String eventDetail) throws MetsExportException {
    PremisComplexType premis = new PremisComplexType();
    ObjectFactory factory = new ObjectFactory();
    JAXBElement<PremisComplexType> jaxbPremix = factory.createPremis(premis);
    EventComplexType event = factory.createEventComplexType();
    premis.getEvent().add(event);//  w  w w . j a v a  2  s  .c o  m
    event.setEventDateTime(md5Info.getCreated().toXMLFormat());
    event.setEventDetail(eventDetail);
    EventIdentifierComplexType eventIdentifier = new EventIdentifierComplexType();
    event.setEventIdentifier(eventIdentifier);
    event.setEventType("derivation");
    eventIdentifier.setEventIdentifierType("ProArc_EventID");
    eventIdentifier.setEventIdentifierValue(Const.dataStreamToEvent.get(datastream));
    EventOutcomeInformationComplexType eventInformation = new EventOutcomeInformationComplexType();
    event.getEventOutcomeInformation().add(eventInformation);
    eventInformation.getContent().add(factory.createEventOutcome("successful"));
    LinkingAgentIdentifierComplexType linkingAgentIdentifier = new LinkingAgentIdentifierComplexType();
    linkingAgentIdentifier.setLinkingAgentIdentifierType("ProArc_AgentID");
    linkingAgentIdentifier.setLinkingAgentIdentifierValue("ProArc");
    linkingAgentIdentifier.getLinkingAgentRole().add("software");
    LinkingObjectIdentifierComplexType linkingObject = new LinkingObjectIdentifierComplexType();
    linkingObject.setLinkingObjectIdentifierType("ProArc_URI");
    linkingObject.setLinkingObjectIdentifierValue(
            Const.FEDORAPREFIX + metsElement.getOriginalPid() + "/" + Const.dataStreamToModel.get(datastream));
    event.getLinkingObjectIdentifier().add(linkingObject);
    event.getLinkingAgentIdentifier().add(linkingAgentIdentifier);
    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()='event']")
                .evaluate(document, XPathConstants.NODE);
        return premisNode;
    } catch (Exception e) {
        throw new MetsExportException(metsElement.getOriginalPid(), "Error while generating premis data", false,
                e);
    }
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void assertXPathNodeExists(String xpath, String msg, Document doc)
        throws XPathExpressionException, BadQucosaDocumentException {
    if (xPath.evaluate(xpath, doc, XPathConstants.NODE) == null) {
        throw new BadQucosaDocumentException(msg, doc);
    }//  w w  w .  j  a  va 2s  .  c  o m
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Return the child of the node selected by the xPath.
 * //from   www  .  ja  v  a  2s  .  com
 * @param node The node.
 * @param xpathExpression The XPath expression as string
 * 
 * @return The child of the node selected by the xPath
 * 
 * @throws TransformerException If anything fails.
 */
public static Node selectSingleNode(final Node node, final String xpathExpression) throws TransformerException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        return (Node) xPath.evaluate(xpathExpression, node, XPathConstants.NODE);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}