Example usage for javax.xml.xpath XPathConstants NUMBER

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

Introduction

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

Prototype

QName NUMBER

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

Click Source Link

Document

The XPath 1.0 number data type.

Maps to Java Double .

Usage

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * Returns the number of found elements based on the XPath query.
 *
 * @param xmlNode//  ww w  . j av  a 2 s .c om
 * @param xPathString
 * @return
 */
public static int count(final Node xmlNode, final String xPathString) {
    try {
        final XPathExpression xPathExpression = createXPathExpression(xPathString);
        final Double number = (Double) xPathExpression.evaluate(xmlNode, XPathConstants.NUMBER);
        return number.intValue();
    } catch (XPathExpressionException e) {
        throw new DSSException(e);
    }
}

From source file:com.flozano.socialauth.plugin.linkedin.FeedPluginImpl.java

private List<Feed> getStatusFeed(final Element root) throws Exception {
    NodeList nodes = root.getElementsByTagName("update");
    List<Feed> list = new ArrayList<Feed>();
    if (nodes != null && nodes.getLength() > 0) {
        LOG.debug("Feeds count :: " + nodes.getLength());
        for (int i = 1; i <= nodes.getLength(); i++) {
            String type = xPath.evaluate("//update[" + i + "]/update-type", root);
            String fname = xPath.evaluate(String.format(fnameExpression, i), root);
            String lname = xPath.evaluate(String.format(lnameExpression, i), root);
            String id = xPath.evaluate(String.format(idExpression, i), root);
            String name = fname + " " + lname;
            String time = xPath.evaluate(String.format(dateExpression, i), root);
            Date date = new Date(Long.valueOf(time));

            boolean isSet = true;
            Feed feed = new Feed();
            feed.setId(id);/*from   ww  w.j a va2s.  com*/
            feed.setCreatedAt(date);
            feed.setFrom(name);

            if ("CONN".equals(type)) {
                String cfname = xPath.evaluate(String.format(cfnameExpression, i), root);
                String clname = xPath.evaluate(String.format(clnameExpression, i), root);
                feed.setMessage(name + UPDATE_TYPES.get("CONN") + cfname + " " + clname);
            } else if ("NCON".equals(type)) {
                feed.setMessage(name + UPDATE_TYPES.get("NCON"));
            } else if ("CCEM".equals(type)) {
                feed.setMessage(name + UPDATE_TYPES.get("CCEM"));
            } else if ("SHAR".equals(type)) {
                String comment = xPath.evaluate(String.format(shareCommentExpression, i), root);
                feed.setMessage(name + UPDATE_TYPES.get("SHAR") + comment);
            } else if ("STAT".equals(type)) {
                String status = xPath.evaluate(String.format(statusExpression, i), root);
                feed.setMessage(name + UPDATE_TYPES.get("STAT") + status);
            } else if ("JOBP".equals(type)) {
                String jpFname = xPath.evaluate(String.format(jobPosterFnameExpression, i), root);
                String jpLname = xPath.evaluate(String.format(jobPosterLnameExpression, i), root);
                String jpId = xPath.evaluate(String.format(jobPosterIdExpression, i), root);
                String position = xPath.evaluate(String.format(jobPositionExpression, i), root);
                String company = xPath.evaluate(String.format(jobCompanyExpression, i), root);
                feed.setFrom(jpFname + " " + jpLname);
                feed.setId(jpId);
                feed.setMessage(
                        jpFname + " " + jpLname + UPDATE_TYPES.get("JOBP") + position + " at " + company);
            } else if ("JGRP".equals(type)) {
                String groupName = xPath.evaluate(String.format(groupNameExpression, i), root);
                feed.setMessage(name + UPDATE_TYPES.get("JGRP") + groupName);
            } else if ("PREC".equals(type)) {
                double count = (Double) xPath.evaluate(String.format(recommendationGivenCountExpression, i),
                        root, XPathConstants.NUMBER);
                String message = "";
                if (count > 0) {
                    String recommendation = xPath.evaluate(String.format(recommendationExpression, i), root);
                    String recommendeeFname = xPath.evaluate(String.format(recommendeeFnameExpression, i),
                            root);
                    String recommendeeLname = xPath.evaluate(String.format(recommendeeLnameExpression, i),
                            root);
                    message = name + UPDATE_TYPES.get("PREC_GIVEN") + recommendeeFname + " " + recommendeeLname;
                    if (recommendation != null && recommendation.length() > 0) {
                        message += " :'" + recommendation + "'";
                    }
                } else {
                    String recommendeeFname = xPath.evaluate(String.format(recommenderFnameExpression, i),
                            root);
                    String recommendeeLname = xPath.evaluate(String.format(recommenderLnameExpression, i),
                            root);
                    message = name + UPDATE_TYPES.get("PREC_RECEIVED") + recommendeeFname + " "
                            + recommendeeLname;
                }
                feed.setMessage(message);
            } else if ("PROF".equals(type)) {
                feed.setMessage(name + UPDATE_TYPES.get("PROF"));
            } else if ("APPM".equals(type)) {
                String update = xPath.evaluate(String.format(appUpdateExpression, i), root);
                feed.setMessage(name + UPDATE_TYPES.get("APPM") + update);
            } else if ("MSFC".equals(type)) {
                String company = xPath.evaluate(String.format(companyExpression, i), root);
                String pfname = xPath.evaluate(String.format(companyPersonFnameExpression, i), root);
                String plname = xPath.evaluate(String.format(companyPersonLnameExpression, i), root);
                String pid = xPath.evaluate(String.format(companyPersonIdExpression, i), root);
                feed.setMessage(pfname + " " + plname + UPDATE_TYPES.get("MSFC") + company);
                feed.setFrom(pfname + " " + pfname);
                feed.setId(pid);
                list.add(feed);
            } else if ("PICU".equals(type)) {
                feed.setMessage(name + UPDATE_TYPES.get("PICU"));
            } else {
                isSet = false;
            }

            if (isSet) {
                list.add(feed);
            }
        }
    }
    return list;
}

From source file:com.espertech.esper.client.ConfigurationParser.java

private static void handleXMLDOM(String name, Configuration configuration, Element xmldomElement) {
    String rootElementName = getRequiredAttribute(xmldomElement, "root-element-name");
    String rootElementNamespace = getOptionalAttribute(xmldomElement, "root-element-namespace");
    String schemaResource = getOptionalAttribute(xmldomElement, "schema-resource");
    String schemaText = getOptionalAttribute(xmldomElement, "schema-text");
    String defaultNamespace = getOptionalAttribute(xmldomElement, "default-namespace");
    String resolvePropertiesAbsoluteStr = getOptionalAttribute(xmldomElement,
            "xpath-resolve-properties-absolute");
    String propertyExprXPathStr = getOptionalAttribute(xmldomElement, "xpath-property-expr");
    String eventSenderChecksRootStr = getOptionalAttribute(xmldomElement, "event-sender-validates-root");
    String xpathFunctionResolverClass = getOptionalAttribute(xmldomElement, "xpath-function-resolver");
    String xpathVariableResolverClass = getOptionalAttribute(xmldomElement, "xpath-variable-resolver");
    String autoFragmentStr = getOptionalAttribute(xmldomElement, "auto-fragment");
    String startTimestampProperty = getOptionalAttribute(xmldomElement, "start-timestamp-property-name");
    String endTimestampProperty = getOptionalAttribute(xmldomElement, "end-timestamp-property-name");

    ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();
    xmlDOMEventTypeDesc.setRootElementName(rootElementName);
    xmlDOMEventTypeDesc.setSchemaResource(schemaResource);
    xmlDOMEventTypeDesc.setSchemaText(schemaText);
    xmlDOMEventTypeDesc.setRootElementNamespace(rootElementNamespace);
    xmlDOMEventTypeDesc.setDefaultNamespace(defaultNamespace);
    xmlDOMEventTypeDesc.setXPathFunctionResolver(xpathFunctionResolverClass);
    xmlDOMEventTypeDesc.setXPathVariableResolver(xpathVariableResolverClass);
    xmlDOMEventTypeDesc.setStartTimestampPropertyName(startTimestampProperty);
    xmlDOMEventTypeDesc.setEndTimestampPropertyName(endTimestampProperty);
    if (resolvePropertiesAbsoluteStr != null) {
        xmlDOMEventTypeDesc// ww w.  jav  a2  s. c om
                .setXPathResolvePropertiesAbsolute(Boolean.parseBoolean(resolvePropertiesAbsoluteStr));
    }
    if (propertyExprXPathStr != null) {
        xmlDOMEventTypeDesc.setXPathPropertyExpr(Boolean.parseBoolean(propertyExprXPathStr));
    }
    if (eventSenderChecksRootStr != null) {
        xmlDOMEventTypeDesc.setEventSenderValidatesRoot(Boolean.parseBoolean(eventSenderChecksRootStr));
    }
    if (autoFragmentStr != null) {
        xmlDOMEventTypeDesc.setAutoFragment(Boolean.parseBoolean(autoFragmentStr));
    }
    configuration.addEventType(name, xmlDOMEventTypeDesc);

    DOMElementIterator propertyNodeIterator = new DOMElementIterator(xmldomElement.getChildNodes());
    while (propertyNodeIterator.hasNext()) {
        Element propertyElement = propertyNodeIterator.next();
        if (propertyElement.getNodeName().equals("namespace-prefix")) {
            String prefix = getRequiredAttribute(propertyElement, "prefix");
            String namespace = getRequiredAttribute(propertyElement, "namespace");
            xmlDOMEventTypeDesc.addNamespacePrefix(prefix, namespace);
        }
        if (propertyElement.getNodeName().equals("xpath-property")) {
            String propertyName = getRequiredAttribute(propertyElement, "property-name");
            String xPath = getRequiredAttribute(propertyElement, "xpath");
            String propertyType = getRequiredAttribute(propertyElement, "type");
            QName xpathConstantType;
            if (propertyType.toUpperCase().equals("NUMBER")) {
                xpathConstantType = XPathConstants.NUMBER;
            } else if (propertyType.toUpperCase().equals("STRING")) {
                xpathConstantType = XPathConstants.STRING;
            } else if (propertyType.toUpperCase().equals("BOOLEAN")) {
                xpathConstantType = XPathConstants.BOOLEAN;
            } else if (propertyType.toUpperCase().equals("NODE")) {
                xpathConstantType = XPathConstants.NODE;
            } else if (propertyType.toUpperCase().equals("NODESET")) {
                xpathConstantType = XPathConstants.NODESET;
            } else {
                throw new IllegalArgumentException("Invalid xpath property type for property '" + propertyName
                        + "' and type '" + propertyType + '\'');
            }

            String castToClass = null;
            if (propertyElement.getAttributes().getNamedItem("cast") != null) {
                castToClass = propertyElement.getAttributes().getNamedItem("cast").getTextContent();
            }

            String optionaleventTypeName = null;
            if (propertyElement.getAttributes().getNamedItem("event-type-name") != null) {
                optionaleventTypeName = propertyElement.getAttributes().getNamedItem("event-type-name")
                        .getTextContent();
            }

            if (optionaleventTypeName != null) {
                xmlDOMEventTypeDesc.addXPathPropertyFragment(propertyName, xPath, xpathConstantType,
                        optionaleventTypeName);
            } else {
                xmlDOMEventTypeDesc.addXPathProperty(propertyName, xPath, xpathConstantType, castToClass);
            }
        }
    }
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

/**
 * Returns if the property is available for the reservation.
 * /*w  ww  .  j av  a  2s . c  om*/
 * @param sqlSession the current SQL session.
 * @param reservation the reservation for collisions
 * @return list of collisions
 */
@Override
public boolean isAvailable(SqlSession sqlSession, Reservation reservation) {
    StringBuilder sb = new StringBuilder();
    Date now = new Date();
    long time = now.getTime();
    String SenderSessionID = time + "bookingnetS";
    String ReceiverSessionID = time + "bookingnetR";
    String rq;
    String rs = null;
    boolean available = false;
    if (reservation.notActive()) {
        throw new ServiceException(Error.reservation_state,
                reservation.getId() + " state " + reservation.getState());
    }

    Product product = sqlSession.getMapper(ProductMapper.class).read(reservation.getProductid());
    if (product == null) {
        throw new ServiceException(Error.product_id, reservation.getProductid());
    }
    if (reservation.noAgentid()) {
        throw new ServiceException(Error.reservation_agentid);
    }
    Party agent = sqlSession.getMapper(PartyMapper.class).read(reservation.getAgentid());
    if (agent == null) {
        throw new ServiceException(Error.party_id, reservation.getAgentid());
    }
    if (reservation.noCustomerid()) {
        reservation.setCustomerid(Party.NO_ACTOR);
    }
    Party customer = sqlSession.getMapper(PartyMapper.class).read(reservation.getCustomerid());
    if (customer == null) {
        throw new ServiceException(Error.reservation_customerid, reservation.getCustomerid());
    }

    try {
        sb.append("<?xml version='1.0' ?>");
        sb.append("<TravelMessage VersionID='1.8N'>");
        sb.append(" <Control Language='NL' Test='nee'>");
        sb.append("    <SenderSessionID>" + SenderSessionID + "</SenderSessionID>");
        sb.append("    <ReceiverSessionID>" + ReceiverSessionID + "</ReceiverSessionID>");
        sb.append("    <Date>" + DF.format(new Date()) + "</Date>");
        sb.append("    <Time Reliability='zeker'>" + TF.format(new Date()) + "</Time>");
        sb.append("   <MessageSequence>1</MessageSequence>");
        sb.append("   <SenderID>" + SENDERID + "</SenderID>");
        sb.append("  <ReceiverID>NPS001</ReceiverID>");
        sb.append("   <RequestID>AvailabilitybookingnetRequest</RequestID>");
        sb.append("   <ResponseID>AvailabilitybookingnetResponse</ResponseID>");
        sb.append(" </Control>");
        sb.append("  <TRequest>");
        sb.append("    <AvailabilitybookingnetRequest>");
        sb.append("      <PackageDetails WaitListCheck='ja'>");
        sb.append("          <AccommodationID>" + "A" + product.getAltid() + "</AccommodationID>");
        sb.append("          <ArrivalDate>" + DF.format(reservation.getFromdate()) + "</ArrivalDate>");
        sb.append("        <Duration DurationType='dagen'>" + reservation.getDuration(Time.DAY).intValue()
                + "</Duration>");
        sb.append("     </PackageDetails>");
        sb.append("   </AvailabilitybookingnetRequest>");
        sb.append("  </TRequest>");
        sb.append("</TravelMessage>");

        rq = sb.toString();
        LOG.debug("isAvailable rq: \n" + rq + "\n");

        rs = getConnection(rq);
        LOG.debug("isAvailable rs: \n" + rs + "\n");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        InputSource inputSource = new InputSource(new StringReader(rs.toString()));
        Double bookID = (Double) xpath.evaluate("//PackageID", inputSource, XPathConstants.NUMBER);
        available = !bookID.isNaN();
    } catch (Throwable e) {
        LOG.error(e.getMessage());
    }
    return available;
}

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

private ConfigurationEventTypeXMLDOM getConfigTestType(String additionalXPathProperty,
        boolean isUseXPathPropertyExpression) {
    ConfigurationEventTypeXMLDOM eventTypeMeta = new ConfigurationEventTypeXMLDOM();
    eventTypeMeta.setRootElementName("simpleEvent");
    String schemaUri = TestSchemaXMLEvent.class.getClassLoader().getResource(CLASSLOADER_SCHEMA_URI).toString();
    eventTypeMeta.setSchemaResource(schemaUri);
    eventTypeMeta.addNamespacePrefix("ss", "samples:schemas:simpleSchema");
    eventTypeMeta.addXPathProperty("customProp", "count(/ss:simpleEvent/ss:nested3/ss:nested4)",
            XPathConstants.NUMBER);
    eventTypeMeta.setXPathPropertyExpr(isUseXPathPropertyExpression);
    if (additionalXPathProperty != null) {
        eventTypeMeta.addXPathProperty(additionalXPathProperty, "count(/ss:simpleEvent/ss:nested3/ss:nested4)",
                XPathConstants.NUMBER);
    }// w  w  w  .  j a  v  a  2s  .  co m
    return eventTypeMeta;
}

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

@Test
public void testPerformEntityResolution() throws Exception {

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(testNamespaceContext);

    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);
    // LOG.info(converter.toString(testRequestMessage));

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);// ww  w . j av  a2s  . com
    assertNotNull(entityContainerNode);

    List<String> lastNames = new ArrayList<String>();
    List<String> firstNames = new ArrayList<String>();
    List<String> sids = new ArrayList<String>();

    NodeList inputEntityNodes = (NodeList) testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity");
    int inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, inputEntityNodes.getLength());

    for (int i = 0; i < inputEntityNodeCount; i++) {
        Node entityNode = inputEntityNodes.item(i);
        lastNames.add(
                xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName", entityNode));
        firstNames.add(
                xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName", entityNode));
        sids.add(xp.evaluate(
                "ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID",
                entityNode));
    }

    Map<String, Integer> lastNameCountMap = new HashMap<String, Integer>();
    for (String lastName : lastNames) {
        Integer count = lastNameCountMap.get(lastName);
        if (count == null) {
            count = 0;
        }
        lastNameCountMap.put(lastName, ++count);
    }
    Map<String, Integer> firstNameCountMap = new HashMap<String, Integer>();
    for (String firstName : firstNames) {
        Integer count = firstNameCountMap.get(firstName);
        if (count == null) {
            count = 0;
        }
        firstNameCountMap.put(firstName, ++count);
    }
    Map<String, Integer> sidCountMap = new HashMap<String, Integer>();
    for (String sid : sids) {
        Integer count = sidCountMap.get(sid);
        if (count == null) {
            count = 0;
        }
        sidCountMap.put(sid, ++count);
    }

    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            null);

    resultDocument.normalizeDocument();
    // LOG.info(converter.toString(resultDocument));
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument,
            XPathConstants.NODESET);
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    for (int i = 0; i < entityNodes.getLength(); i++) {
        Element e = (Element) entityNodes.item(i);
        String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref");
        assertNotNull(entityIdRef);
        assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument,
                XPathConstants.NODE));
    }
    for (String lastName : lastNameCountMap.keySet()) {
        assertEquals(lastNameCountMap.get(lastName).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName='"
                        + lastName + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }
    for (String firstName : firstNames) {
        assertEquals(firstNameCountMap.get(firstName).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName='"
                        + firstName + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }
    for (String sid : sids) {
        assertEquals(sidCountMap.get(sid).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID='"
                        + sid + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }

    String recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Extract a tracking ID from an XML string.
 * /*from w  ww  .  java 2 s. c om*/
 * @param xml
 *        the XML to extract from
 * @param xp
 *        the XPath to use that returns a number
 * @param xpath
 *        the XPath as a string (for debugging)
 * @return the tracking ID, or <em>null</em> if not found
 */
protected Long extractTrackingId(InputSource xml, XPathExpression xp, String xpath) {
    Double tid;
    try {
        tid = (Double) xp.evaluate(xml, XPathConstants.NUMBER);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
    if (tid.isNaN()) {
        log.warn("Unable to extract tracking ID via XPath [{}]", xpath);
        return null;
    }
    return tid.longValue();
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

private static Reservation readPrice(SqlSession sqlSession, Reservation reservation, String productAltId) {
    StringBuilder sb = new StringBuilder();
    Date now = new Date();
    long time = now.getTime();
    String SenderSessionID = time + "bookingnetS";
    String ReceiverSessionID = time + "bookingnetR";
    String rq;/*from   ww w  . j  av a2s  . c o  m*/
    String rs = null;

    try {
        sb.append("<?xml version='1.0' ?>");
        sb.append("<TravelMessage VersionID='1.8N'>");
        sb.append(" <Control Language='NL' Test='nee'>");
        sb.append("    <SenderSessionID>" + SenderSessionID + "</SenderSessionID>");
        sb.append("    <ReceiverSessionID>" + ReceiverSessionID + "</ReceiverSessionID>");
        sb.append("    <Date>" + DF.format(new Date()) + "</Date>");
        sb.append("    <Time Reliability='zeker'>" + TF.format(new Date()) + "</Time>");
        sb.append("   <MessageSequence>1</MessageSequence>");
        sb.append("   <SenderID>" + SENDERID + "</SenderID>");
        sb.append("  <ReceiverID>NPS001</ReceiverID>");
        sb.append("   <RequestID>AvailabilitybookingnetRequest</RequestID>");
        sb.append("   <ResponseID>AvailabilitybookingnetResponse</ResponseID>");
        sb.append(" </Control>");
        sb.append("  <TRequest>");
        sb.append("    <AvailabilitybookingnetRequest>");
        sb.append("      <PackageDetails WaitListCheck='ja'>");
        sb.append("          <AccommodationID>" + "A" + productAltId + "</AccommodationID>");
        sb.append("          <ArrivalDate>" + DF.format(reservation.getFromdate()) + "</ArrivalDate>");
        sb.append("        <Duration DurationType='dagen'>" + reservation.getDuration(Time.DAY).intValue()
                + "</Duration>");
        sb.append("     </PackageDetails>");
        sb.append("   </AvailabilitybookingnetRequest>");
        sb.append("  </TRequest>");
        sb.append("</TravelMessage>");

        rq = sb.toString();
        rs = getConnection(rq); // fix code have better support. gettting errors when deploying with tomcat.

        LOG.debug("computePrice rq: \n" + rq + "\n");
        LOG.debug("computePrice rs: \n" + rs + "\n");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        InputSource inputSource = new InputSource(new StringReader(rs.toString()));
        Double price = (Double) xpath.evaluate("//Price", inputSource, XPathConstants.NUMBER);
        if (Double.isNaN(price)) {
            throw new ServiceException(Error.product_not_available);
        }

        price = price / 100.00; //price is a whole number

        factory = XPathFactory.newInstance();
        xpath = factory.newXPath();
        inputSource = new InputSource(new StringReader(rs.toString()));
        String fromCurrency = (String) xpath.evaluate("//Price/@Currency", inputSource, XPathConstants.STRING);
        if ("".equals(fromCurrency)) {
            throw new ServiceException(Error.price_missing, reservation.getId() + " State = "
                    + reservation.getState() + " currency = " + reservation.getCurrency());
        }
        String tocurrency = reservation.getCurrency();
        if (!fromCurrency.equalsIgnoreCase(tocurrency)) {
            // Double rate = OpenExchangeRates.getExchangeRate(currency,rescurrency);
            Double rate = WebService.getRate(sqlSession, fromCurrency, tocurrency, new Date());
            price = rate * price;
        }

        LOG.debug("price = " + price);
        reservation.setPrice(price);
        reservation.setQuote(price);
    } catch (Throwable e) {
        LOG.error(e.getMessage());
        reservation.setPrice(0.00);
    }
    return reservation;
}

From source file:net.ymate.framework.commons.XPathHelper.java

public Number getNumberValue(String expression) throws XPathExpressionException {
    return (Number) __doEvaluate(expression, null, XPathConstants.NUMBER);
}

From source file:net.ymate.framework.commons.XPathHelper.java

public Number getNumberValue(Object item, String expression) throws XPathExpressionException {
    return (Number) __doEvaluate(expression, item, XPathConstants.NUMBER);
}