List of usage examples for javax.xml.xpath XPathConstants NUMBER
QName NUMBER
To view the source code for javax.xml.xpath XPathConstants NUMBER.
Click Source Link
The XPath 1.0 number data type.
Maps to Java Double .
From source file:org.joox.test.JOOXTest.java
License:asdf
@Before public void setUp() throws Exception { DocumentBuilder builder = JOOX.builder(); xmlExampleString = IOUtils.toString(JOOXTest.class.getResourceAsStream("/example.xml")); xmlExampleDocument = builder.parse(new ByteArrayInputStream(xmlExampleString.getBytes())); xmlExampleElement = xmlExampleDocument.getDocumentElement(); xmlDatesString = IOUtils.toString(JOOXTest.class.getResourceAsStream("/dates.xml")); xmlDatesDocument = builder.parse(new ByteArrayInputStream(xmlDatesString.getBytes())); xmlDatesElement = xmlDatesDocument.getDocumentElement(); xmlNamespacesString = IOUtils.toString(JOOXTest.class.getResourceAsStream("/namespaces.xml")); xmlNamespacesDocument = builder.parse(new ByteArrayInputStream(xmlNamespacesString.getBytes())); xmlNamespacesElement = xmlNamespacesDocument.getDocumentElement(); $ = $(xmlExampleDocument);//w w w. j a v a 2 s . co m xPath = XPathFactory.newInstance().newXPath(); totalElements = ((Number) xPath.evaluate("count(//*)", xmlExampleDocument, XPathConstants.NUMBER)) .intValue() - 1; }
From source file:org.lockss.plugin.clockss.XPathXmlMetadataParser.java
private ArticleMetadata extractDataFromNode(Object startNode, XPathInfo[] xPathList) throws XPathExpressionException { ArticleMetadata returnAM = makeNewArticleMetadata(); NumberFormat format = NumberFormat.getInstance(); for (int i = 0; i < xPathList.length; i++) { log.debug3("evaluate xpath: " + xPathList[i].xKey.toString()); QName definedType = xPathList[i].xVal.getType(); Object itemResult = xPathList[i].xExpr.evaluate(startNode, XPathConstants.NODESET); NodeList resultNodeList = (NodeList) itemResult; log.debug3(resultNodeList.getLength() + " results for this xKey"); for (int p = 0; p < resultNodeList.getLength(); p++) { Node resultNode = resultNodeList.item(p); if (resultNode == null) { continue; }//from ww w . j a v a2s. c o m String value = null; if (definedType == XPathConstants.NODE) { // filter node value = xPathList[i].xVal.getValue(resultNode); } else if (definedType == XPathConstants.STRING) { // filter node text content String text = resultNode.getTextContent(); if (!StringUtil.isNullString(text)) { value = xPathList[i].xVal.getValue(text); } } else if (definedType == XPathConstants.BOOLEAN) { // filter boolean value of node text content String text = resultNode.getTextContent(); if (!StringUtil.isNullString(text)) { value = xPathList[i].xVal.getValue(Boolean.parseBoolean(text)); } } else if (definedType == XPathConstants.NUMBER) { // filter number value of node text content try { String text = resultNode.getTextContent(); if (!StringUtil.isNullString(text)) { value = xPathList[i].xVal.getValue(format.parse(text)); } } catch (ParseException ex) { // ignore invalid number log.debug3("ignore invalid number", ex); } } else { log.debug("Unknown nodeValue type: " + definedType.toString()); } if (!StringUtil.isNullString(value)) { log.debug3(" returning (" + xPathList[i].xKey + ", " + value); returnAM.putRaw(xPathList[i].xKey, value); } } } return returnAM; }
From source file:org.mule.module.dxpath.DxTransformer.java
/** * Result type from this transformer.// www. j a v a2 s . c o m * * @param resultType * Result type from this transformer. */ public void setResultType(ResultType resultTypeType) { QName resultType; switch (resultTypeType) { case BOOLEAN: resultType = XPathConstants.BOOLEAN; break; case NODE: resultType = XPathConstants.NODE; break; case NODESET: resultType = XPathConstants.NODESET; break; case NUMBER: resultType = XPathConstants.NUMBER; break; default: resultType = XPathConstants.STRING; break; } this.resultType = resultType; }
From source file:org.opencastproject.comments.CommentParser.java
private static Comment commentFromManifest(Node commentNode, UserDirectoryService userDirectoryService) throws UnsupportedElementException { try {/*from w ww . jav a2 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 {/*w ww . j a va 2 s . co m*/ // 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.metadata.dublincore.DublinCoreCatalogList.java
/** * Parses an XML or JSON string to an dublin core catalog list. * /*from w ww .j a va 2 s . c o m*/ * @param dcString * the XML or JSON string * @throws IOException * if there is a problem parsing the XML or JSON */ public static DublinCoreCatalogList parse(String dcString) throws IOException { List<DublinCoreCatalog> catalogs = new ArrayList<DublinCoreCatalog>(); if (dcString.startsWith("{")) { JSONObject json; try { json = (JSONObject) new JSONParser().parse(dcString); long totalCount = Long.parseLong((String) json.get("totalCount")); JSONArray catalogsArray = (JSONArray) json.get("catalogs"); for (Object catalog : catalogsArray) { InputStream is = null; try { is = IOUtils.toInputStream(((JSONObject) catalog).toJSONString(), "UTF-8"); catalogs.add(new DublinCoreCatalogImpl(is)); } finally { IoSupport.closeQuietly(is); } } return new DublinCoreCatalogList(catalogs, totalCount); } catch (Exception e) { throw new IllegalStateException("Unable to load dublin core catalog list, json parsing failed.", e); } } else { InputStream is = null; try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); is = IOUtils.toInputStream(dcString, "UTF-8"); Document document = docBuilder.parse(is); XPath xPath = XPathFactory.newInstance().newXPath(); Number totalCount = (Number) xPath.evaluate("/*[local-name() = 'dublincorelist']/@totalCount", document, XPathConstants.NUMBER); NodeList nodes = (NodeList) xPath.evaluate("//*[local-name() = 'dublincore']", document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { InputStream nodeIs = null; try { nodeIs = nodeToString(nodes.item(i)); catalogs.add(new DublinCoreCatalogImpl(nodeIs)); } finally { IoSupport.closeQuietly(nodeIs); } } return new DublinCoreCatalogList(catalogs, totalCount.longValue()); } catch (Exception e) { throw new IOException(e); } finally { IoSupport.closeQuietly(is); } } }
From source file:org.wattdepot.client.http.api.collector.EGaugeCollector.java
@Override public void run() { Measurement meas = null;// ww w .j av a 2s.c o m DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); // Have to make HTTP connection manually so we can set proper timeouts URL url = new URL(eGaugeUri); URLConnection httpConnection; httpConnection = url.openConnection(); // Set both connect and read timeouts to 15 seconds. No point in long // timeouts since the // sensor will retry before too long anyway. httpConnection.setConnectTimeout(15 * 1000); httpConnection.setReadTimeout(15 * 1000); httpConnection.connect(); // Record current time as close approximation to time for reading we are // about to make Date timestamp = new Date(); Document doc = builder.parse(httpConnection.getInputStream()); XPathFactory factory = XPathFactory.newInstance(); XPath powerXpath = factory.newXPath(); XPath energyXpath = factory.newXPath(); // Path to get the current power consumed measured by the meter in watts String exprPowerString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/i/text()"; XPathExpression exprPower = powerXpath.compile(exprPowerString); // Path to get the energy consumed month to date in watt seconds String exprEnergyString = "//r[@rt='total' and @t='P' and @n='" + this.registerName + "']/v/text()"; XPathExpression exprEnergy = energyXpath.compile(exprEnergyString); Object powerResult = exprPower.evaluate(doc, XPathConstants.NUMBER); Object energyResult = exprEnergy.evaluate(doc, XPathConstants.NUMBER); Double value = null; // power is given in W Amount<?> power = Amount.valueOf((Double) powerResult, SI.WATT); // energy given in Ws Amount<?> energy = Amount.valueOf((Double) energyResult, SI.WATT.times(SI.SECOND)); if (isPower()) { value = power.to(measUnit).getEstimatedValue(); } else { value = energy.to(measUnit).getEstimatedValue(); } meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit); } catch (MalformedURLException e) { System.err.format("URI %s was invalid leading to malformed URL%n", eGaugeUri); } catch (XPathExpressionException e) { System.err.println("Bad XPath expression, this should never happen."); } catch (ParserConfigurationException e) { System.err.println("Unable to configure XML parser, this is weird."); } catch (SAXException e) { System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } catch (IOException e) { System.err.format( "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } if (meas != null) { try { this.client.putMeasurement(depository, meas); } catch (MeasurementTypeException e) { System.err.format("%s does not store %s measurements%n", depository.getName(), meas.getMeasurementType()); } if (debug) { System.out.println(meas); } } }
From source file:org.wattdepot.client.http.api.collector.NOAAWeatherCollector.java
@Override public void run() { Measurement meas = null;//from www . j a va2 s . c o m DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); // Have to make HTTP connection manually so we can set proper timeouts URL url = new URL(noaaWeatherUri); URLConnection httpConnection; httpConnection = url.openConnection(); // Set both connect and read timeouts to 15 seconds. No point in long // timeouts since the // sensor will retry before too long anyway. httpConnection.setConnectTimeout(15 * 1000); httpConnection.setReadTimeout(15 * 1000); httpConnection.connect(); // Record current time as close approximation to time for reading we are // about to make Date timestamp = new Date(); Document doc = builder.parse(httpConnection.getInputStream()); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); // path to the data String valString = "/current_observation/" + this.registerName + "/text()"; XPathExpression exprValue = xPath.compile(valString); Object result = new Double(0); if (this.registerName.equals("weather")) { Object cloudCoverage = exprValue.evaluate(doc, XPathConstants.STRING); String cloudStr = cloudCoverage.toString(); if (cloudStr.equalsIgnoreCase("sunny") || cloudStr.equalsIgnoreCase("clear")) { // 0 to 1/8 cloud coverage result = new Double(6.25); } else if (cloudStr.equalsIgnoreCase("mostly sunny") || cloudStr.equalsIgnoreCase("mostly clear")) { // 1/8 to 2/8 cloud coverage result = new Double(18.75); } else if (cloudStr.equalsIgnoreCase("partly sunny") || cloudStr.equalsIgnoreCase("partly cloudy")) { // 3/8 to 5/8 cloud coverage result = new Double(50.0); } else if (cloudStr.equalsIgnoreCase("mostly cloudy")) { // 6/8 to 7/8 cloud coverage result = new Double(81.25); } else if (cloudStr.equalsIgnoreCase("cloudy")) { // 7/8 to 100% cloud coverage result = new Double(93.75); } } else { result = exprValue.evaluate(doc, XPathConstants.NUMBER); } Double value = (Double) result; meas = new Measurement(definition.getSensorId(), timestamp, value, measUnit); } catch (MalformedURLException e) { System.err.format("URI %s was invalid leading to malformed URL%n", noaaWeatherUri); } catch (XPathExpressionException e) { System.err.println("Bad XPath expression, this should never happen."); } catch (ParserConfigurationException e) { System.err.println("Unable to configure XML parser, this is weird."); } catch (SAXException e) { System.err.format("%s: Got bad XML from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } catch (IOException e) { System.err.format( "%s: Unable to retrieve data from eGauge sensor %s (%s), hopefully this is temporary.%n", Tstamp.makeTimestamp(), sensor.getName(), e); } if (meas != null) { try { this.client.putMeasurement(depository, meas); } catch (MeasurementTypeException e) { System.err.format("%s does not store %s measurements%n", depository.getName(), meas.getMeasurementType()); } if (debug) { System.out.println(meas); } } }
From source file:org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument.java
/** * Function to evaluate xPath query, and return specified return type * * @param xpathStr xpath expression to evaluate * @param returnType The desired return type of xpath evaluation. Supported retrun types : "NODESET", "NODE", "STRING", "NUMBER", "BOOLEAN" * @return result of xpath evaluation in specified return type * @throws BPMNXmlException/*from ww w .ja v a 2 s .c om*/ * @throws XPathExpressionException */ public Object xPath(String xpathStr, String returnType) throws BPMNXmlException, XPathExpressionException { if (returnType.equals(XPathConstants.NODESET.getLocalPart())) { Utils.evaluateXPath(doc, xpathStr, XPathConstants.NODESET); } else if (returnType.equals(XPathConstants.NODE.getLocalPart())) { Utils.evaluateXPath(doc, xpathStr, XPathConstants.NODE); } else if (returnType.equals(XPathConstants.STRING.getLocalPart())) { Utils.evaluateXPath(doc, xpathStr, XPathConstants.STRING); } else if (returnType.equals(XPathConstants.NUMBER.getLocalPart())) { Utils.evaluateXPath(doc, xpathStr, XPathConstants.NUMBER); } else if (returnType.equals(XPathConstants.BOOLEAN.getLocalPart())) { Utils.evaluateXPath(doc, xpathStr, XPathConstants.BOOLEAN); } else { //Unknown return type throw new BPMNXmlException("Unknown return type : " + returnType); } return null; }
From source file:org.wso2.carbon.humantask.core.engine.runtime.xpath.XPathExpressionRuntime.java
/** * Evaluate given XPath and returns the results as a java.lang.Number * * @param exp XPath expression//from w w w. j a v a 2 s . c o m * @param evalCtx Evaluation context containing all the required context information * @return Number */ @Override public Number evaluateAsNumber(String exp, EvaluationContext evalCtx) { return (Number) evaluate(exp, evalCtx, XPathConstants.NUMBER); }