List of usage examples for org.w3c.dom Node getTextContent
public String getTextContent() throws DOMException;
From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java
private List<NZB> fetchFeed(Collection<NameValuePair> params) throws SearchException, DOMException { THROTTLER.throttle();// w w w . j a v a 2 s. c o m Document document = null; try { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.addAll(params); qparams.add(new BasicNameValuePair("dl", "1")); URI uri = getUri("rss.php", qparams); synchronized (builderSemaphore) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); int attempts = RETRY_ATTEMPTS; boolean retry; do try { retry = false; document = builder.parse(uri.toString()); } catch (IOException ioe) { if (attempts == 0 || !ioe.getMessage().startsWith("Server returned HTTP response code: 503")) { throw ioe; } else { attempts--; retry = true; THROTTLER.throttleBig(); } } while (retry); } } catch (IOException ioe) { throw new SearchException("Error connecting to Nzbs.org.", ioe); } catch (SAXException se) { throw new SearchException("Error parsing rss from Nzbs.org.", se); } catch (ParserConfigurationException pce) { throw new SearchException("Error configuring XML parser.", pce); } catch (URISyntaxException e) { throw new SearchException("Error parsing URI.", e); } Node rss = document.getFirstChild(); if (!"rss".equalsIgnoreCase(rss.getNodeName())) { throw new SearchException("Result was not RSS but " + rss.getNodeName()); } Node channel = rss.getFirstChild(); while (channel != null && "#text".equals(channel.getNodeName())) { channel = channel.getNextSibling(); } NodeList list = channel.getChildNodes(); DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.CANADA); List<NZB> result = new ArrayList<NZB>(); UrlBasedSupplier supplier = new UrlBasedSupplier(); supplier.setThrottler(THROTTLER); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); if ("item".equals(n.getNodeName())) { LazyNZB nzb = new LazyNZB("tmpName", supplier); try { for (int j = 0; j < n.getChildNodes().getLength(); j++) { Node n2 = n.getChildNodes().item(j); if ("title".equalsIgnoreCase(n2.getNodeName())) { nzb.setName(n2.getTextContent()); nzb.setFilename(Util.saveFileName(n2.getTextContent()) + ".nzb"); } if ("pubdate".equalsIgnoreCase(n2.getNodeName())) { nzb.setPostDate(df.parse(n2.getTextContent())); } if ("link".equalsIgnoreCase(n2.getNodeName())) { nzb.setUrl(n2.getTextContent()); } } result.add(nzb); } catch (ParseException e) { LOG.info("Skipping " + nzb.getName() + " because of date error.", e); } } } THROTTLER.setThrottleForNextAction(); return result; }
From source file:sce.RESTAppMetricJob.java
public static String parseKBResponse(Node node, JobExecutionContext context) throws JobExecutionException { String result = ""; try {/*from w ww . j a va 2 s . c om*/ String parentNodeName = node.getParentNode().getNodeName(); Node parentNodeAttribute = node.getParentNode().getAttributes() != null ? node.getParentNode().getAttributes().getNamedItem("name") : null; String parentParentNodeName = node.getParentNode().getParentNode() != null ? node.getParentNode().getParentNode().getNodeName() : ""; if (/*node.getNodeName().equals("literal") &&*/parentNodeName.equals("binding") && parentNodeAttribute != null && parentParentNodeName.equals("result")) { result += "\n" + node.getNodeName() + ": " + node.getTextContent() + " " + node.getParentNode().getAttributes().getNamedItem("name").getTextContent(); context.setResult(context.getResult() != null ? context.getResult() + result : result); //createAndExecuteJob(node.getTextContent()); } NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node currentNode = nodeList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { //calls this method for all the children which is Element parseKBResponse(currentNode, context); } } return result; } catch (DOMException | JobExecutionException e) { e.printStackTrace(); throw new JobExecutionException(e); } }
From source file:org.openmrs.module.sync.web.controller.ViewRecordController.java
@SuppressWarnings("unchecked") @RequestMapping(value = "/module/sync/viewrecord", method = RequestMethod.GET) public void showThePage(ModelMap modelMap, HttpServletRequest request, @RequestParam String uuid, @RequestParam(value = "action", required = false) String action) throws Exception { // default empty Object SyncRecord record = null;/* ww w . j a va2s . com*/ SyncRecord previousRecord = null; SyncRecord nextRecord = null; // only fill the Object if the user has authenticated properly if (Context.isAuthenticated()) { SyncService syncService = Context.getService(SyncService.class); record = syncService.getSyncRecord(uuid); if (record != null) { previousRecord = syncService.getPreviousRecord(record); nextRecord = syncService.getNextRecord(record); if ("reset".equals(action)) { record.setRetryCount(0); record.setState(SyncRecordState.NEW); for (SyncServerRecord serverRecord : record.getServerRecords()) { serverRecord.setState(SyncRecordState.NEW); } syncService.updateSyncRecord(record); } else if ("remove".equals(action)) { record.setRetryCount(0); record.setState(SyncRecordState.NOT_SUPPOSED_TO_SYNC); for (SyncServerRecord serverRecord : record.getServerRecords()) { serverRecord.setState(SyncRecordState.NOT_SUPPOSED_TO_SYNC); } syncService.updateSyncRecord(record); } List<SyncItem> syncItems = new ArrayList<SyncItem>(); Map<Object, String> itemTypes = new HashMap<Object, String>(); Map<Object, String> itemUuids = new HashMap<Object, String>(); if (record != null) { String mainClassName = null; String mainuuid = null; String mainState = null; for (SyncItem item : record.getItems()) { String syncItem = item.getContent(); syncItems.add(item); if (mainState == null) mainState = item.getState().toString(); Record xml = Record.create(syncItem); Item root = xml.getRootItem(); String className = root.getNode().getNodeName().substring("org.openmrs.".length()); itemTypes.put(item.getKey().getKeyValue(), className); if (mainClassName == null) mainClassName = className; // String itemInfoKey = itemInfoKeys.get(className); // now we have to go through the item child nodes to find the // real uuid that we want NodeList nodes = root.getNode().getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); String propName = n.getNodeName(); if (propName.equalsIgnoreCase("uuid")) { String tmpuuid = n.getTextContent(); itemUuids.put(item.getKey().getKeyValue(), tmpuuid); if (mainuuid == null) mainuuid = tmpuuid; } } } String displayName = ""; try { displayName = SyncUtil.displayName(mainClassName, mainuuid); } catch (Exception e) { // some methods like Concept.getName() throw Exception s all the // time... displayName = ""; } modelMap.put("displayName", displayName); modelMap.put("mainClassName", mainClassName); modelMap.put("mainState", mainState); } modelMap.put("nextRecord", nextRecord); modelMap.put("previousRecord", previousRecord); modelMap.put("record", record); modelMap.put("syncItems", syncItems); modelMap.put("itemsNumber", syncItems.size()); modelMap.put("itemTypes", itemTypes); modelMap.put("itemuuids", itemUuids); modelMap.put("syncDateDisplayFormat", TimestampNormalizer.DATETIME_DISPLAY_FORMAT); } } }
From source file:eu.esdihumboldt.hale.io.geoserver.rest.ResourceManagerIT.java
@Test public void testDataStoreManager() throws Exception { DataStoreManager dsMgr = createDataStoreManager(); // create datastore URL url = dsMgr.create();/*from w w w .j a va 2 s . c o m*/ assertNotNull(url); assertTrue(dsMgr.exists()); Document listDoc = dsMgr.list(); assertEquals("dataStores", listDoc.getDocumentElement().getNodeName()); NodeList dataStoreNodes = listDoc.getElementsByTagName("dataStore"); assertEquals(1, dataStoreNodes.getLength()); NodeList dataStoreChildren = dataStoreNodes.item(0).getChildNodes(); for (int i = 0; i < dataStoreChildren.getLength(); i++) { Node child = dataStoreChildren.item(i); if ("name".equals(child.getNodeName())) { assertEquals(APP_SCHEMA_DATASTORE, child.getTextContent()); break; } } }
From source file:DOMDump.java
private static void dumpLoop(Node node, String indent) { switch (node.getNodeType()) { case Node.CDATA_SECTION_NODE: System.out.println(indent + "CDATA_SECTION_NODE"); break;//from www . j a va2s .c o m case Node.COMMENT_NODE: System.out.println(indent + "COMMENT_NODE"); break; case Node.DOCUMENT_FRAGMENT_NODE: System.out.println(indent + "DOCUMENT_FRAGMENT_NODE"); break; case Node.DOCUMENT_NODE: System.out.println(indent + "DOCUMENT_NODE"); break; case Node.DOCUMENT_TYPE_NODE: System.out.println(indent + "DOCUMENT_TYPE_NODE"); break; case Node.ELEMENT_NODE: System.out.println(indent + "ELEMENT_NODE"); break; case Node.ENTITY_NODE: System.out.println(indent + "ENTITY_NODE"); break; case Node.ENTITY_REFERENCE_NODE: System.out.println(indent + "ENTITY_REFERENCE_NODE"); break; case Node.NOTATION_NODE: System.out.println(indent + "NOTATION_NODE"); break; case Node.PROCESSING_INSTRUCTION_NODE: System.out.println(indent + "PROCESSING_INSTRUCTION_NODE"); break; case Node.TEXT_NODE: System.out.print(indent + "TEXT_NODE"); System.out.println(" : " + node.getTextContent()); break; default: System.out.println(indent + "Unknown node"); break; } NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { dumpLoop(list.item(i), indent + " "); } }
From source file:hudson.plugins.plot.XMLSeries.java
/*** * This is a fallback strategy for nodesets that include non numeric content * enabling users to create lists by selecting them such that names and * values share a common parent. If a node has attributes and is empty that * node will be re-enqueued as a parent to its attributes. * /* ww w.j a va 2 s .com*/ * @param buildNumber * the build number * * @returns a list of PlotPoints where the label is the last non numeric * text content and the value is the last numeric text content for * each set of nodes under a given parent. ***/ private List<PlotPoint> coalesceTextnodesAsLabelsStrategy(NodeList nodeList, int buildNumber) { Map<Node, List<Node>> parentNodeMap = new HashMap<Node, List<Node>>(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (!parentNodeMap.containsKey(node.getParentNode())) { parentNodeMap.put(node.getParentNode(), new ArrayList<Node>()); } parentNodeMap.get(node.getParentNode()).add(node); } List<PlotPoint> retval = new ArrayList<PlotPoint>(); Queue<Node> parents = new ArrayDeque<Node>(parentNodeMap.keySet()); while (!parents.isEmpty()) { Node parent = parents.poll(); Double value = null; String label = null; for (Node child : parentNodeMap.get(parent)) { if (null == child.getTextContent() || child.getTextContent().trim().isEmpty()) { NamedNodeMap attrmap = child.getAttributes(); List<Node> attrs = new ArrayList<Node>(); for (int i = 0; i < attrmap.getLength(); i++) { attrs.add(attrmap.item(i)); } parentNodeMap.put(child, attrs); parents.add(child); } else if (new Scanner(child.getTextContent().trim()).hasNextDouble()) { value = new Scanner(child.getTextContent().trim()).nextDouble(); } else { label = child.getTextContent().trim(); } } if ((label != null) && (value != null)) { addValueToList(retval, new String(label), String.valueOf(value), buildNumber); } } return retval; }
From source file:com.YahooWeather.utils.YahooWeatherUtils.java
private WeatherInfo parseWeatherInfo(Context context, Document doc) { WeatherInfo weatherInfo = new WeatherInfo(); try {/*from ww w. j a va2 s .c o m*/ Node titleNode = doc.getElementsByTagName("title").item(0); if (titleNode.getTextContent().equals(YAHOO_WEATHER_ERROR)) { return null; } weatherInfo.setWeatherurl(doc.getElementsByTagName("link").item(0).getTextContent()); 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()); Node forecast1ConditionNode = doc.getElementsByTagName("yweather:forecast").item(0); weatherInfo.setForecast1Code( Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("code").getNodeValue())); weatherInfo .setForecast1Text(forecast1ConditionNode.getAttributes().getNamedItem("text").getNodeValue()); weatherInfo .setForecast1Date(forecast1ConditionNode.getAttributes().getNamedItem("date").getNodeValue()); weatherInfo.setForecast1Day(forecast1ConditionNode.getAttributes().getNamedItem("day").getNodeValue()); weatherInfo.setForecast1TempHighF( Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("high").getNodeValue())); weatherInfo.setForecast1TempLowF( Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("low").getNodeValue())); Node forecast2ConditionNode = doc.getElementsByTagName("yweather:forecast").item(1); weatherInfo.setForecast2Code( Integer.parseInt(forecast2ConditionNode.getAttributes().getNamedItem("code").getNodeValue())); weatherInfo .setForecast2Text(forecast2ConditionNode.getAttributes().getNamedItem("text").getNodeValue()); weatherInfo .setForecast2Date(forecast2ConditionNode.getAttributes().getNamedItem("date").getNodeValue()); weatherInfo.setForecast2Day(forecast2ConditionNode.getAttributes().getNamedItem("day").getNodeValue()); weatherInfo.setForecast2TempHighF( Integer.parseInt(forecast2ConditionNode.getAttributes().getNamedItem("high").getNodeValue())); weatherInfo.setForecast2TempLowF( Integer.parseInt(forecast2ConditionNode.getAttributes().getNamedItem("low").getNodeValue())); Node forecast3ConditionNode = doc.getElementsByTagName("yweather:forecast").item(2); weatherInfo.setForecast3Code( Integer.parseInt(forecast3ConditionNode.getAttributes().getNamedItem("code").getNodeValue())); weatherInfo .setForecast3Text(forecast3ConditionNode.getAttributes().getNamedItem("text").getNodeValue()); weatherInfo .setForecast3Date(forecast3ConditionNode.getAttributes().getNamedItem("date").getNodeValue()); weatherInfo.setForecast3Day(forecast3ConditionNode.getAttributes().getNamedItem("day").getNodeValue()); weatherInfo.setForecast3TempHighF( Integer.parseInt(forecast3ConditionNode.getAttributes().getNamedItem("high").getNodeValue())); weatherInfo.setForecast3TempLowF( Integer.parseInt(forecast3ConditionNode.getAttributes().getNamedItem("low").getNodeValue())); Node forecast4ConditionNode = doc.getElementsByTagName("yweather:forecast").item(3); weatherInfo.setForecast4Code( Integer.parseInt(forecast4ConditionNode.getAttributes().getNamedItem("code").getNodeValue())); weatherInfo .setForecast4Text(forecast4ConditionNode.getAttributes().getNamedItem("text").getNodeValue()); weatherInfo .setForecast4Date(forecast4ConditionNode.getAttributes().getNamedItem("date").getNodeValue()); weatherInfo.setForecast4Day(forecast4ConditionNode.getAttributes().getNamedItem("day").getNodeValue()); weatherInfo.setForecast4TempHighF( Integer.parseInt(forecast4ConditionNode.getAttributes().getNamedItem("high").getNodeValue())); weatherInfo.setForecast4TempLowF( Integer.parseInt(forecast4ConditionNode.getAttributes().getNamedItem("low").getNodeValue())); Node forecast5ConditionNode = doc.getElementsByTagName("yweather:forecast").item(4); weatherInfo.setForecast5Code( Integer.parseInt(forecast5ConditionNode.getAttributes().getNamedItem("code").getNodeValue())); weatherInfo .setForecast5Text(forecast5ConditionNode.getAttributes().getNamedItem("text").getNodeValue()); weatherInfo .setForecast5Date(forecast5ConditionNode.getAttributes().getNamedItem("date").getNodeValue()); weatherInfo.setForecast5Day(forecast5ConditionNode.getAttributes().getNamedItem("day").getNodeValue()); weatherInfo.setForecast5TempHighF( Integer.parseInt(forecast5ConditionNode.getAttributes().getNamedItem("high").getNodeValue())); weatherInfo.setForecast5TempLowF( Integer.parseInt(forecast5ConditionNode.getAttributes().getNamedItem("low").getNodeValue())); } 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.tibco.businessworks6.sonar.plugin.source.XmlSource.java
/** * @param rule/*from w ww. j av a 2 s. c o m*/ * @param node * @param message * @return */ public List<Violation> getViolationsHardCodedNode(Rule rule, Node node, String message) { List<Violation> violations = new ArrayList<Violation>(); if (node.getTextContent() == null || node.getTextContent().isEmpty()) { violations.add(new DefaultViolation(rule, getLineForNode(node), message + " (empty)")); } else { /*if(!GvHelper.isGVReference(node.getTextContent())){ violations.add(new DefaultViolation(rule, getLineForNode(node), message)); }*/ } return violations; }
From source file:org.apache.solr.kelvin.responseanalyzers.LegacyResponseAnalyzer.java
public void decode(Map<String, Object> previousResponses) throws Exception { ObjectMapper mapper = new ObjectMapper(); ArrayNode response = mapper.createArrayNode(); if (!previousResponses.containsKey(XmlResponseAnalyzer.XML_DOM)) { previousResponses.put(XmlDoclistExtractorResponseAnalyzer.DOC_LIST, response); //empty return;/*from w ww . java 2 s . c om*/ } NodeList nodeList = (NodeList) expr.evaluate((Document) previousResponses.get(XmlResponseAnalyzer.XML_DOM), XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node doc = nodeList.item(i); ObjectNode oDoc = mapper.createObjectNode(); Node subel = doc.getFirstChild(); while (subel != null) { String localName = subel.getNodeName(); if (localName == "field") { String fieldName = subel.getAttributes().getNamedItem("name").getNodeValue(); if (!"infoold".equals(fieldName)) { String value = subel.getTextContent(); oDoc.put(fieldName, value); } } else if (localName == "slug_preferenziale") { NodeList slugNodes = subel.getChildNodes(); oDoc.put("slug_preferenziale", slugNodes.item(slugNodes.getLength() - 1).getAttributes() .getNamedItem("path").getTextContent()); } subel = subel.getNextSibling(); } response.add(oDoc); } previousResponses.put(XmlDoclistExtractorResponseAnalyzer.DOC_LIST, response); }
From source file:com.jaeksoft.searchlib.Client.java
public int deleteXmlDocuments(Node xmlDoc, int bufferSize, InfoCallback infoCallBack) throws XPathExpressionException, NoSuchAlgorithmException, IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { List<Node> deleteNodeList = DomUtils.getNodes(xmlDoc, "index", "delete"); Collection<String> deleteList = new ArrayList<String>(bufferSize); int deleteCount = 0; final int totalCount = deleteNodeList.size(); for (Node deleteNode : deleteNodeList) { List<Node> uniqueKeyNodeList = DomUtils.getNodes(deleteNode, "uniquekey"); for (Node uniqueKeyNode : uniqueKeyNodeList) { deleteList.add(uniqueKeyNode.getTextContent()); if (deleteList.size() == bufferSize) deleteCount = deleteUniqueKeyList(totalCount, deleteCount, deleteList, infoCallBack); }/*w w w. ja v a2 s. c o m*/ } if (deleteList.size() > 0) deleteCount = deleteUniqueKeyList(totalCount, deleteCount, deleteList, infoCallBack); return deleteCount; }