Example usage for javax.xml.xpath XPathConstants BOOLEAN

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

Introduction

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

Prototype

QName BOOLEAN

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

Click Source Link

Document

The XPath 1.0 boolean data type.

Maps to Java Boolean .

Usage

From source file:Main.java

/**
 * <p>/*  www . jav  a2s .  com*/
 * Evaluates the given XPath expression in the context of the given item, with
 * the expectation of a boolean result.
 * </p>
 * 
 * @param xpe
 *          An XPath expression.
 * @param item
 *          A context item.
 * @return The result of the evaluation as a {@link Boolean} instance.
 * @throws XPathExpressionException
 *           if the evaluation fails
 * @since 1.67.5
 * @see XPathConstants#BOOLEAN
 */
public static Boolean evaluateBoolean(XPathExpression xpe, Object item) throws XPathExpressionException {
    return (Boolean) xpe.evaluate(item, XPathConstants.BOOLEAN);
}

From source file:Main.java

public static Boolean getBoolean(String xPathExpression, Node node) throws XPathExpressionException {
    return (Boolean) xPath.evaluate(xPathExpression, node, XPathConstants.BOOLEAN);
}

From source file:Main.java

/** Evaluates an XPath returning null if not found. <br>
 *  <br>// ww  w  .  j a v  a 2s  .c o m
 *  This is intended for use with pre-defined XPaths stored as constants,
 *  where runtime exceptions should not be possible.
 *  @param expression The XPath expression to evaluate.
 *  @param item       The {@link Node} or other item to evaluate the XPath on.
 *  @param type       The type to return, this must be one of the following:
 *                    {@link String}, {@link CharSequence}, {@link Boolean},
 *                    {@link Node}, {@link NodeList}, {@link Double}, or
 *                    {@link Number}.
 *  @throws AssertionError If the nested call to <tt>XPath.newInstance(path)</tt>
 *                         throws an {@link XPathExpressionException}.
 */
public static <T> T evalXPath(String expression, Object item, Class<T> type) {
    Object val;

    if (type == String.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == CharSequence.class)
        val = evalXPath(expression, item, XPathConstants.STRING);
    else if (type == Boolean.class)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Boolean.TYPE)
        val = evalXPath(expression, item, XPathConstants.BOOLEAN);
    else if (type == Node.class)
        val = evalXPath(expression, item, XPathConstants.NODE);
    else if (type == NodeList.class)
        val = evalXPath(expression, item, XPathConstants.NODESET);
    else if (type == Double.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Double.TYPE)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else if (type == Number.class)
        val = evalXPath(expression, item, XPathConstants.NUMBER);
    else
        throw new IllegalArgumentException("Invalid type given " + type);

    return type.cast(val);
}

From source file:com.predic8.membrane.core.interceptor.cbr.XPathCBRInterceptor.java

private Case findRoute(Request request) throws Exception {
    for (Case r : cases) {
        //TODO getBodyAsStream creates ByteArray each call. That could be a performance issue. Using BufferedInputStream did't work, because stream got closed.
        InputSource is = new InputSource(request.getBodyAsStreamDecoded());
        is.setEncoding(request.getCharset());
        if ((Boolean) newXPath(namespaces).evaluate(r.getxPath(), is, XPathConstants.BOOLEAN))
            return r;
        log.debug("no match found for xpath {" + r.getxPath() + "}");
    }/*from www  . ja va 2s.  c om*/
    return null;
}

From source file:com.espertech.esperio.representation.axiom.AxiomXPathPropertyGetter.java

public Object get(EventBean eventBean) throws PropertyAccessException {
    Object und = eventBean.getUnderlying();
    if (und == null) {
        throw new PropertyAccessException(
                "Unexpected null underlying event encountered, expecting org.w3c.dom.Node instance as underlying");
    }//from  w  ww  .  java  2s .com
    if (!(und instanceof OMNode)) {
        throw new PropertyAccessException("Unexpected underlying event of type '" + und.getClass()
                + "' encountered, expecting org.w3c.dom.Node as underlying");
    }
    try {
        // if there is no parser, return xpath expression type
        if (optionalCastToType == null) {
            if (resultType.equals(XPathConstants.BOOLEAN)) {
                return expression.booleanValueOf(und);
            } else if (resultType.equals(XPathConstants.NUMBER)) {
                Number n = expression.numberValueOf(und);
                return n.doubleValue();
            } else {
                String result = expression.stringValueOf(und);
                return result;
            }
        }

        // obtain result as string and parse
        String result = expression.stringValueOf(und);
        if (result == null) {
            return null;
        }

        try {
            return simpleTypeParser.parse(result.toString());
        } catch (RuntimeException ex) {
            log.warn("Error parsing XPath property named '" + property + "' expression result '" + result
                    + " as type " + optionalCastToType.getName());
            return null;
        }
    } catch (JaxenException e) {
        throw new PropertyAccessException("Error getting property '" + property + "' : " + e.getMessage(), e);
    }
}

From source file:org.opencastproject.remotetest.util.Utils.java

public static Boolean xpathExists(Document document, String path) throws Exception {
    return (Boolean) xpath(document, path, XPathConstants.BOOLEAN);
}

From source file:org.codice.ddf.admin.sources.opensearch.OpenSearchSourceUtils.java

public UrlAvailability getUrlAvailability(String url, String un, String pw) {
    UrlAvailability result = new UrlAvailability(url);
    boolean queryResponse;
    int status;/*from w w w .  j av a 2s  .c o  m*/
    String contentType;
    HttpGet request = new HttpGet(url + SIMPLE_QUERY_PARAMS);
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;

    if (url.startsWith("https") && un != null && pw != null) {
        byte[] auth = Base64.encodeBase64((un + ":" + pw).getBytes());
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    try {
        client = getCloseableHttpClient(false);
        response = client.execute(request);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document responseXml = builder.parse(response.getEntity().getContent());
        queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                XPathConstants.BOOLEAN);
        status = response.getStatusLine().getStatusCode();
        contentType = response.getEntity().getContentType().getValue();
        if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
            return result.trustedCertAuthority(true).certError(false).available(true);
        } else {
            return result.trustedCertAuthority(true).certError(false).available(false);
        }
    } catch (SSLPeerUnverifiedException e) {
        // This is the hostname != cert name case - if this occurs, the URL's SSL cert configuration
        // is incorrect, or a serious network security issue has occurred.
        return result.trustedCertAuthority(false).certError(true).available(false);
    } catch (Exception e) {
        try {
            closeClientAndResponse(client, response);
            client = getCloseableHttpClient(true);
            response = client.execute(request);
            status = response.getStatusLine().getStatusCode();
            contentType = response.getEntity().getContentType().getValue();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document responseXml = builder.parse(response.getEntity().getContent());
            queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                    XPathConstants.BOOLEAN);
            if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
                return result.trustedCertAuthority(false).certError(false).available(true);
            }
        } catch (Exception e1) {
            return result.trustedCertAuthority(false).certError(false).available(false);
        }
    } finally {
        closeClientAndResponse(client, response);
    }
    return result;
}

From source file:com.espertech.esperio.representation.axiom.AxiomXPathPropertyGetter.java

public Class getResultClass() {
    if (resultType.equals(XPathConstants.BOOLEAN)) {
        return Boolean.class;
    }//w ww.  j a v  a  2  s.com
    if (resultType.equals(XPathConstants.NUMBER)) {
        return Double.class;
    }
    if (resultType.equals(XPathConstants.STRING)) {
        return String.class;
    }

    return String.class;
}

From source file:com.espertech.esper.regression.event.TestNoSchemaXMLEvent.java

public void testSimpleXMLXPathProperties() throws Exception {
    Configuration configuration = SupportConfigFactory.getConfiguration();

    ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName("myevent");
    xmlDOMEventTypeDesc.addXPathProperty("xpathElement1", "/myevent/element1", XPathConstants.STRING);
    xmlDOMEventTypeDesc.addXPathProperty("xpathCountE21", "count(/myevent/element2/element21)",
            XPathConstants.NUMBER);
    xmlDOMEventTypeDesc.addXPathProperty("xpathAttrString", "/myevent/element3/@attrString",
            XPathConstants.STRING);
    xmlDOMEventTypeDesc.addXPathProperty("xpathAttrNum", "/myevent/element3/@attrNum", XPathConstants.NUMBER);
    xmlDOMEventTypeDesc.addXPathProperty("xpathAttrBool", "/myevent/element3/@attrBool",
            XPathConstants.BOOLEAN);
    xmlDOMEventTypeDesc.addXPathProperty("stringCastLong", "/myevent/element3/@attrNum", XPathConstants.STRING,
            "long");
    xmlDOMEventTypeDesc.addXPathProperty("stringCastDouble", "/myevent/element3/@attrNum",
            XPathConstants.STRING, "double");
    xmlDOMEventTypeDesc.addXPathProperty("numCastInt", "/myevent/element3/@attrNum", XPathConstants.NUMBER,
            "int");
    xmlDOMEventTypeDesc.setXPathFunctionResolver(SupportXPathFunctionResolver.class.getName());
    xmlDOMEventTypeDesc.setXPathVariableResolver(SupportXPathVariableResolver.class.getName());
    configuration.addEventType("TestXMLNoSchemaType", xmlDOMEventTypeDesc);

    xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName("my.event2");
    configuration.addEventType("TestXMLWithDots", xmlDOMEventTypeDesc);

    epService = EPServiceProviderManager.getProvider("TestNoSchemaXML", configuration);
    epService.initialize();/*  w  w w.  j a  v  a 2 s. c  o  m*/
    updateListener = new SupportUpdateListener();

    // assert type metadata
    EventTypeSPI type = (EventTypeSPI) ((EPServiceProviderSPI) epService).getEventAdapterService()
            .getExistsTypeByName("TestXMLNoSchemaType");
    assertEquals(EventTypeMetadata.ApplicationType.XML, type.getMetadata().getOptionalApplicationType());
    assertEquals(null, type.getMetadata().getOptionalSecondaryNames());
    assertEquals("TestXMLNoSchemaType", type.getMetadata().getPrimaryName());
    assertEquals("TestXMLNoSchemaType", type.getMetadata().getPublicName());
    assertEquals("TestXMLNoSchemaType", type.getName());
    assertEquals(EventTypeMetadata.TypeClass.APPLICATION, type.getMetadata().getTypeClass());
    assertEquals(true, type.getMetadata().isApplicationConfigured());
    assertEquals(true, type.getMetadata().isApplicationPreConfigured());
    assertEquals(true, type.getMetadata().isApplicationPreConfiguredStatic());

    EPAssertionUtil.assertEqualsAnyOrder(new Object[] {
            new EventPropertyDescriptor("xpathElement1", String.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("xpathCountE21", Double.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("xpathAttrString", String.class, null, false, false, false, false,
                    false),
            new EventPropertyDescriptor("xpathAttrNum", Double.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("xpathAttrBool", Boolean.class, null, false, false, false, false,
                    false),
            new EventPropertyDescriptor("stringCastLong", Long.class, null, false, false, false, false, false),
            new EventPropertyDescriptor("stringCastDouble", Double.class, null, false, false, false, false,
                    false),
            new EventPropertyDescriptor("numCastInt", Integer.class, null, false, false, false, false,
                    false), },
            type.getPropertyDescriptors());

    String stmt = "select xpathElement1, xpathCountE21, xpathAttrString, xpathAttrNum, xpathAttrBool,"
            + "stringCastLong," + "stringCastDouble," + "numCastInt "
            + "from TestXMLNoSchemaType.win:length(100)";

    EPStatement joinView = epService.getEPAdministrator().createEPL(stmt);
    joinView.addListener(updateListener);

    // Generate document with the specified in element1 to confirm we have independent events
    sendEvent("EventA");
    assertDataSimpleXPath("EventA");

    sendEvent("EventB");
    assertDataSimpleXPath("EventB");
}