Example usage for javax.xml.xpath XPathConstants NODESET

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

Introduction

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

Prototype

QName NODESET

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

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceXmlTests.java

@Test
public void CoreResourceHasAtMostOneIdentifier() throws XPathExpressionException {
    String eval = "//" + getNode() + "/" + "dc:identifier";

    NodeList ids = (NodeList) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), ids.getLength() <= 1);
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java

@Test
public void changeRequestHasAtMostOneDescription() throws XPathExpressionException {
    NodeList descriptions = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/dc:description", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), descriptions.getLength() <= 1);
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.informationflow.VisioInformationFlowTemplateParser.java

/**
 * Extracts the relevant information from the given {@link Node} into a
 * {@link VisioInformationFlowTemplateNode} and adds this to the given
 * nodes map. Child nodes will be recursively added to the map, too, and the
 * parent/child references of affected {@link VisioInformationFlowTemplateNode}
 * updated./* w w w  .ja  va 2s  .co m*/
 * @param node
 *          {@link Node} to parse.
 * @param parentNode
 *          The, already parsed, parent of the node to be parsed here. Can be null for the root node.
 */
private void parseNodeAndAddToMap(Node node, VisioInformationFlowTemplateNode parentNode)
        throws XPathExpressionException {

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

    String idString = (String) xPath.evaluate(ID_PROPERTY_XPATH, node, XPathConstants.STRING);
    Integer id = Integer.valueOf(idString);
    String pinXString = (String) xPath.evaluate(PINX_XPATH, node, XPathConstants.STRING);
    double pinX = Double.parseDouble(pinXString);
    String pinYString = (String) xPath.evaluate(PINY_XPATH, node, XPathConstants.STRING);
    double pinY = Double.parseDouble(pinYString);

    VisioInformationFlowTemplateNode parsedNode = new VisioInformationFlowTemplateNode(id, pinX, pinY);
    parsedNodes.put(id, parsedNode);

    if (parentNode != null) {
        parsedNode.setParentId(parentNode.getId());
        parentNode.addChildrenId(id);
    }

    NodeList childApplicationNodes = (NodeList) xPath.evaluate(APPLICATION_SHAPE_XPATH, node,
            XPathConstants.NODESET);

    for (int i = 0; i < childApplicationNodes.getLength(); i++) {
        parseNodeAndAddToMap(childApplicationNodes.item(i), parsedNode);
    }
}

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

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

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

    PostMethod postMethod = null;/*from   w  w  w .  j a  v a  2s .  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/getRecords";

        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");

        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:de.bayern.gdi.processor.AtomDownloadJob.java

@Override
protected void download() throws JobExecutionException {
    Document ds = getDocument(figureoutDatasource());
    HashMap<String, String> vars = new HashMap<>();
    vars.put("VARIATION", this.variation);
    NodeList nl = (NodeList) XML.xpath(ds, XPATH_LINKS, XPathConstants.NODESET, NAMESPACE_CONTEXT, vars);

    ArrayList<DLFile> files = new ArrayList<>(nl.getLength());

    String format = "%0" + places(nl.getLength()) + "d.%s";
    for (int i = 0, j = 0, n = nl.getLength(); i < n; i++) {
        Element link = (Element) nl.item(i);
        String href = link.getAttribute("href");
        if (href.isEmpty()) {
            continue;
        }/*from w w  w  .j a  v  a2  s.co  m*/
        URL dataURL = toURL(href);
        String fileName;
        // Service call?
        if (dataURL.getQuery() != null) {
            String type = link.getAttribute("type");
            String ext = mimetypeToExt(type);
            fileName = String.format(format, j, ext);
            j++;
        } else { // Direct download.
            // XXX: Do more to prevent directory traversals?
            fileName = new File(dataURL.getPath()).getName().replaceAll("\\.+", ".");

            if (fileName.isEmpty()) {
                String type = link.getAttribute("type");
                String ext = mimetypeToExt(type);
                fileName = String.format(format, j, ext);
                j++;
            }
        }
        File file = new File(this.workingDir, fileName);
        files.add(new DLFile(file, dataURL));
    }

    int failed = 0;
    int numFiles = files.size();

    for (;;) {
        for (int i = 0; i < files.size();) {
            DLFile file = files.get(i);
            if (downloadFile(file)) {
                files.remove(i);
            } else {
                if (++file.tries < MAX_TRIES) {
                    i++;
                } else {
                    failed++;
                    files.remove(i);
                }
            }
            broadcastMessage(
                    I18n.format("atom.downloaded.files", numFiles - failed - files.size(), files.size()));
        }
        if (files.isEmpty()) {
            break;
        }
        try {
            Thread.sleep(FAIL_SLEEP);
        } catch (InterruptedException ie) {
            break;
        }
    }

    log.log(Level.INFO, "Bytes downloaded: " + this.totalCount);

    if (failed > 0) {
        throw new JobExecutionException(I18n.format("atom.downloaded.failed", numFiles - failed, failed));
    }

    broadcastMessage(I18n.format("atom.downloaded.success", numFiles));
}

From source file:org.eclipse.lyo.testsuite.oslcv2.ServiceProviderCatalogXmlTests.java

@Test
public void serviceProviderCatalogsHaveAtMostOneTitle() throws XPathException {
    // Check root to make sure it has at most one title.
    NodeList rootChildren = (NodeList) OSLCUtils.getXPath()
            .evaluate("/rdf:RDF/oslc_v2:ServiceProviderCatalog/*", doc, XPathConstants.NODESET);
    int numTitles = 0;/*from  ww  w.  ja  v a 2  s  .co  m*/
    for (int i = 0; i < rootChildren.getLength(); i++) {
        if (rootChildren.item(i).getNamespaceURI().equals(OSLCConstants.DC)
                && rootChildren.item(i).getLocalName().equals("title")) {
            numTitles++;
        }
    }
    assert (numTitles <= 1);

    // Get all service provider catalogs listed
    NodeList nestedSPCs = (NodeList) OSLCUtils.getXPath().evaluate("/*/*//oslc_v2:serviceProviderCatalog", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nestedSPCs.getLength(); i++) {
        NodeList spcChildren = (NodeList) OSLCUtils.getXPath()
                .evaluate("/*/*//oslc_v2:serviceProviderCatalog[" + i + "]/*/*", doc, XPathConstants.NODESET);
        int titleCount = 0;
        // Go through the service provider catalog's children, make sure it
        // contains at most one title.
        for (int j = 0; j < spcChildren.getLength(); j++) {
            if (spcChildren.item(j).getNamespaceURI().equals(OSLCConstants.DC)
                    && spcChildren.item(j).getLocalName().equals("title")) {
                titleCount++;
            }
        }
        assert (titleCount <= 1);
    }
}

From source file:org.eclipse.lyo.testsuite.oslcv2.ServiceProviderXmlTests.java

@Test
public void serviceProviderHasAtMostOneTitle() throws XPathException {
    //Verify that the ServiceProvider has at most one dc:title child element
    NodeList providerChildren = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_v2:ServiceProvider/*", doc,
            XPathConstants.NODESET);

    int numTitles = 0;
    for (int i = 0; i < providerChildren.getLength(); i++) {
        Node child = providerChildren.item(i);
        if (child.getLocalName() != null && child.getLocalName().equals("title")
                && child.getNamespaceURI().equals(OSLCConstants.DC)) {
            numTitles++;// w w  w  .  ja  v a  2s . c  o  m
        }
    }
    assertTrue("Expected number of dcterms:titles to be <=1 but was:" + numTitles, numTitles <= 1);
}

From source file:ru.cti.gosuslugi.service.client.OffenceInfoServiceClient.java

private OffenceInfoForProgrammaticSystems getOffenceInfoList(String response)
        throws IOException, SAXException, ParserConfigurationException, XPathExpressionException,
        TransformerFactoryConfigurationError, TransformerException, JAXBException {
    Document responseDocument = buildXmlDocumentFromString(response);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate("//Body/*", responseDocument, XPathConstants.NODESET);

    StringWriter sw = new StringWriter();

    if (serializer == null)
        serializer = TransformerFactory.newInstance().newTransformer();

    serializer.transform(new DOMSource(nodeList.item(0)), new StreamResult(sw));
    String res = sw.toString();/*from   w ww  .j a v  a 2  s  .c o  m*/

    logger.debug("offence body: {}", res);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    return (OffenceInfoForProgrammaticSystems) unmarshaller
            .unmarshal(new ByteArrayInputStream(res.getBytes("UTF-8")));

}

From source file:eu.eexcess.zbw.recommender.PartnerConnector.java

protected String getValueWithXPath(String xpath, Document orgPartnerResult) {
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes;/* ww w  .j  av  a 2s.c  om*/
    try {
        nodes = (NodeList) xPath.evaluate(xpath, orgPartnerResult.getDocumentElement(), XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength();) {
            Element e = (Element) nodes.item(i);
            return e.getTextContent();
        }
    } catch (XPathExpressionException e1) {
        e1.printStackTrace();
    }
    return "";
}

From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

/**
 * Close the specified stage.//from w w  w.  j  av  a  2 s . c o  m
 * 
 * @param stage the stage to close.
 * @throws StageException if any issue occurred whilst closing the stage.
 */
public void closeStage(Stage stage, String description) throws StageException {
    performStageAction(StageAction.CLOSE, stage, description);
    if (isAsyncClose()) {
        waitForActionToComplete(stage);
        // check the action completed successfully and no rules failed.
        URL url = getActivityURL(stage);
        Document doc = getDocument(url);
        // last stagingActivity that was a close
        String xpathExpr = "(/list/stagingActivity[name='close'])[last()]";
        Node lastCloseNode = (Node) evaluateXPath(xpathExpr, doc, XPathConstants.NODE);
        if (lastCloseNode == null) {
            throw new StageException("Stage activity completed but no close action was recorded!");
        }
        Node closed = (Node) evaluateXPath("events/stagingActivityEvent[name='repositoryClosed']",
                lastCloseNode, XPathConstants.NODE);
        if (closed != null) {
            // we have successfully closed the repository
            return;
        }
        Node failed = (Node) evaluateXPath("events/stagingActivityEvent[name='repositoryCloseFailed']",
                lastCloseNode, XPathConstants.NODE);
        if (failed == null) {
            throw new StageException(
                    "Close stage action was signalled as completed, but was not recorded as either failed or succeeded!");
        }
        StringBuilder failureMessage = new StringBuilder("Closing stage ").append(stage.getStageID())
                .append(" failed.\n");
        String cause = (String) evaluateXPath("properties/stagingProperty[name='cause']/value", failed,
                XPathConstants.STRING);
        failureMessage.append('\t').append(cause);
        NodeList failedRules = (NodeList) evaluateXPath(
                "events/stagingActivityEvent[name='ruleFailed']/properties/stagingProperty[name='failureMessage']/value",
                lastCloseNode, XPathConstants.NODESET);
        for (int i = 0; i < failedRules.getLength(); i++) {
            failureMessage.append("\n\t");
            failureMessage.append(failedRules.item(i).getTextContent());
        }
        throw new StageException(failureMessage.toString());
    }
}