Example usage for javax.xml.xpath XPathExpression evaluate

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Find and delete from the underlying Document any text nodes that
 * contain nothing but whitespace, such as newlines and tab or space
 * characters used to indent or pretty-print an XML document.
 *
 * Uses approach I documented on StackOverflow:
 * http://stackoverflow.com/a/979606/4970
 *
 * @return/*w w  w.  ja v  a  2  s.  c om*/
 * a builder node at the same location as before the operation.
 * @throws XPathExpressionException
 */
public XMLBuilder stripWhitespaceOnlyTextNodes() throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // XPath to find empty text nodes.
    XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(this.getDocument(), XPathConstants.NODESET);

    // Remove each empty text node from document.
    for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
    }
    return this;
}

From source file:com.fluidops.iwb.provider.XMLProvider.java

/**
 * Resolves a parametrized expression against a given context node.
 * A parametrized expression is a string of the form
 * /* w ww  . j a v a  2s .c o  m*/
 *   "Bla bla {XP1} some text {XP2} ... {XPn}",
 * 
 * where XP1 ... XPn are XPath expressions. When evaluating a parametrized
 * expression, the XPath expressions are evaluated against the context 
 * node and their occurences are replaced by the result nodes. The result
 * nodes is a list of strings, representing all permutations of solutions.
 * 
 * As an example, assume the parametrized expression is
 * 
 *   "{./name} - {./friend}"
 *  
 * and [[./name]] = { Pete }, [[./friend]] = { Jane, Joe }, then the result
 * of evaluating the parametrized expression is the list { "Pete - Jane", "Pete - Joe" }.
 * 
 * @param parametrizedExpression
 * @param context
 * @return
 */
protected List<String> resolveParametrizedExpression(String parametrizedExpression, Node context,
        boolean useNodeName, String ignoreIfMatches) {
    Map<String, XPathExpression> map = new HashMap<String, XPathExpression>();

    List<String> result = new ArrayList<String>();
    if (parametrizedExpression == null)
        return result;

    // first collect XPath Expression hidden in ruleExpression
    Map<String, List<String>> xPathExpressions = new HashMap<String, List<String>>();
    Matcher m = PARAMETRIZED_EXPRESSION_PATTERN.matcher(parametrizedExpression);
    while (m.find())
        xPathExpressions.put(m.group(0), new ArrayList<String>());

    XPath xpathDPExp = xpf.newXPath();
    xpathDPExp.setNamespaceContext(ctx);
    for (Entry<String, List<String>> entry : xPathExpressions.entrySet()) {
        String xPathExpression = entry.getKey();
        try {
            XPathExpression xpathExp = map.get(xPathExpression);
            if (xpathExp == null) {
                xpathExp = xpathDPExp.compile(xPathExpression.substring(1, xPathExpression.length() - 1));
                map.put(xPathExpression, xpathExp);
            }

            try {
                NodeList dpNodeList = (NodeList) xpathExp.evaluate(context, XPathConstants.NODESET);

                for (int i = 0; i < dpNodeList.getLength(); i++) {
                    Node dpNode = dpNodeList.item(i);
                    String dpNodeVal = null;
                    if (useNodeName)
                        dpNodeVal = dpNode.getNodeName();
                    else {
                        if (dpNode instanceof Element)
                            dpNodeVal = dpNode.getTextContent();
                        else
                            dpNodeVal = dpNode.getNodeValue();
                    }
                    if (!StringUtil.isNullOrEmpty(dpNodeVal))
                        entry.getValue().add(dpNodeVal);
                }
            } catch (XPathExpressionException isString) {
                String string = (String) xpathExp.evaluate(context, XPathConstants.STRING);
                if (!StringUtil.isNullOrEmpty(string))
                    entry.getValue().add(string);
            }
        } catch (Exception e) {
            logger.warn(e.getMessage());
            return result; // error
        }
    }

    // and compute set of all Literals
    result.add(parametrizedExpression);
    for (Entry<String, List<String>> entry : xPathExpressions.entrySet()) {
        String outerKey = entry.getKey();
        List<String> tempResult = new ArrayList<String>();
        List<String> outer = entry.getValue();
        for (int i = 0; i < outer.size(); i++) {
            for (String res : result) {
                while (res.contains(outerKey))
                    res = res.replace(outerKey, outer.get(i));
                tempResult.add(res);
            }
        }
        result = tempResult;
    }

    if (StringUtil.isNullOrEmpty(ignoreIfMatches))
        return result;

    // else: we filter the result
    List<String> resultFiltered = new ArrayList<String>();
    for (String s : result) {
        if (!s.matches(ignoreIfMatches))
            resultFiltered.add(s);
    }
    return resultFiltered;
}

From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java

private Map<String, String> identifyPreUpdateIdentifiers(String message) {
    Map<String, String> preUpdateIdentifiers = new HashMap<String, String>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//w  ww  .java 2 s .c om
    org.w3c.dom.Document doc = null;
    XPathExpression expr = null;
    XPathExpression exprIdType = null;

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource(new StringReader(message)));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();
        expr = xpath.compile("//preUpdateIdentifiers/preUpdateIdentifier/identifier/text()");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        XPath xpathIdType = xFactory.newXPath();
        exprIdType = xpathIdType.compile(
                "//preUpdateIdentifiers/preUpdateIdentifier/identifierDomain/universalIdentifierTypeCode/text()");
        Object resultIdType = exprIdType.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        NodeList nodesIdType = (NodeList) resultIdType;

        for (int i = 0; i < nodes.getLength(); i++) {
            preUpdateIdentifiers.put(nodesIdType.item(i).getTextContent(), nodes.item(i).getTextContent());
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return preUpdateIdentifiers;
}

From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java

private Map<String, String> identifyPostUpdateIdentifiers(String message) {
    Map<String, String> postUpdateIdentifiers = new HashMap<String, String>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from ww  w  .  j av  a 2  s .co  m
    org.w3c.dom.Document doc = null;
    XPathExpression expr = null;
    XPathExpression exprIdType = null;

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource(new StringReader(message)));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();
        expr = xpath.compile("//postUpdateIdentifiers/postUpdateIdentifier/identifier/text()");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        XPath xpathIdType = xFactory.newXPath();
        exprIdType = xpathIdType.compile(
                "//postUpdateIdentifiers/postUpdateIdentifier/identifierDomain/universalIdentifierTypeCode/text()");
        Object resultIdType = exprIdType.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        NodeList nodesIdType = (NodeList) resultIdType;

        for (int i = 0; i < nodes.getLength(); i++) {
            postUpdateIdentifiers.put(nodesIdType.item(i).getTextContent(), nodes.item(i).getTextContent());
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return postUpdateIdentifiers;
}

From source file:com.dwdesign.tweetings.activity.ComposeActivity.java

private String uploadTwitlonger(String text) {
    String finalUrl = "http://www.twitlonger.com/api_post/";

    final String atext = parseString(mEditText.getText());
    String screen_name = null;// w w w  . ja  va2s.  c om
    if (mAccountIds != null && mAccountIds.length > 0) {
        screen_name = getAccountUsername(this, mAccountIds[0]);
    }

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(finalUrl);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        reqEntity.addPart("username", new StringBody(screen_name));
        reqEntity.addPart("application", new StringBody(TWIT_LONGER_USER));
        reqEntity.addPart("api_key", new StringBody(TWIT_LONGER_API_KEY));
        reqEntity.addPart("message", new StringBody(atext, Charset.forName("UTF-8")));
        postRequest.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(postRequest);

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse(response.getEntity().getContent());

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr;
        expr = xpath.compile("//twitlonger/post/content/text()");

        Object result = expr.evaluate(doc, XPathConstants.STRING);
        Log.d("ComposeActivity.uploadTwitlonger", "path: " + atext + " " + result.toString());

        return result.toString();
    } catch (Exception e) {

        //Toast.makeText(getApplicationContext(), "Network exception" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    return null;
}

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

@Override
public String newElementIdByPath(String path, final String xmlData)
        throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(path);//from  w ww. j a v a 2 s .  c om
    Assert.hasText(xmlData);

    Document finalDom = parse(xmlData);

    XPathExpression xPathExpression = null;

    XPath xPath = getXPathInstance();
    xPathExpression = xPath.compile(path);
    NodeList nodeList = (NodeList) (xPathExpression.evaluate(finalDom, XPathConstants.NODESET));

    int l = nodeList.getLength();

    Element currentElement = null;
    for (int i = 0; i < l; i++) {
        if (nodeList.item(i) == null)
            continue;
        String id = UUID.randomUUID().toString();
        currentElement = (Element) nodeList.item(i);

        currentElement.setAttribute("id", id);
    }

    return DomUtils.elementToString(finalDom.getFirstChild());
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

public void checkPropFindSupportedCalendarComponentSet(Account user, String fullurl, String shorturl,
        String[] compNames) throws Exception {
    PropFindMethod method = new PropFindMethod(fullurl);
    addBasicAuthHeaderForUser(method, user);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    String respBody;//from  www  .j  ava  2s  .  com
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(new ByteArrayRequestEntity(propFindSupportedCalendarComponentSet.getBytes(),
            MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;
    String text;
    NodeList result;
    xPathExpr = xpath.compile("/D:multistatus/D:response/D:href/text()");
    result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
    text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
    assertEquals("HREF", shorturl.replaceAll("@", "%40"), text);
    xPathExpr = xpath.compile("/D:multistatus/D:response/D:propstat/D:status/text()");
    text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
    assertEquals("status", "HTTP/1.1 200 OK", text);
    xPathExpr = xpath
            .compile("/D:multistatus/D:response/D:propstat/D:prop/C:supported-calendar-component-set/C:comp");
    result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
    assertEquals("Number of comp nodes under supported-calendar-component-set", compNames.length,
            result.getLength());
    List<String> names = Arrays.asList(compNames);
    for (int ndx = 0; ndx < result.getLength(); ndx++) {
        org.w3c.dom.Element child = (org.w3c.dom.Element) result.item(ndx);
        String name = child.getAttribute("name");
        assertNotNull("comp should have a 'name' attribute", name);
        assertTrue(String.format("comp 'name' attribute '%s' should be one of the expected names", name),
                names.contains(name));
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

/**
 * http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-proxy.txt
 * This is an Apple standard implemented by Apple Mac OSX at least up to Yosemite and offers a fairly simple
 * sharing model for calendars.  The model is simpler than Zimbra's native model and there are mismatches,
 * for instance Zimbra requires the proposed delegate to accept shares.
 *///from   w w  w . j  a  v a2s . c  o m
@Test
public void testAppleCaldavProxyFunctions() throws ServiceException, IOException {
    Account sharer = users[3].create();
    Account sharee1 = users[1].create();
    Account sharee2 = users[2].create();
    ZMailbox mboxSharer = TestUtil.getZMailbox(sharer.getName());
    ZMailbox mboxSharee1 = TestUtil.getZMailbox(sharee1.getName());
    ZMailbox mboxSharee2 = TestUtil.getZMailbox(sharee2.getName());
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharer, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee1, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee2, true);
    // Test PROPPATCH to "calendar-proxy-read" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyReadUrl(sharer), sharer, sharee2);
    // Test PROPPATCH to "calendar-proxy-write" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyWriteUrl(sharer), sharer, sharee1);

    // verify that adding new members to groups triggered notification messages
    List<ZMessage> msgs = TestUtil.waitForMessages(mboxSharee1,
            "in:inbox subject:\"Share Created: Calendar shared by \"", 1, 10000);
    assertNotNull(String.format("Notification msgs for %s", sharee1.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee1.getName()), 1, msgs.size());

    msgs = TestUtil.waitForMessages(mboxSharee2, "in:inbox subject:\"Share Created: Calendar shared by \"", 1,
            10000);
    assertNotNull(String.format("Notification msgs for %s", sharee2.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee2.getName()), 1, msgs.size());
    // Simulate acceptance of the shares (would normally need to be done in ZWC
    createCalendarMountPoint(mboxSharee1, sharer);
    createCalendarMountPoint(mboxSharee2, sharer);
    Document doc = delegateForExpandProperty(sharee1);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;
    try {
        String xpathS = "/D:multistatus/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        NodeList result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        String text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for account owner", UrlNamespace.getPrincipalUrl(sharee1).replaceAll("@", "%40"),
                text);

        xpathS = "/D:multistatus/D:response/D:propstat/D:prop/CS:calendar-proxy-write-for/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for sharer", UrlNamespace.getPrincipalUrl(sharer).replaceAll("@", "%40"), text);
    } catch (XPathExpressionException e1) {
        ZimbraLog.test.debug("xpath problem", e1);
    }
    // Check that proxy write has sharee1 in it
    doc = groupMemberSetExpandProperty(sharer, sharee1, true);
    // Check that proxy read has sharee2 in it
    doc = groupMemberSetExpandProperty(sharer, sharee2, false);
    String davBaseName = "notAllowed@There";
    String url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            davBaseName);
    HttpMethodExecutor exe = doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_MOVED_TEMPORARILY);
    String location = null;
    for (Header hdr : exe.respHeaders) {
        if ("Location".equals(hdr.getName())) {
            location = hdr.getValue();
        }
    }
    assertNotNull("Location Header not returned when creating", location);
    url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            location.substring(location.lastIndexOf('/') + 1));
    doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_CREATED);
}

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;/*from  www . ja v  a  2 s  .  co  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:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testNameIDUnset() throws Exception {
    new SamlClientBuilder().navigateTo(employee2ServletPage.toString()).processSamlResponse(Binding.POST)
            .build().login().user(bburkeUser).build().processSamlResponse(Binding.POST)
            .transformDocument(responseDoc -> {
                XPathFactory xPathfactory = XPathFactory.newInstance();
                XPath xpath = xPathfactory.newXPath();
                XPathExpression expr = xpath.compile("//*[local-name()='NameID']");

                NodeList nodeList = (NodeList) expr.evaluate(responseDoc, XPathConstants.NODESET);
                Assert.assertThat(nodeList.getLength(), is(1));

                final Node nameIdNode = nodeList.item(0);
                nameIdNode.getParentNode().removeChild(nameIdNode);

                return responseDoc;
            }).build()/*from w  ww  .  j  av a  2s . c o  m*/

            .navigateTo(employee2ServletPage.toString())

            .execute(r -> {
                Assert.assertThat(r, statusCodeIsHC(Response.Status.OK));
                Assert.assertThat(r, bodyHC(allOf(containsString("principal="), not(containsString("500")))));
            });
}