List of usage examples for org.w3c.dom Node getTextContent
public String getTextContent() throws DOMException;
From source file:org.freeeed.search.web.solr.SolrSearchService.java
/** * Parse the given DOM to SolrResult object. * /*ww w . j a v a 2 s .c o m*/ * @param query * @param solrDoc * @return */ private SolrResult buildResult(Document solrDoc) { SolrResult result = new SolrResult(); NodeList responseList = solrDoc.getElementsByTagName("result"); Element responseEl = (Element) responseList.item(0); int totalSize = Integer.parseInt(responseEl.getAttribute("numFound")); result.setTotalSize(totalSize); NodeList documentsList = responseEl.getElementsByTagName("doc"); Map<String, SolrDocument> solrDocuments = new HashMap<String, SolrDocument>(); for (int i = 0; i < documentsList.getLength(); i++) { Element documentEl = (Element) documentsList.item(i); Map<String, List<String>> data = new HashMap<String, List<String>>(); NodeList fieldsList = documentEl.getChildNodes(); for (int j = 0; j < fieldsList.getLength(); j++) { Element field = (Element) fieldsList.item(j); String name = field.getAttribute("name"); List<String> value = new ArrayList<String>(); //multivalues if (field.getNodeName().equals("arr")) { NodeList strList = field.getChildNodes(); for (int k = 0; k < strList.getLength(); k++) { Node strNode = strList.item(k); value.add(strNode.getTextContent()); } } else { value.add(field.getTextContent()); } data.put(name, value); } SolrDocument doc = solrDocumentParser.createSolrDocument(data); solrDocuments.put(doc.getDocumentId(), doc); } result.setDocuments(solrDocuments); return result; }
From source file:de.slub.fedora.oai.OaiHarvester.java
private void handleXmlResult(InputStream content) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); Document document = documentBuilderFactory.newDocumentBuilder().parse(content); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression xSelectIdentifier = xPath.compile("//header/identifier"); NodeList nodes = (NodeList) xSelectIdentifier.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); jobQueue.add(new ObjectIndexJob(IndexJob.Type.CREATE, getLocalIdentifier(n.getTextContent()))); }/*from ww w .j a v a 2 s.c o m*/ XPathExpression xSelectResumptionToken = xPath.compile("//resumptionToken"); resumptionToken = (String) xSelectResumptionToken.evaluate(document, XPathConstants.STRING); XPathExpression xSelectExpirationDate = xPath.compile("//resumptionToken/@expirationDate"); String s = (String) xSelectExpirationDate.evaluate(document, XPathConstants.STRING); if (s == null || s.isEmpty()) { expirationDate = null; } else { expirationDate = DatatypeConverter.parseDateTime(s).getTime(); } }
From source file:com.jaeksoft.searchlib.util.XPathParser.java
final public String getSubNodeTextIfAny(Node parentNode, String nodeName, boolean trim) throws XPathExpressionException { Node node = getNode(parentNode, nodeName); if (node == null) return null; String txt = node.getTextContent(); if (txt == null) return null; return trim ? txt.trim() : txt; }
From source file:com.comcast.magicwand.spells.web.iexplore.IePhoenixDriver.java
/** * {@inheritDoc}/*from w w w. j a v a 2s.com*/ */ public boolean verify(PhoenixDriverIngredients i) { boolean rv = false; Map<String, Object> configs = i.getDriverConfigs(); LOGGER.debug("[version_property, arch_property] = [{}, {}]", (String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); IePlatformSpecifics ips = this.createIePlatformSpecifics((String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); if (!ips.isValid()) { LOGGER.error("The IePlatformSpecifics retrieved are not valid."); return false; } try { XPath xpath = XPathFactory.newInstance().newXPath(); String pwd = System.getProperty("user.dir"); String version = ips.getVersion(); String arch = ips.getArch(); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(IE_XML_DRIVER_LISTING_URL); NodeList nodes = (NodeList) xpath.evaluate(IE_XML_DRIVER_LISTING_XPATH, doc, XPathConstants.NODESET); String highestVersion = null; String needle = version + "/IEDriverServer_" + arch + "_"; for (int idx = 0; idx < nodes.getLength(); idx++) { Node n = nodes.item(idx); String text = n.getTextContent(); if (text.startsWith(needle)) { text = text.substring(needle.length(), text.length()); if (IePhoenixDriver.versionGreater(highestVersion, text)) { highestVersion = text; } } } if (null != highestVersion) { highestVersion = FilenameUtils.removeExtension(highestVersion); URL url = new URL(String.format(IE_HTTP_DRIVER_PATH_FORMAT, version, arch, highestVersion)); String zipName = String.format(IE_ZIP_FILE_FORMAT, arch, highestVersion); File ieSaveDir = new File(Paths.get(pwd, "target", "drivers", "iexplore", version).toString()); LOGGER.debug("Will read from \"{}\"", url); File zipFile = new File( Paths.get(pwd, "target", "drivers", "iexplore", version, zipName).toString()); FileUtils.copyURLToFile(url, zipFile); extract(zipFile, ieSaveDir.getAbsolutePath()); File exe = Paths.get(pwd, "target", "drivers", "iexplore", version, IE_EXE_FILE_NAME).toFile(); if (exe.exists()) { exe.setExecutable(true); systemSetProperty("webdriver.ie.driver", exe.getAbsolutePath()); this.webDriver = this.createDriver(i.getDriverCapabilities()); rv = true; } else { LOGGER.error("Extracted zip archive did nto contain \"{}\".", IE_EXE_FILE_NAME); } } else { LOGGER.error("Unable to find any IE Drivers from [{}]", IE_XML_DRIVER_LISTING_XPATH); } } catch (ParserConfigurationException | SAXException | XPathExpressionException err) { throw new RuntimeException(err); } catch (IOException ioe) { LOGGER.error("IO failure: {}", ioe); } return rv; }
From source file:com.openteach.diamond.service.route.WeightRuleParser.java
/** * ? config?????/*from www .ja v a2s. c om*/ * @param serviceUniqueName ??? * @param rule ?: * <service> * <name>com.*</name> * <ipweights> * <ipweight> * <ip></ip> * <weight></weight> * </ipweight> * </ipweights> * </service> * XXX TODO throw exception * @return * @throws RuleParseException */ public WeightRule parse(String rule) throws RuleParseException { if (StringUtils.isBlank(rule)) { // allowed empty weight rule of service return null; } InputStream stream = null; try { Document doc = null; try { stream = new ByteArrayInputStream(rule.getBytes()); doc = db.parse(stream); } catch (SAXException e) { throw new RuleParseException(String.format("Parse rule failed, wrong xml format, rule:%s", rule)); } catch (IOException e) { throw new RuleParseException("OMG, Not possible", e); } WeightRule w = new WeightRule(); Element root = doc.getDocumentElement(); NodeList nameNodeList = root.getElementsByTagName(NAME); if (null == nameNodeList || 1 != nameNodeList.getLength()) { throw new RuleParseException( String.format("Parse rule failed, rule must has only one <name> tag, rule:%s", rule)); } // name Node nameNode = nameNodeList.item(0); w.setServiceName(StringUtils.trim(nameNode.getTextContent())); if (StringUtils.isBlank(w.getServiceName())) { throw new RuleParseException( String.format("Parse rule failed, <name> tag must not be empty, rule:%s", rule)); } NodeList ipWeightsList = root.getElementsByTagName(IPWEIGHTS); if (null == ipWeightsList || ipWeightsList.getLength() != 1) { throw new RuleParseException( String.format("Parse rule failed, rule must has only one <ipweights> tag, rule:%s", rule)); } // ipweights Node ipWeightsNode = ipWeightsList.item(0); NodeList ipWeightNodeList = ipWeightsNode.getChildNodes(); if (null == ipWeightNodeList || 0 == ipWeightNodeList.getLength()) { throw new RuleParseException(String.format( "Parse rule failed, tag <ipweights> must has one or more child tag <ipweight>, rule:%s", rule)); } for (int i = 0; i < ipWeightNodeList.getLength(); i++) { String ip = null; String weight = null; Node ipWeightNode = ipWeightNodeList.item(i); NodeList ipAndWeightList = ipWeightNode.getChildNodes(); if (null == ipAndWeightList || 2 != ipAndWeightList.getLength()) { throw new RuleParseException(String.format( "Parse rule failed, tag <ipweight> must has only one child tag <ip> and only one <weight>, rule:%s", rule)); } for (int k = 0; k < ipAndWeightList.getLength(); k++) { Node ipAndWeightNode = ipAndWeightList.item(k); if (IP.equalsIgnoreCase(ipAndWeightNode.getNodeName())) { ip = ipAndWeightNode.getTextContent(); } else if (WEIGHT.equalsIgnoreCase(ipAndWeightNode.getNodeName())) { weight = ipAndWeightNode.getTextContent(); } } if (StringUtils.isBlank(ip) || StringUtils.isBlank(weight)) { throw new RuleParseException(String.format( "Parse rule failed, tag <ipweight> must has only one child tag <ip> and only one <weight>, rule:%s", rule)); } try { Integer tmp = Integer.valueOf(weight); if (tmp <= 0) { throw new RuleParseException(String .format("Parse rule failed, weight must be big then 0 integer, rule:%s", rule)); } w.addIPAndWeight(ip, tmp); } catch (NumberFormatException e) { throw new RuleParseException( String.format("Parse rule failed, weight must be big then 0 integer, rule:%s", rule)); } } return w; } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { //ignore } } } }
From source file:com.dmsl.anyplace.googleapi.GMapV2Direction.java
public ArrayList<LatLng> getDirection(Document doc) { NodeList nl1, nl2, nl3;//from ww w .j a va2s .c om ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>(); nl1 = doc.getElementsByTagName("step"); if (nl1.getLength() > 0) { for (int i = 0; i < nl1.getLength(); i++) { Node node1 = nl1.item(i); nl2 = node1.getChildNodes(); Node locationNode = nl2.item(getNodeIndex(nl2, "start_location")); nl3 = locationNode.getChildNodes(); Node latNode = nl3.item(getNodeIndex(nl3, "lat")); double lat = Double.parseDouble(latNode.getTextContent()); Node lngNode = nl3.item(getNodeIndex(nl3, "lng")); double lng = Double.parseDouble(lngNode.getTextContent()); listGeopoints.add(new LatLng(lat, lng)); locationNode = nl2.item(getNodeIndex(nl2, "polyline")); nl3 = locationNode.getChildNodes(); latNode = nl3.item(getNodeIndex(nl3, "points")); //ArrayList<LatLng> arr = decodePoly(latNode.getTextContent()); List<LatLng> arr = PolyUtil.decode(latNode.getTextContent()); for (int j = 0; j < arr.size(); j++) { listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude)); } locationNode = nl2.item(getNodeIndex(nl2, "end_location")); nl3 = locationNode.getChildNodes(); latNode = nl3.item(getNodeIndex(nl3, "lat")); lat = Double.parseDouble(latNode.getTextContent()); lngNode = nl3.item(getNodeIndex(nl3, "lng")); lng = Double.parseDouble(lngNode.getTextContent()); listGeopoints.add(new LatLng(lat, lng)); } } return listGeopoints; }
From source file:io.fabric8.tooling.archetype.builder.CatalogBuilder.java
/** * Starts generation of Archetype Catalog (see: http://maven.apache.org/xsd/archetype-catalog-1.0.0.xsd) * * @throws IOException/*from w ww . ja v a2 s . c o m*/ */ public void configure() throws IOException { if (archetypesPomFile != null) { archetypesPomArtifactIds = loadArchetypesPomArtifactIds(archetypesPomFile); } catalogXmlFile.getParentFile().mkdirs(); LOG.info("Writing catalog: " + catalogXmlFile); printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(catalogXmlFile), "UTF-8")); printWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<archetype-catalog xmlns=\"http://maven.apache.org/plugins/maven-archetype-plugin/archetype-catalog/1.0.0\"\n" + indent + indent + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + indent + indent + "xsi:schemaLocation=\"http://maven.apache.org/plugins/maven-archetype-plugin/archetype-catalog/1.0.0 http://maven.apache.org/xsd/archetype-catalog-1.0.0.xsd\">\n" + indent + "<archetypes>"); if (bomFile != null && bomFile.exists()) { // read all properties of the bom, so we have default values for ${ } placeholders String text = IOHelpers.readFully(bomFile); Document doc = archetypeUtils.parseXml(new InputSource(new StringReader(text))); Element root = doc.getDocumentElement(); // lets load all the properties defined in the <properties> element in the bom pom. NodeList propertyElements = root.getElementsByTagName("properties"); if (propertyElements.getLength() > 0) { Element propertyElement = (Element) propertyElements.item(0); NodeList children = propertyElement.getChildNodes(); for (int cn = 0; cn < children.getLength(); cn++) { Node e = children.item(cn); if (e instanceof Element) { versionProperties.put(e.getNodeName(), e.getTextContent()); } } } if (LOG.isDebugEnabled()) { for (Map.Entry<String, String> entry : versionProperties.entrySet()) { LOG.debug("bom property: {}={}", entry.getKey(), entry.getValue()); } } } }
From source file:fr.redteam.dressyourself.plugins.weather.yahooWeather.YahooWeatherUtils.java
private WeatherInfo parseWeatherInfo(Context context, Document doc) { WeatherInfo weatherInfo = new WeatherInfo(); try {/*from w w w .j a v a 2 s .c o m*/ Node titleNode = doc.getElementsByTagName("title").item(0); if (titleNode.getTextContent().equals(YAHOO_WEATHER_ERROR)) { return null; } weatherInfo.setTitle(titleNode.getTextContent()); weatherInfo.setDescription(doc.getElementsByTagName("description").item(0).getTextContent()); weatherInfo.setLanguage(doc.getElementsByTagName("language").item(0).getTextContent()); weatherInfo.setLastBuildDate(doc.getElementsByTagName("lastBuildDate").item(0).getTextContent()); Node locationNode = doc.getElementsByTagName("yweather:location").item(0); weatherInfo.setLocationCity(locationNode.getAttributes().getNamedItem("city").getNodeValue()); weatherInfo.setLocationRegion(locationNode.getAttributes().getNamedItem("region").getNodeValue()); weatherInfo.setLocationCountry(locationNode.getAttributes().getNamedItem("country").getNodeValue()); Node windNode = doc.getElementsByTagName("yweather:wind").item(0); weatherInfo.setWindChill(windNode.getAttributes().getNamedItem("chill").getNodeValue()); weatherInfo.setWindDirection(windNode.getAttributes().getNamedItem("direction").getNodeValue()); weatherInfo.setWindSpeed(windNode.getAttributes().getNamedItem("speed").getNodeValue()); Node atmosphereNode = doc.getElementsByTagName("yweather:atmosphere").item(0); weatherInfo .setAtmosphereHumidity(atmosphereNode.getAttributes().getNamedItem("humidity").getNodeValue()); weatherInfo.setAtmosphereVisibility( atmosphereNode.getAttributes().getNamedItem("visibility").getNodeValue()); weatherInfo .setAtmospherePressure(atmosphereNode.getAttributes().getNamedItem("pressure").getNodeValue()); weatherInfo.setAtmosphereRising(atmosphereNode.getAttributes().getNamedItem("rising").getNodeValue()); Node astronomyNode = doc.getElementsByTagName("yweather:astronomy").item(0); weatherInfo.setAstronomySunrise(astronomyNode.getAttributes().getNamedItem("sunrise").getNodeValue()); weatherInfo.setAstronomySunset(astronomyNode.getAttributes().getNamedItem("sunset").getNodeValue()); weatherInfo.setConditionTitle(doc.getElementsByTagName("title").item(2).getTextContent()); weatherInfo.setConditionLat(doc.getElementsByTagName("geo:lat").item(0).getTextContent()); weatherInfo.setConditionLon(doc.getElementsByTagName("geo:long").item(0).getTextContent()); Node currentConditionNode = doc.getElementsByTagName("yweather:condition").item(0); weatherInfo.setCurrentCode( Integer.parseInt(currentConditionNode.getAttributes().getNamedItem("code").getNodeValue())); weatherInfo.setCurrentText(currentConditionNode.getAttributes().getNamedItem("text").getNodeValue()); weatherInfo.setCurrentTempF( Integer.parseInt(currentConditionNode.getAttributes().getNamedItem("temp").getNodeValue())); weatherInfo.setCurrentConditionDate( currentConditionNode.getAttributes().getNamedItem("date").getNodeValue()); this.parseForecastInfo(weatherInfo.getForecastInfo1(), doc, 0); this.parseForecastInfo(weatherInfo.getForecastInfo2(), doc, 1); } catch (NullPointerException e) { e.printStackTrace(); Toast.makeText(context, "Parse XML failed - Unrecognized Tag", Toast.LENGTH_SHORT).show(); weatherInfo = null; } return weatherInfo; }
From source file:com.mirth.connect.donkey.server.data.jdbc.XmlQuerySource.java
public void load(String xmlFile) throws XmlQuerySourceException { Document document = null;//from w w w . j a va 2s .co m try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); InputStream is = ResourceUtil.getResourceStream(XmlQuerySource.class, xmlFile); document = documentBuilder.parse(is); IOUtils.closeQuietly(is); } catch (Exception e) { throw new XmlQuerySourceException("Failed to read query file: " + xmlFile, e); } NodeList queryNodes = document.getElementsByTagName("query"); int queryNodeCount = queryNodes.getLength(); for (int i = 0; i < queryNodeCount; i++) { Node node = queryNodes.item(i); if (node.hasAttributes()) { Attr attr = (Attr) node.getAttributes().getNamedItem("id"); if (attr != null) { String query = StringUtils.trim(node.getTextContent()); if (query.length() > 0) { queries.put(attr.getValue(), query); } } } } }
From source file:co.edu.uniajc.vtf.utils.GMapV2Direction.java
public ArrayList<DirectionsEntity> getDirection(Document doc) { NodeList nl1, nl2, nl3;//from w ww . ja va2 s . c o m ArrayList<DirectionsEntity> loListDirections = new ArrayList<DirectionsEntity>(); //format the data before to return it to the activity nl1 = doc.getElementsByTagName("step"); if (nl1.getLength() > 0) { for (int i = 0; i < nl1.getLength(); i++) { DirectionsEntity loDirectionPoint = new DirectionsEntity(); ArrayList<LatLng> loListGeopoints = new ArrayList<LatLng>(); Node node1 = nl1.item(i); nl2 = node1.getChildNodes(); Node locationNode = nl2.item(getNodeIndex(nl2, "start_location")); nl3 = locationNode.getChildNodes(); Node latNode = nl3.item(getNodeIndex(nl3, "lat")); double lat = Double.parseDouble(latNode.getTextContent()); Node lngNode = nl3.item(getNodeIndex(nl3, "lng")); double lng = Double.parseDouble(lngNode.getTextContent()); loListGeopoints.add(new LatLng(lat, lng)); locationNode = nl2.item(getNodeIndex(nl2, "polyline")); nl3 = locationNode.getChildNodes(); latNode = nl3.item(getNodeIndex(nl3, "points")); ArrayList<LatLng> arr = decodePoly(latNode.getTextContent()); for (int j = 0; j < arr.size(); j++) { loListGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude)); } locationNode = nl2.item(getNodeIndex(nl2, "end_location")); nl3 = locationNode.getChildNodes(); latNode = nl3.item(getNodeIndex(nl3, "lat")); lat = Double.parseDouble(latNode.getTextContent()); lngNode = nl3.item(getNodeIndex(nl3, "lng")); lng = Double.parseDouble(lngNode.getTextContent()); loListGeopoints.add(new LatLng(lat, lng)); loDirectionPoint.setGeopoint(loListGeopoints); Node loDataNode = null; locationNode = nl2.item(getNodeIndex(nl2, "duration")); nl3 = locationNode.getChildNodes(); loDataNode = nl3.item(getNodeIndex(nl3, "text")); loDirectionPoint.setDuration(loDataNode.getTextContent()); locationNode = nl2.item(getNodeIndex(nl2, "distance")); nl3 = locationNode.getChildNodes(); loDataNode = nl3.item(getNodeIndex(nl3, "text")); loDirectionPoint.setDistance(loDataNode.getTextContent()); locationNode = nl2.item(getNodeIndex(nl2, "html_instructions")); loDirectionPoint.setInstructions(locationNode.getTextContent()); loListDirections.add(loDirectionPoint); } } return loListDirections; }