List of usage examples for org.w3c.dom Node getTextContent
public String getTextContent() throws DOMException;
From source file:com.cloudbees.sdk.Bees.java
private void initialize(boolean force) throws Exception { LocalRepository localRepository = new LocalRepository(); String beesRepoPath = localRepository.getRepositoryPath(); File lastCheckFile = new File(beesRepoPath, CHECK_FILE); boolean checkVersion = true; Properties p = new Properties(); if (!force && Helper.loadProperties(lastCheckFile, p)) { String str = p.getProperty("last"); if (str != null) { long interval = System.currentTimeMillis() - Long.parseLong(str); if (interval < CHECK_INTERVAL) checkVersion = false;//w w w .ja v a2 s. com } } if (checkVersion) { // Check SDK version File sdkConfig = getURLAsFile(localRepository, app_template_xml_url + app_template_xml_name, app_template_xml_name, app_template_xml_desc); Document doc = XmlHelper.readXMLFromFile(sdkConfig.getCanonicalPath()); Element e = doc.getDocumentElement(); String availVersion = e.getAttribute("version"); String minVersion = e.getAttribute("min-version"); VersionNumber currentVersion = new VersionNumber(BOOTSTRAP_VERSION); VersionNumber availableVersion = new VersionNumber(availVersion); VersionNumber minimumVersion = new VersionNumber(minVersion); if (currentVersion.compareTo(availableVersion) < 0) { System.out.println(); if (currentVersion.compareTo(minimumVersion) < 0) { throw new AbortException("ERROR - This version of the CloudBees SDK is no longer supported," + "" + " please install the latest version (" + availVersion + ")."); } else if (currentVersion.compareTo(availableVersion) < 0) { System.out.println( "WARNING - A new version of the CloudBees SDK is available, please install the latest version (" + availVersion + ")."); } String hRef = e.getAttribute("href"); String homeRef = "www.cloudbees.com"; NodeList nodeList = e.getElementsByTagName("link"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); NamedNodeMap nodeMap = node.getAttributes(); Node rel = nodeMap.getNamedItem("rel"); Node href = nodeMap.getNamedItem("href"); if (rel != null && rel.getTextContent().trim().equalsIgnoreCase("alternate") && href != null) { homeRef = href.getTextContent(); } } NodeList libsNL = e.getElementsByTagName("libraries"); Node libsNode = null; if (libsNL.getLength() > 0) { libsNode = libsNL.item(0); } if (libsNode != null) { NodeList libNL = e.getElementsByTagName("library"); for (int i = 0; i < libNL.getLength(); i++) { Node node = libNL.item(i); NamedNodeMap nodeMap = node.getAttributes(); Node nameNode = nodeMap.getNamedItem("name"); Node refNode = nodeMap.getNamedItem("href"); if (nameNode != null && refNode != null) { String libName = nameNode.getTextContent(); String libUrlString = refNode.getTextContent().trim(); int idx = libUrlString.lastIndexOf('/'); String libFileName = libUrlString.substring(idx); localRepository.getURLAsFile(libUrlString, "lib1" + libFileName, libName); } } } System.out.println(" SDK home: " + homeRef); System.out.println(" SDK download: " + hRef); System.out.println(); } // Check plugins version NodeList pluginsNL = e.getElementsByTagName("plugins"); Node pluginsNode = null; if (pluginsNL.getLength() > 0) { pluginsNode = pluginsNL.item(0); } if (pluginsNode != null) { NodeList pluginNL = e.getElementsByTagName("plugin"); CommandServiceImpl service = (CommandServiceImpl) commandService; for (int i = 0; i < pluginNL.getLength(); i++) { Node node = pluginNL.item(i); NamedNodeMap nodeMap = node.getAttributes(); Node nameNode = nodeMap.getNamedItem("artifact"); if (nameNode != null) { Node n = nodeMap.getNamedItem("required"); boolean forceInstall = (n != null && Boolean.parseBoolean(n.getTextContent())); String pluginArtifact = nameNode.getTextContent(); GAV gav = new GAV(pluginArtifact); VersionNumber pluginVersion = new VersionNumber(gav.version); Plugin plugin = service.getPlugin(gav.artifactId); if (plugin != null) { forceInstall = false; GAV pgav = new GAV(plugin.getArtifact()); VersionNumber currentPluginVersion = new VersionNumber(pgav.version); if (currentPluginVersion.compareTo(pluginVersion) < 0) { Node nf = nodeMap.getNamedItem("force-upgrade"); boolean forced = (nf != null && Boolean.parseBoolean(nf.getTextContent())); if (forced) { forceInstall = true; } else { System.out.println(); System.out.println("WARNING - A newer version of the [" + gav.artifactId + "] plugin is available, please update with:"); System.out.println(" > bees plugin:update " + gav.artifactId); System.out.println(); } } } if (forceInstall) pluginsToInstallList.put(gav.artifactId, gav); } } } // Update last check p.setProperty("last", "" + System.currentTimeMillis()); lastCheckFile.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(lastCheckFile); p.store(fos, "CloudBees SDK check"); fos.close(); } }
From source file:com.websystique.springmvc.youtube_api.Function.java
@SuppressWarnings({ "static-access", "unchecked" }) private String printNote(NodeList nodeList) { List<VideoSub> listsub = new ArrayList<VideoSub>(); List<VideoSub> savelistsub = new ArrayList<VideoSub>(); for (int count = 0; count < nodeList.getLength(); count++) { VideoSub v = new VideoSub(); Node tempNode = nodeList.item(count); if (tempNode.getNodeType() == Node.ELEMENT_NODE) { v.setTextsb(replace_all(replacetext(tempNode.getTextContent().replace("...", ".")))); if (tempNode.hasAttributes()) { NamedNodeMap nodeMap = tempNode.getAttributes(); for (int i = 0; i < nodeMap.getLength(); i++) { Node node = nodeMap.item(i); if (i == 0) { v.setEnd(node.getNodeValue()); } else { v.setStart(node.getNodeValue()); }/*from w w w.j av a2s . com*/ } } } listsub.add(v); } String savetext = ""; double sodu = 0; double savedur = 0; String dutext = ""; double start = 0; String kq = ""; boolean flag = true;// vo lan dau boolean flagchamcuoi = false;// vo lan dau for (int i = 0; i < listsub.size(); i++) { String cau = listsub.get(i).getTextsb(); if (flag || flagchamcuoi == true) { start = Double.parseDouble(listsub.get(i).getStart()); savedur = Double.parseDouble(listsub.get(i).getEnd()); flag = false; flagchamcuoi = false; } double dur = Double.parseDouble(listsub.get(i).getEnd()); if (sodu != 0) { savetext += dutext; start = Double.parseDouble(listsub.get(i).getStart()); start -= sodu; System.out.println(sodu + "So du" + start); dutext = ""; sodu = 0; } if (cau.contains("####") == true) { float sogiay = (float) dur; float phantram = 0; int socau = 0; int sotu = demsotu(cau); String[] savecau = new String[100]; int[] savesotu = new int[1000]; double[] phantramsotu = new double[1000]; for (String retval : cau.split("####")) { // split("\\|;\\s*|\\.\\s*|\\?\\s*") if (retval != "" && retval.length() > 0) { savecau[socau] = retval; savesotu[socau] = (1 + StringUtils.countMatches(retval.trim(), " ")); double pt = 0.0; double so1 = (double) savesotu[socau]; double so2 = (double) sotu; pt = so1 / so2; phantramsotu[socau] = pt * sogiay; socau++; } } // ******************************* char[] array = cau.toCharArray(); // save cau 1 VideoSub cau1 = new VideoSub(); cau1.setTextsb((savetext + " " + savecau[0]).replace("\n", " ").replace("'", " ").trim()); cau1.setStart(start + ""); String end = (savedur + phantramsotu[0]) + ""; cau1.setEnd(end + ""); if (savecau[0] != ".") savelistsub.add(cau1); // add vao savetext = ""; // cap nhat start start += Double.parseDouble(cau1.getEnd()); savedur = 0; // save cau giua for (int i1 = 1; i1 < socau - 1; i1++) { // add vao VideoSub Cau2 = new VideoSub(); Cau2.setTextsb(savecau[i1].replace("\n", " ").replace("'", " ").trim()); Cau2.setStart(start + ""); Cau2.setEnd(phantramsotu[i1] + ""); if (savecau[i1] != ".") savelistsub.add(Cau2); start += phantramsotu[i1]; } // save cau cuoi if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == '?' || array[cau.length() - 5] == ';') { flagchamcuoi = true; } System.out.println(cau); if (array[cau.length() - 5] == '.' || array[cau.length() - 5] == ';' || array[cau.length() - 5] == '?') { if (socau - 1 != 0) { VideoSub Cau3 = new VideoSub(); Cau3.setTextsb(savecau[socau - 1].replace("\n", " ").replace("'", "-").trim()); Cau3.setStart(start + ""); Cau3.setEnd(phantramsotu[socau - 1] + ""); if (savecau[socau - 1] != ".") savelistsub.add(Cau3); start += phantramsotu[socau - 1]; } } else { dutext = savecau[socau - 1]; sodu = phantramsotu[socau - 1]; } } else { savetext += " " + cau; savedur += dur; } } // ================Xuat File Json=============== JSONArray jsonArray = new JSONArray(); for (int i = 0; i < savelistsub.size(); i++) { JSONObject obj = new JSONObject(); if (savelistsub.get(i).getTextsb() != ".") { String startadd = savelistsub.get(i).getStart(); String duradd = savelistsub.get(i).getEnd(); String textadd = savelistsub.get(i).getTextsb(); obj.put("start", startadd); obj.put("dur", duradd); obj.put("text", textadd); jsonArray.add(obj); } } String out_String = jsonArray.toJSONString(); out_String = out_String.toString(); // ================Xuat File Json=============== return out_String; }
From source file:org.epop.dataprovider.msacademic.MicrosoftAcademicSearch.java
private Literature extractPaper(Element element) { LiteratureBuilder litBuilder = new LiteratureBuilder(); URI pageURI = null;//from w ww.j a va2s.c om for (Element s : element.getAllElements(HTMLElementName.DIV)) { Attribute classAttr = s.getStartTag().getAttributes().get("class"); if (classAttr != null) { if (classAttr.getValue().equals("title-fullwidth") || classAttr.getValue().equals("title")) { String id = s.getStartTag().getAttributes().get("id").getValue().replace("divTitle", ""); for (Element a : s.getAllElements(HTMLElementName.A)) { // System.out.println(a.toString()); Attribute classAttr2 = a.getStartTag().getAttributes().get("id"); if (classAttr2 != null) { if (classAttr2.getValue().equals(id + "Title")) { Source htmlSource = new Source(a.getContent().toString()); String paperTitle = StringUtils .formatInLineSingleSpace(htmlSource.getTextExtractor().toString()); litBuilder.setTitle(paperTitle); String pageURLString = "http://academic.research.microsoft.com" + a.getAttributeValue("href").substring(2); if (litBuilder.getWebsiteURLs() == null) litBuilder.setWebsiteURLs(new HashSet<Link>()); try { pageURI = new URI(pageURLString); litBuilder.getWebsiteURLs().add(new Link("MS Academic", pageURI)); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } Matcher idMatcher = ID_PATTERN.matcher(pageURLString); if (idMatcher.find()) litBuilder.setMsAcademicID(idMatcher.group(1)); // else // TODO error handling } else if (classAttr2.getValue().equals(id + "Citation")) { Source htmlSource = new Source(a.getContent().toString()); String citedInfo = StringUtils.formatInLineSingleSpace( htmlSource.getTextExtractor().toString().replaceAll("Citations: ", "")); try { Integer numCitations = Integer.parseInt(citedInfo); litBuilder.setMsAcademicNumCitations(numCitations); } catch (NumberFormatException e) { // TODO error handling e.printStackTrace(); } } } } } else if (classAttr.getValue().equals("content")) { // authors String[] parts = s.getContent().toString().split("<span class=\"span-break\"\\s?>, </span>"); for (String part : parts) { AuthorBuilder authBuilder = new AuthorBuilder(); // ID Source htmlSource = new Source(part); if (htmlSource.getFirstElement("a") != null) { String authorURL = htmlSource.getFirstElement("a").getAttributeValue("href"); java.util.regex.Matcher m = AUTHOR_ID_PATTERN.matcher(authorURL); if (m.find()) { authBuilder.setMsAcademicID(m.group(1)); } else { // TODO feedback } } // name String nameString = htmlSource.getTextExtractor().toString(); try { Utils.setFirstMiddleLastNameFromNameString(authBuilder, nameString); if (litBuilder.getAuthors() == null) litBuilder.setAuthors(new HashSet<Author>()); litBuilder.getAuthors().add(authBuilder.getObject()); } catch (PatternMismatchException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else if (classAttr.getValue().equals("conference")) { Source htmlSource = new Source(s.getContent().toString()); if (htmlSource.getFirstElementByClass("conference-name") != null) litBuilder.setPublicationContext( htmlSource.getFirstElementByClass("conference-name").getTextExtractor().toString()); if (htmlSource.getFirstElement("span") != null) { String contextType = htmlSource.getFirstElement("span").getTextExtractor().toString(); if (contextType.equals("Journal:")) litBuilder.setType(LiteratureType.JOURNAL_PAPER); if (contextType.equals("Conference:")) litBuilder.setType(LiteratureType.CONFERENCE_PAPER); } for (Element q : s.getAllElements(HTMLElementName.SPAN)) { // System.out.println(q.toString()); Attribute classAttr3 = q.getStartTag().getAttributes().get("class"); if (classAttr3 != null && classAttr3.getValue().equals("year")) { htmlSource = new Source(q.getContent().toString()); String venueYearStr = StringUtils .formatInLineSingleSpace(htmlSource.getTextExtractor().toString()); venueYearStr = venueYearStr.substring(venueYearStr.lastIndexOf(",") + 1).trim(); Integer venueYear; try { venueYear = Integer.parseInt(venueYearStr); } catch (NumberFormatException ae) { venueYear = null; } litBuilder.setYear(venueYear); break; } // class="year" } } } } if (pageURI != null) { HTMLPage page; try { try { Thread.sleep(1861); } catch (InterruptedException e1) { e1.printStackTrace(); } page = new HTMLPage(pageURI); try { Node abstractTextNode = page.getNodeByXPath(".//div[@class='abstract']/span"); if (abstractTextNode != null) litBuilder.setAbstractText(abstractTextNode.getTextContent()); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { String doiString = page .getStringByXPath(".//*[@id='ctl00_MainContent_PaperItem_hypDOIText']/text()"); if (!doiString.isEmpty()) litBuilder.setDOI(doiString); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException | ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return litBuilder.getObject(); }
From source file:lv.semti.morphology.analyzer.Word.java
public Word(Node node) { if (node.getNodeName().equalsIgnoreCase("V?rds")) { NodeList nodes = node.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); if (n.getNodeName().equalsIgnoreCase("V?rdforma")) wordforms.add(new Wordform(n)); }// ww w. jav a2 s . c o m Node n = node.getAttributes().getNamedItem("v?rds"); if (n != null) token = n.getTextContent(); n = node.getAttributes().getNamedItem("pareiz?V?rdforma"); if (n != null) setCorrectWordform(wordforms.get(Integer.parseInt(n.getTextContent()))); } else if (node.getNodeName().equalsIgnoreCase("V?rdforma")) { token = node.getAttributes().getNamedItem("v?rds").getTextContent(); wordforms.add(new Wordform(node)); } else throw new Error("Node " + node.getNodeName() + " nav ne V?rds, ne V?rdforma"); }
From source file:com.rbmhtechnology.apidocserver.service.RepositoryService.java
private String getVersionRefFromMetadataXML(String groupId, String artifactId, MavenVersionRef versionRef) throws RepositoryException { LOG.info("getVersionRefFromMetadataXML('{}','{}','{}')", groupId, artifactId, versionRef); String version = null;/*from w ww. jav a 2s . c o m*/ File mavenMetadataXmlFile = downloadMavenMetadataXml(groupId, artifactId); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Using factory get an instance of document builder DocumentBuilder db; try { db = dbf.newDocumentBuilder(); // parse using builder to get DOM representation of the XML file Document dom = db.parse(mavenMetadataXmlFile); // get the root element Element rootElement = dom.getDocumentElement(); NodeList latestNodeList = rootElement.getElementsByTagName(versionRef.getXmlElementName()); if (latestNodeList.getLength() > 1) { throw new RepositoryException("Found more than one element '" + versionRef.getXmlElementName() + "' in maven-metadata.xml"); } else if (latestNodeList.getLength() == 1) { Node versionNode = latestNodeList.item(0); version = versionNode.getTextContent(); } else { throw new VersionNotFoundException("No " + versionRef + " version could be found for groupId: '" + groupId + "' and artifactId: '" + artifactId + "'"); } } catch (SAXException | IOException | ParserConfigurationException e) { throw new RepositoryException("Could not parse maven-metadata.xml for groupId: '" + groupId + "' and artifactId: '" + artifactId + "'", e); } return version; }
From source file:ru.itdsystems.alfresco.persistence.CrudPost.java
@Override public void execute(WebScriptRequest req, WebScriptResponse res) throws WebScriptException { // construct path elements array from request parameters List<String> pathElements = new ArrayList<String>(); Map<String, String> templateVars = req.getServiceMatch().getTemplateVars(); pathElements.add(templateVars.get("application_name")); pathElements.add(templateVars.get("form_name")); doBefore(pathElements, null);//from w w w . j av a 2 s . com // parse xml from request and perform a search Document searchXML; DocumentBuilder xmlBuilder; DocumentBuilderFactory xmlFact; try { xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true); xmlBuilder = xmlFact.newDocumentBuilder(); searchXML = xmlBuilder.parse(req.getContent().getInputStream()); } catch (Exception e) { throw new WebScriptException(500, "Error occured while parsing XML from request.", e); } XPath xpath = XPathFactory.newInstance().newXPath(); Integer pageSize; Integer pageNumber; String lang; // String applicationName; // String formName; NodeList queries; // extract search details try { pageSize = new Integer( ((Node) xpath.evaluate("/search/page-size/text()", searchXML, XPathConstants.NODE)) .getNodeValue()); pageNumber = new Integer( ((Node) xpath.evaluate("/search/page-number/text()", searchXML, XPathConstants.NODE)) .getNodeValue()); lang = ((Node) xpath.evaluate("/search/lang/text()", searchXML, XPathConstants.NODE)).getNodeValue(); // applicationName = ((Node) xpath.evaluate("/search/app/text()", // searchXML, XPathConstants.NODE)).getNodeValue(); // formName = ((Node) xpath.evaluate("/search/form/text()", // searchXML, // XPathConstants.NODE)).getNodeValue(); queries = (NodeList) xpath.evaluate("/search/query", searchXML, XPathConstants.NODESET); if (queries.getLength() == 0) throw new Exception("No queries found."); } catch (Exception e) { throw new WebScriptException(500, "XML in request is malformed.", e); } // check if requested query is supported if (!"".equals(queries.item(0).getTextContent())) throw new WebScriptException(500, "Freetext queries are not supported at the moment."); // resolve path to root data pathElements.add("data"); NodeRef nodeRef = getRootNodeRef(); // resolve path to file FileInfo fileInfo = null; Integer totalForms = 0; try { // fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements, false); fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements); } catch (FileNotFoundException e) { // do nothing here } if (fileInfo != null) { // iterate through all forms List<ChildAssociationRef> assocs = nodeService.getChildAssocs(fileInfo.getNodeRef()); List<String> details = new ArrayList<String>(); Document resultXML; try { resultXML = xmlBuilder.newDocument(); } catch (Exception e) { throw new WebScriptException(500, "Smth really strange happened o.O", e); } Element rootElement = resultXML.createElement("documents"); rootElement.setAttribute("page-size", pageSize.toString()); rootElement.setAttribute("page-number", pageNumber.toString()); rootElement.setAttribute("query", ""); resultXML.appendChild(rootElement); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"); int skip = pageSize * (pageNumber - 1); Integer found = 0; Integer searchTotal = 0; for (ChildAssociationRef assoc : assocs) { if ((nodeRef = nodeService.getChildByName(assoc.getChildRef(), ContentModel.ASSOC_CONTAINS, "data.xml")) != null) { // parse file Document dataXML; try { dataXML = xmlBuilder.parse(fileFolderService.getReader(nodeRef).getContentInputStream()); } catch (Exception e) { throw new WebScriptException(500, "Form file is malformed.", e); } totalForms++; details.clear(); xpath.setNamespaceContext(new OrbeonNamespaceContext()); // execute search queries for (int i = 1; i < queries.getLength(); i++) { Node query = queries.item(i); String path = query.getAttributes().getNamedItem("path").getNodeValue(); String match = query.getAttributes().getNamedItem("match").getNodeValue(); String queryString = query.getTextContent(); if (path == null || match == null || queryString == null) throw new WebScriptException(500, "Search query XML is malformed."); path = path.replace("$fb-lang", "'" + lang + "'"); boolean exactMatch = "exact".equals(match); Node queryResult; try { queryResult = (Node) xpath.evaluate(path, dataXML.getDocumentElement(), XPathConstants.NODE); } catch (Exception e) { throw new WebScriptException(500, "Error in query xpath expression.", e); } if (queryResult == null) break; String textContent = queryResult.getTextContent(); // TODO // check type while comparing values if (exactMatch && queryString.equals(textContent) || !exactMatch && textContent != null && textContent.contains(queryString) || queryString.isEmpty()) details.add(textContent); else break; } // add document to response xml if (details.size() == queries.getLength() - 1) { searchTotal++; if (skip > 0) skip--; else if (++found <= pageSize) { Element item = resultXML.createElement("document"); String createdText = dateFormat .format(fileFolderService.getFileInfo(nodeRef).getCreatedDate()); item.setAttribute("created", createdText.substring(0, 26) + ":" + createdText.substring(26)); String modifiedText = dateFormat .format(fileFolderService.getFileInfo(nodeRef).getModifiedDate()); item.setAttribute("last-modified", modifiedText.substring(0, 26) + ":" + modifiedText.substring(26)); item.setAttribute("name", fileFolderService.getFileInfo(assoc.getChildRef()).getName()); resultXML.getDocumentElement().appendChild(item); Element detailsElement = resultXML.createElement("details"); item.appendChild(detailsElement); for (String detail : details) { Element detailElement = resultXML.createElement("detail"); detailElement.appendChild(resultXML.createTextNode(detail)); detailsElement.appendChild(detailElement); } } /* * else break; */ } } } rootElement.setAttribute("total", totalForms.toString()); rootElement.setAttribute("search-total", searchTotal.toString()); // stream output to client try { TransformerFactory.newInstance().newTransformer().transform(new DOMSource(resultXML), new StreamResult(res.getOutputStream())); } catch (Exception e) { throw new WebScriptException(500, "Error occured while streaming output to client.", e); } } }
From source file:com.nanocrawler.contentparser.HtmlContentParser.java
private void getLinks(List<ExtractedUrlAnchorPair> outgoingUrls, Document doc, String elementName, String attribName, boolean getAnchorText) { if (doc.getElementsByTagName(elementName).getLength() > 0) { NodeList nl = doc.getElementsByTagName(elementName); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.hasAttributes() && n.getAttributes().getNamedItem(attribName) != null) { ExtractedUrlAnchorPair newUrl = new ExtractedUrlAnchorPair(); newUrl.setHref(n.getAttributes().getNamedItem(attribName).getNodeValue().trim()); if (getAnchorText) { newUrl.setAnchor(n.getTextContent().trim()); } else { newUrl.setAnchor(""); }/* www. j a v a 2 s. c o m*/ if (newUrl.getHref().trim().length() > 0) { outgoingUrls.add(newUrl); } } } } }
From source file:ca.itquality.patrol.util.weather.YahooWeather.java
private WeatherInfo parseWeatherInfo(Context context, Document doc) { WeatherInfo weatherInfo = new WeatherInfo(); try {// 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()); int curTempF = Integer .parseInt(currentConditionNode.getAttributes().getNamedItem("temp").getNodeValue()); int curTempC = YahooWeather.turnFtoC(curTempF); weatherInfo.setCurrentTemp(mUnit == UNIT.CELSIUS ? curTempC : curTempF); weatherInfo.setCurrentConditionDate( currentConditionNode.getAttributes().getNamedItem("date").getNodeValue()); if (mNeedDownloadIcons) { weatherInfo.setCurrentConditionIcon( ImageUtils.getBitmapFromWeb(weatherInfo.getCurrentConditionIconURL())); } for (int i = 0; i < FORECAST_INFO_MAX_SIZE; i++) { this.parseForecastInfo(weatherInfo.getForecastInfoList().get(i), doc, i); } } catch (NullPointerException e) { YahooWeatherLog.printStack(e); if (mExceptionListener != null) mExceptionListener.onFailParsing(e); weatherInfo = null; } return weatherInfo; }
From source file:org.openxdata.server.export.CSVDataExport.java
/** * Writes data, collected for a particular form version, to a stream in a CSV format. * /*from w ww. j av a2 s . c o m*/ * @param printWriter the stream to write the data. * @param formId the unique identifier of the form version whose data we are to export. This should never be null. * @param fromDate the data submission date from which start the export. Supply null to include all dates. * @param toDate the data submission date to which to end the export. Supply null to include all dates * @param userId the user who submitted the data. Supply null to export data for all users. */ @Override public void export(PrintWriter printWriter, Integer formId, Date fromDate, Date toDate, Integer userId) { //Check to ensure that we have such a form version as identified by the formId. FormDefVersion formDefVersion = dataExportService.getFormDefVersion(formId); if (formDefVersion == null) return; //Get the list of xforms xml models to export. List<Object[]> data = dataExportService.getFormDataWithAuditing(formId, fromDate, toDate, userId); if (data == null || data.size() == 0) return; Document doc = XmlUtil.fromString2Doc(formDefVersion.getXform()); //Get GPS and multimedia field names. List<String> gpsFields = new ArrayList<String>(); List<String> multimediaFields = getMultimediaFields(doc, gpsFields); Map<String, List<String>> multSelOptions = new HashMap<String, List<String>>(); List<String> multSelFields = getMultSelFields(doc, multSelOptions); //Get and write the CSV header. Object[] initial = data.get(0); String header = (String) initial[3]; String line = "ID,CAPTURER,CREATION DATE,"; line += getHeader(header, multimediaFields, gpsFields, multSelFields, multSelOptions).toUpperCase();//"Concept Id,Name,Description,Synonyms,Answers,Class,Datatype,Changed By,Creator\n"; printWriter.write(line + "\n"); SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); for (Object obs : data) { line = ""; Object[] o = (Object[]) obs; String userName = (String) o[1]; Date dateCreated = (Date) o[2]; String xml = (String) o[3]; NodeList nodes = XmlUtil.fromString2Doc(xml).getDocumentElement().getChildNodes(); line = o[0] + "," + userName.toUpperCase() + "," + df.format(dateCreated).toUpperCase(); for (int index = 0; index < nodes.getLength(); index++) { Node node = nodes.item(index); if (node.getNodeType() != Node.ELEMENT_NODE) continue; //As for now we do not export multimedia field values. if (multimediaFields.contains(node.getNodeName())) continue; String value = node.getTextContent(); //If a GPS field, split it into its various pieces (latitude, longitude and altitude) if (gpsFields.contains(node.getNodeName())) line = "," + addGPSValues(line, value); else if (multSelFields.contains(node.getNodeName())) line = "," + addMultSelValues(line, value, multSelOptions.get(node.getNodeName())); else line += "," + '"' + formatCSV(value) + '"'; } printWriter.write(line + "\n"); } }
From source file:de.codesourcery.jasm16.ide.ProjectConfiguration.java
private List<String> getValues(XPathExpression expr, Document doc) throws XPathExpressionException { final NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); final List<String> result = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { final Node node = nodes.item(i); final String value = node.getTextContent(); if (value == null || StringUtils.isBlank(value)) { LOG.error("getValues(): Invalid project XML - blank/empty value"); throw new XPathExpressionException( "Invalid project XML - blank/empty value for " + " expression " + expr); }/*w w w. j av a 2 s . com*/ result.add(value.trim()); } return result; }