Example usage for javax.xml.xpath XPathConstants STRING

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

Introduction

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

Prototype

QName STRING

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

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:org.mule.module.xml.filters.XPathFilter.java

protected boolean accept(Node node) {
    Object xpathResult;/*from  w  w  w.  j  av a2s.com*/
    boolean accept = false;

    try {
        xpathResult = getXpath().evaluate(pattern, node, XPathConstants.STRING);
    } catch (Exception e) {
        if (logger.isWarnEnabled()) {
            logger.warn(ClassUtils.getSimpleName(getClass())
                    + " filter rejected message because of an error while evaluating the expression: "
                    + e.getMessage(), e);
        }
        return false;
    }

    if (logger.isDebugEnabled()) {
        logger.debug(MessageFormat.format("{0} Expression result = ''{1}'' -  Expected value = ''{2}''",
                ClassUtils.getSimpleName(getClass()), xpathResult, expectedValue));
    }

    // Compare the XPath result with the expected result.
    if (xpathResult != null && !"".equals(xpathResult)) {
        accept = xpathResult.toString().equals(expectedValue);
    } else {
        // A null result was actually expected.
        if ("null".equals(expectedValue)) {
            accept = true;
        }
        // A null result was not expected, something probably went wrong.
        else {
            if (logger.isDebugEnabled()) {
                logger.debug(MessageFormat.format("{0} expression evaluates to null: {1}",
                        ClassUtils.getSimpleName(getClass()), pattern));
            }
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug(
                MessageFormat.format("{0} accept object  : {1}", ClassUtils.getSimpleName(getClass()), accept));
    }

    return accept;
}

From source file:org.mule.module.xml.util.XMLUtils.java

/**
 * Select a single XML String value using an Xpath
 * @param xpath the XPath expression to evaluate
 * @param node the node (or document) to evaluate on
 * @return the result of the evaluation.
 * @throws XPathExpressionException if the XPath expression is malformed and cannot be parsed
 *///  w w  w  .j  a  v  a 2  s. c o m
public static String selectValue(String xpath, Node node) throws XPathExpressionException {
    XPath xp = createXPath(node);
    return (String) xp.evaluate(xpath, node, XPathConstants.STRING);
}

From source file:ORG.oclc.os.SRW.SRWOpenSearchDatabase.java

@Override
public void init(String dbname, String srwHome, String dbHome, String dbPropertiesFileName,
        Properties dbProperties, HttpServletRequest request) throws Exception {
    log.debug("entering SRWOpenSearchDatabase.init, dbname=" + dbname);
    super.initDB(dbname, srwHome, dbHome, dbPropertiesFileName, dbProperties);

    String urlStr = dbProperties.getProperty("SRWOpenSearchDatabase.OpenSearchDescriptionURL");
    author = dbProperties.getProperty("SRWOpenSearchDatabase.author");
    contact = dbProperties.getProperty("SRWOpenSearchDatabase.contact");
    description = dbProperties.getProperty("SRWOpenSearchDatabase.description");
    restrictions = dbProperties.getProperty("SRWOpenSearchDatabase.restrictions");
    title = dbProperties.getProperty("SRWOpenSearchDatabase.title");
    defaultSchemaName = dbProperties.getProperty("SRWOpenSearchDatabase.defaultSchemaName");
    defaultSchemaID = dbProperties.getProperty("SRWOpenSearchDatabase.defaultSchemaID");
    itemsPerPage = Integer.parseInt(dbProperties.getProperty("SRWOpenSearchDatabase.itemsPerPage", "0"));
    URL url = new URL(urlStr);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    StringBuilder sb = new StringBuilder();
    String inputLine;//from   ww w .  j  av  a2  s .co m
    while ((inputLine = in.readLine()) != null)
        sb.append(inputLine).append('\n');
    in.close();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(sb.toString())));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr;
    if (contact == null) {
        expr = xpath.compile("/OpenSearchDescription/Contact");
        contact = (String) expr.evaluate(document, XPathConstants.STRING);
    }
    if (description == null) {
        expr = xpath.compile("/OpenSearchDescription/Description");
        description = (String) expr.evaluate(document, XPathConstants.STRING);
    }
    if (restrictions == null) {
        expr = xpath.compile("/OpenSearchDescription/SyndicationRight");
        restrictions = (String) expr.evaluate(document, XPathConstants.STRING);
        if (restrictions != null)
            restrictions = "SynticationRight=" + restrictions;
        expr = xpath.compile("/OpenSearchDescription/Attribution");
        String attribution = (String) expr.evaluate(document, XPathConstants.STRING);
        if (attribution != null)
            if (restrictions != null)
                restrictions = restrictions + ", Attribution=" + attribution;
            else
                restrictions = "Attribution=" + attribution;
    }
    if (title == null) {
        expr = xpath.compile("/OpenSearchDescription/LongName");
        title = (String) expr.evaluate(document, XPathConstants.STRING);
    }
    expr = xpath.compile("/OpenSearchDescription/Url");
    NodeList nl = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    NamedNodeMap attrs;
    String template, type;
    if (nl.getLength() == 0) {
        throw new InstantiationException("No OpenSearchDescription/Url found in " + url);
    }
    for (int i = 0; i < nl.getLength(); i++) {
        Node n = nl.item(i);
        attrs = n.getAttributes();
        n = attrs.getNamedItem("template");
        template = n.getTextContent();
        log.debug("template=" + template);
        n = attrs.getNamedItem("type");
        type = n.getTextContent();
        log.info("<Url type='" + type + "' template='" + template + "'/>");
        if ("application/rss+xml".equals(type)) {
            addSchema("RSS2.0", "rss", "http://europa.eu/rapid/conf/RSS20.xsd", "RSS Items", template);
        }
    }
    log.debug("leaving SRWOpenSearchDatabase.init");
}

From source file:org.ojbc.util.xml.XmlUtils.java

/**
 * Search the context node for a String that matches the specified xpath
 * //from ww  w .  ja  va 2s. c  om
 * @param context
 *            the node that's the context for the xpath
 * @param xPath
 *            the xpath query
 * @return the matching string, or null if no match
 * @throws Exception
 */
public static final String xPathStringSearch(Node context, String xPath) throws Exception {
    if (xPath == null) {
        return null;
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(OJBC_NAMESPACE_CONTEXT);
    XPathExpression expression = xpath.compile(xPath);
    return StringUtils.trimToNull((String) expression.evaluate(context, XPathConstants.STRING));
}

From source file:org.ojbc.web.portal.controllers.PortalController.java

UserLogonInfo getUserLogonInfo(Element assertionElement) {

    UserLogonInfo userLogonInfo = new UserLogonInfo();

    if (assertionElement == null) {
        log.warn("assertionElement was null, returning empty UserLogonInfo");
        return userLogonInfo;
    }//from  w w w  .  j  a  va 2s. co  m

    try {

        debugPrintAssertion(assertionElement);

        String instantString = (String) xPath.evaluate("/saml2:Assertion/saml2:AuthnStatement/@AuthnInstant",
                assertionElement, XPathConstants.STRING);
        DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
        DateTime authnInstant = fmt.parseDateTime(instantString);
        int minutesOnline = Minutes.minutesBetween(authnInstant, new DateTime()).getMinutes();
        int hoursOnline = (int) minutesOnline / 60;
        minutesOnline = minutesOnline % 60;
        userLogonInfo.timeOnlineString = String.valueOf(hoursOnline) + ":" + (minutesOnline < 10 ? "0" : "")
                + String.valueOf(minutesOnline);

        String userLastName = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:SurName']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);
        String userFirstName = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:GivenName']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);
        String userAgency = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:EmployerName']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);

        String sEmail = (String) xPath.evaluate(
                "/saml2:Assertion/saml2:AttributeStatement[1]/saml2:Attribute[@Name='gfipm:2.0:user:EmailAddressText']/saml2:AttributeValue/text()",
                assertionElement, XPathConstants.STRING);

        userLogonInfo.userNameString = (userFirstName == null ? "" : userFirstName) + " "
                + (userLastName == null ? "" : userLastName) + " / " + (userAgency == null ? "" : userAgency);
        userLogonInfo.emailAddress = sEmail;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return userLogonInfo;
}

From source file:org.onebusaway.transit_data_federation.impl.realtime.SiriLikeRealtimeSource.java

public NodesAndTimestamp parseVehicles(URL url) throws Exception {
    List<Node> vehicles = new ArrayList<Node>();
    Document doc = builder.parse(url.toString());
    String recordedAtStr = (String) recordedAtExpression.evaluate(doc, XPathConstants.STRING);
    long timestamp = parseDate(recordedAtStr).getTime();
    _log.debug("timestamp=" + new Date(timestamp) + " for date " + recordedAtStr);
    NodeList nl = (NodeList) this.mvjExpression.evaluate(doc, XPathConstants.NODESET);
    if (nl == null || nl.getLength() == 0) {
        _log.debug("no nodes found");
        return new NodesAndTimestamp(vehicles, timestamp);
    }//w w  w. j  av a2s.c  om
    for (int i = 0; i < nl.getLength(); i++) {
        vehicles.add(nl.item(i));
    }
    return new NodesAndTimestamp(vehicles, timestamp);
}

From source file:org.onebusaway.transit_data_federation.impl.realtime.SiriLikeRealtimeSource.java

public VehicleLocationRecord parse(Node node, long timestamp) throws Exception {
    String tripId = (String) tripIdExpression.evaluate(node, XPathConstants.STRING);
    if (tripId == null) {
        _log.error("no trip for node=" + node);
        return null;
    }// ww w. j a  v a  2 s .c om
    if (timestamp == 0) {
        timestamp = SystemTime.currentTimeMillis();
    }

    String serviceDateStr = (String) serviceDateExpression.evaluate(node, XPathConstants.STRING);
    Date serviceDate = parseServiceDate(serviceDateStr);

    VehicleLocationRecord vlr = new VehicleLocationRecord();
    try {
        vlr.setTimeOfLocationUpdate(timestamp);
        vlr.setTimeOfRecord(timestamp);
        vlr.setTripId(new AgencyAndId(getAgency(), tripId));
        vlr.setServiceDate(serviceDate.getTime());
        vlr.setVehicleId(new AgencyAndId(getAgency(),
                (String) vehicleIdExpression.evaluate(node, XPathConstants.STRING)));
        vlr.setCurrentLocationLat(asDouble(latExpression.evaluate(node, XPathConstants.STRING)));
        vlr.setCurrentLocationLon(asDouble(lonExpression.evaluate(node, XPathConstants.STRING)));
        Integer scheduleDeviation = calculateScheduleDeviation(vlr);
        if (scheduleDeviation != null) {
            vlr.setScheduleDeviation(scheduleDeviation);
        }
    } catch (NumberFormatException nfe) {
        _log.info("caught nfe", nfe);
        return null;
    }
    _log.debug("return vlr=" + vlr);
    return vlr;
}

From source file:org.opencastproject.comments.CommentParser.java

private static Comment commentFromManifest(Node commentNode, UserDirectoryService userDirectoryService)
        throws UnsupportedElementException {
    try {/*from w  w  w  .jav a  2 s .  c o m*/
        // id
        Long id = null;
        Double idAsDouble = ((Number) xpath.evaluate("@id", commentNode, XPathConstants.NUMBER)).doubleValue();
        if (!idAsDouble.isNaN())
            id = idAsDouble.longValue();

        // text
        String text = (String) xpath.evaluate("text/text()", commentNode, XPathConstants.STRING);

        // Author
        Node authorNode = (Node) xpath.evaluate("author", commentNode, XPathConstants.NODE);
        User author = userFromManifest(authorNode, userDirectoryService);

        // ResolvedStatus
        Boolean resolved = BooleanUtils
                .toBoolean((Boolean) xpath.evaluate("@resolved", commentNode, XPathConstants.BOOLEAN));

        // Reason
        String reason = (String) xpath.evaluate("reason/text()", commentNode, XPathConstants.STRING);
        if (StringUtils.isNotBlank(reason))
            reason = reason.trim();

        // CreationDate
        String creationDateString = (String) xpath.evaluate("creationDate/text()", commentNode,
                XPathConstants.STRING);
        Date creationDate = new Date(DateTimeSupport.fromUTC(creationDateString));

        // ModificationDate
        String modificationDateString = (String) xpath.evaluate("modificationDate/text()", commentNode,
                XPathConstants.STRING);
        Date modificationDate = new Date(DateTimeSupport.fromUTC(modificationDateString));

        // Create comment
        Comment comment = Comment.create(Option.option(id), text.trim(), author, reason, resolved, creationDate,
                modificationDate);

        // Replies
        NodeList replyNodes = (NodeList) xpath.evaluate("replies/reply", commentNode, XPathConstants.NODESET);
        for (int i = 0; i < replyNodes.getLength(); i++) {
            comment.addReply(replyFromManifest(replyNodes.item(i), userDirectoryService));
        }

        return comment;
    } catch (XPathExpressionException e) {
        throw new UnsupportedElementException("Error while reading comment information from manifest", e);
    } catch (Exception e) {
        if (e instanceof UnsupportedElementException)
            throw (UnsupportedElementException) e;
        throw new UnsupportedElementException(
                "Error while reading comment creation or modification date information from manifest", e);
    }
}

From source file:org.opencastproject.comments.CommentParser.java

private static CommentReply replyFromManifest(Node commentReplyNode, UserDirectoryService userDirectoryService)
        throws UnsupportedElementException {
    try {/*from  w  ww.ja va2 s .c  om*/
        // id
        Long id = null;
        Double idAsDouble = ((Number) xpath.evaluate("@id", commentReplyNode, XPathConstants.NUMBER))
                .doubleValue();
        if (!idAsDouble.isNaN())
            id = idAsDouble.longValue();

        // text
        String text = (String) xpath.evaluate("text/text()", commentReplyNode, XPathConstants.STRING);

        // Author
        Node authorNode = (Node) xpath.evaluate("author", commentReplyNode, XPathConstants.NODE);
        User author = userFromManifest(authorNode, userDirectoryService);

        // CreationDate
        String creationDateString = (String) xpath.evaluate("creationDate/text()", commentReplyNode,
                XPathConstants.STRING);
        Date creationDate = new Date(DateTimeSupport.fromUTC(creationDateString));

        // ModificationDate
        String modificationDateString = (String) xpath.evaluate("modificationDate/text()", commentReplyNode,
                XPathConstants.STRING);
        Date modificationDate = new Date(DateTimeSupport.fromUTC(modificationDateString));

        // Create reply
        return CommentReply.create(Option.option(id), text.trim(), author, creationDate, modificationDate);
    } catch (XPathExpressionException e) {
        throw new UnsupportedElementException("Error while reading comment reply information from manifest", e);
    } catch (Exception e) {
        if (e instanceof UnsupportedElementException)
            throw (UnsupportedElementException) e;
        throw new UnsupportedElementException(
                "Error while reading comment reply creation or modification date information from manifest", e);
    }
}

From source file:org.opencastproject.comments.CommentParser.java

private static User userFromManifest(Node authorNode, UserDirectoryService userDirectoryService) {
    try {// w ww  .  jav  a  2s.c  o m
        // Username
        String userName = (String) xpath.evaluate("username/text()", authorNode, XPathConstants.STRING);
        return userDirectoryService.loadUser(userName);
    } catch (XPathExpressionException e) {
        throw new UnsupportedElementException("Error while reading comment author information from manifest",
                e);
    }
}