List of usage examples for org.w3c.dom Document getFirstChild
public Node getFirstChild();
From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java
/** * Creates the export study response./*from w ww . ja v a2s .c o m*/ * * @param study the study * @return the sOAP message * @throws SOAPException the sOAP exception * @throws XMLUtilityException the xML utility exception * @throws ParserConfigurationException the parser configuration exception * @throws SAXException the sAX exception * @throws IOException Signals that an I/O exception has occurred. */ private SOAPMessage createExportStudyResponse(Study study) throws SOAPException, XMLUtilityException, ParserConfigurationException, SAXException, IOException { MessageFactory mf = MessageFactory.newInstance(); SOAPMessage response = mf.createMessage(); SOAPBody body = response.getSOAPBody(); SOAPElement exportStudyResponse = body.addChildElement(new QName(SERVICE_NS, "ExportStudyResponse")); String xml = marshaller.toXML(study); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) .newSchema(XmlMarshaller.class.getResource(C3PR_DOMAIN_XSD_URL))); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(xml)); Element studyEl = (Element) doc.getFirstChild(); exportStudyResponse.appendChild(body.getOwnerDocument().importNode(studyEl, true)); response.saveChanges(); return response; }
From source file:com.mnxfst.testing.client.TSClientPlanResultCollectCallable.java
/** * TODO TEST!!!/*from w ww . j av a 2 s . c o m*/ * @see java.util.concurrent.Callable#call() */ public TSClientPlanExecutionResult call() throws Exception { InputStream ptestServerInputStream = null; try { HttpResponse response = httpClient.execute(httpHost, getMethod); ptestServerInputStream = response.getEntity().getContent(); XPath xpath = XPathFactory.newInstance().newXPath(); Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(ptestServerInputStream); if (response == null) throw new TSClientExecutionException( "No response document received from " + httpHost.getHostName()); // fetch root node Node rootNode = responseDoc.getFirstChild(); if (rootNode == null) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); if (rootNode.getNodeName() == null || !rootNode.getNodeName().equalsIgnoreCase(TEST_EXEC_RESPONSE_ROOT)) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); int responseCode = parseIntValue(rootNode, TEST_EXEC_RESPONSE_CODE, xpath); String resultIdentifier = parseStringValue(rootNode, TEST_EXEC_RESULT_IDENTIFIER, xpath); switch (responseCode) { case RESPONSE_CODE_EXECUTION_RESULTS_PENDING: { TSClientPlanExecutionResult planExecutionResult = new TSClientPlanExecutionResult(); planExecutionResult.setResponseCode(RESPONSE_CODE_EXECUTION_RESULTS_PENDING); planExecutionResult.setResultIdentifier(resultIdentifier); planExecutionResult.setHostName(httpHost.getHostName()); planExecutionResult.setPort(httpHost.getPort()); return planExecutionResult; } case RESPONSE_CODE_EXECUTION_RESULTS_CONTAINED: { long averageDuration = parseLongValue(rootNode, TEST_EXEC_AVERAGE_DURATION, xpath); double averageDurationMedian = parseDoubleValue(rootNode, TEST_EXEC_AVERAGE_MEDIAN, xpath); long endTimestamp = parseLongValue(rootNode, TEST_EXEC_END, xpath); long startTimestamp = parseLongValue(rootNode, TEST_EXEC_START, xpath); int errors = parseIntValue(rootNode, TEST_EXEC_ERRORS, xpath); String executionEnvironmentId = parseStringValue(rootNode, TEST_EXEC_ENVIRONMENT, xpath); long singleAverageDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_AVERAGE_DURATION, xpath); long singleMaxDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_MAX_DURATION, xpath); long singleMinDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_MIN_DURATION, xpath); String testPlan = parseStringValue(rootNode, TEST_EXEC_TEST_PLAN, xpath); TSClientPlanExecutionResult planExecutionResult = new TSClientPlanExecutionResult(); planExecutionResult.setResponseCode(RESPONSE_CODE_EXECUTION_RESULTS_PENDING); planExecutionResult.setResultIdentifier(resultIdentifier); planExecutionResult.setHostName(httpHost.getHostName()); planExecutionResult.setPort(httpHost.getPort()); planExecutionResult.setAverageDuration(averageDuration); planExecutionResult.setAverageDurationMedian(averageDurationMedian); planExecutionResult.setEndTimestamp(endTimestamp); planExecutionResult.setErrors(errors); planExecutionResult.setExecutionEnvironmentId(executionEnvironmentId); planExecutionResult.setSingleAverageDuration(singleAverageDuration); planExecutionResult.setSingleMaxDuration(singleMaxDuration); planExecutionResult.setSingleMinDuration(singleMinDuration); planExecutionResult.setStartTimestamp(startTimestamp); planExecutionResult.setTestPlan(testPlan); return planExecutionResult; } default: { throw new TSClientExecutionException("Unexpected response code '" + responseCode + "' received from " + httpHost.getHostName() + ":" + httpHost.getPort()); } } } catch (ClientProtocolException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + getMethod.getURI() + ". Error: " + e.getMessage()); } catch (IOException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + getMethod.getURI() + ". Error: " + e.getMessage()); } finally { if (ptestServerInputStream != null) { try { ptestServerInputStream.close(); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { System.out.println("Failed to close ptest-server connection"); } } } }
From source file:com.wandrell.example.swss.test.util.test.integration.endpoint.AbstractITEndpoint.java
/** * Tests that the WSDL contains the correct SOAP address. * * @throws ParserConfigurationException/*from www.j a v a 2 s. co m*/ * never, this is a required declaration * @throws SAXException * never, this is a required declaration * @throws IOException * never, this is a required declaration * @throws XPathExpressionException * never, this is a required declaration */ @Test public final void testEndpoint_WSDL_ValidSOAPAddress() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { final DocumentBuilderFactory factory; // Factory for the // DocumentBuilder final DocumentBuilder builder; // Document builder final Document doc; // Document for the WSDL final Node serviceNode; // WSDL service node final Node portNode; // WSDL port node final Node addressNode; // WSDL address node // Creates the document factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); builder = factory.newDocumentBuilder(); doc = builder.parse(new URL(wsdlURL).openStream()); serviceNode = getChild((Element) doc.getFirstChild(), "wsdl:service"); portNode = getChild((Element) serviceNode, "wsdl:port"); addressNode = getChild((Element) portNode, "soap:address"); Assert.assertEquals(((Element) addressNode).getAttribute("location"), wsURL); }
From source file:com.marklogic.client.test.RawQueryDefinitionTest.java
@Test public void testExtractDocumentData() throws Exception { String options = "<search:options>" + "<search:extract-document-data>" + "<search:extract-path>/root/child</search:extract-path>" + "<search:extract-path>/a/*</search:extract-path>" + "</search:extract-document-data>" + "</search:options>"; // test XML response with extracted XML and JSON matches String combinedSearch = head + qtext4 + options + tail; RawCombinedQueryDefinition rawCombinedQueryDefinition = queryMgr .newRawCombinedQueryDefinition(new StringHandle(combinedSearch).withMimetype("application/xml")); SearchHandle results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle()); MatchDocumentSummary[] summaries = results.getMatchResults(); assertNotNull(summaries);//from ww w .jav a 2s. c o m assertEquals(2, summaries.length); for (MatchDocumentSummary summary : summaries) { ExtractedResult extracted = summary.getExtracted(); if (Format.XML == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(3, extracted.size()); Document item1 = extracted.next().getAs(Document.class); assertEquals("1", item1.getFirstChild().getAttributes().getNamedItem("id").getNodeValue()); Document item2 = extracted.next().getAs(Document.class); assertEquals("2", item2.getFirstChild().getAttributes().getNamedItem("id").getNodeValue()); Document item3 = extracted.next().getAs(Document.class); assertEquals("3", item3.getFirstChild().getAttributes().getNamedItem("id").getNodeValue()); continue; } else if (Format.JSON == summary.getFormat()) { // we don't test for kind because it isn't sent in this case assertEquals(3, extracted.size()); for (ExtractedItem item : extracted) { String stringJsonItem = item.getAs(String.class); JsonNode nodeJsonItem = item.getAs(JsonNode.class); if (nodeJsonItem.has("b1")) { assertEquals("{\"b1\":{\"c\":\"jsonValue1\"}}", stringJsonItem); continue; } else if (nodeJsonItem.has("b2")) { assertTrue(stringJsonItem.matches("\\{\"b2\":\"b2 val[12]\"}")); continue; } fail("unexpected extracted item:" + stringJsonItem); } continue; } fail("unexpected search result:" + summary.getUri()); } // test JSON response with extracted XML and JSON matches JsonNode jsonResults = queryMgr.search(rawCombinedQueryDefinition, new JacksonHandle()).get(); JsonNode jsonSummaries = jsonResults.get("results"); assertNotNull(jsonSummaries); assertEquals(2, jsonSummaries.size()); for (int i = 0; i < jsonSummaries.size(); i++) { JsonNode summary = jsonSummaries.get(i); String format = summary.get("format").textValue(); String docPath = summary.get("path").textValue(); assertNotNull(docPath); JsonNode extracted = summary.get("extracted"); if ("xml".equals(format)) { if (docPath.contains("/sample/first.xml")) { JsonNode extractedItems = extracted.path("content"); assertEquals(3, extractedItems.size()); assertEquals(3, extractedItems.size()); Document item1 = parseXml(extractedItems.get(0).textValue()); assertEquals("1", item1.getFirstChild().getAttributes().getNamedItem("id").getNodeValue()); Document item2 = parseXml(extractedItems.get(1).textValue()); assertEquals("2", item2.getFirstChild().getAttributes().getNamedItem("id").getNodeValue()); Document item3 = parseXml(extractedItems.get(2).textValue()); assertEquals("3", item3.getFirstChild().getAttributes().getNamedItem("id").getNodeValue()); continue; } } else if ("json".equals(format)) { if (docPath.contains("/basic1.json")) { JsonNode items = extracted.get("content"); assertNotNull(items); assertEquals(3, items.size()); assertTrue(items.get(0).has("b1")); assertTrue(items.get(1).has("b2")); assertTrue(items.get(2).has("b2")); continue; } } fail("unexpected search result:" + summary); } // test XML response with full document XML and JSON matches options = "<search:options>" + "<search:extract-document-data selected=\"all\"/>" + "</search:options>"; combinedSearch = head + qtext4 + options + tail; rawCombinedQueryDefinition = queryMgr .newRawCombinedQueryDefinition(new StringHandle(combinedSearch).withMimetype("application/xml")); results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle()); summaries = results.getMatchResults(); assertNotNull(summaries); assertEquals(2, summaries.length); for (MatchDocumentSummary summary : summaries) { ExtractedResult extracted = summary.getExtracted(); if (Format.XML == summary.getFormat()) { assertEquals("element", extracted.getKind()); assertEquals(1, extracted.size()); Document root = extracted.next().getAs(Document.class); assertEquals("root", root.getFirstChild().getNodeName()); NodeList children = root.getFirstChild().getChildNodes(); assertEquals(3, children.getLength()); Node item1 = children.item(0); assertEquals("1", item1.getAttributes().getNamedItem("id").getNodeValue()); Node item2 = children.item(1); assertEquals("2", item2.getAttributes().getNamedItem("id").getNodeValue()); Node item3 = children.item(2); assertEquals("3", item3.getAttributes().getNamedItem("id").getNodeValue()); continue; } else if (Format.JSON == summary.getFormat()) { assertEquals("object", extracted.getKind()); String jsonDocument = extracted.next().getAs(String.class); assertEquals("{\"a\":{\"b1\":{\"c\":\"jsonValue1\"}, \"b2\":[\"b2 val1\", \"b2 val2\"]}}", jsonDocument); continue; } fail("unexpected search result:" + summary.getUri()); } // test JSON response with full document XML matches jsonResults = queryMgr.search(rawCombinedQueryDefinition, new JacksonHandle()).get(); jsonSummaries = jsonResults.get("results"); assertNotNull(jsonSummaries); assertEquals(2, jsonSummaries.size()); for (int i = 0; i < jsonSummaries.size(); i++) { JsonNode summary = jsonSummaries.get(i); String format = summary.get("format").textValue(); String docPath = summary.get("path").textValue(); assertNotNull(docPath); JsonNode extracted = summary.get("extracted"); if ("xml".equals(format)) { if (docPath.contains("/sample/first.xml")) { assertEquals("fn:doc(\"/sample/first.xml\")", docPath); JsonNode extractedItems = extracted.path("content"); assertEquals(1, extractedItems.size()); Document root = parseXml(extractedItems.get(0).textValue()); assertEquals("root", root.getFirstChild().getNodeName()); NodeList children = root.getFirstChild().getChildNodes(); assertEquals(3, children.getLength()); Node item1 = children.item(0); assertEquals("1", item1.getAttributes().getNamedItem("id").getNodeValue()); Node item2 = children.item(1); assertEquals("2", item2.getAttributes().getNamedItem("id").getNodeValue()); Node item3 = children.item(2); assertEquals("3", item3.getAttributes().getNamedItem("id").getNodeValue()); continue; } } else if ("json".equals(format)) { if (docPath.contains("/basic1.json")) { assertEquals("fn:doc(\"/basic1.json\")", docPath); assertEquals("object", extracted.get("kind").textValue()); JsonNode items = extracted.get("content"); assertNotNull(items); assertEquals(1, items.size()); assertTrue(items.path(0).has("a")); assertTrue(items.path(0).path("a").has("b1")); assertTrue(items.path(0).path("a").path("b1").has("c")); continue; } } fail("unexpected search result:" + summary); } // test XML response with XML and JSON document matches with path that does not match options = "<search:options>" + "<search:extract-document-data>" + "<search:extract-path>/somethingThatShouldNeverMatch</search:extract-path>" + "</search:extract-document-data>" + "</search:options>"; combinedSearch = head + qtext4 + options + tail; rawCombinedQueryDefinition = queryMgr .newRawCombinedQueryDefinition(new StringHandle(combinedSearch).withMimetype("application/xml")); results = queryMgr.search(rawCombinedQueryDefinition, new SearchHandle()); summaries = results.getMatchResults(); assertNotNull(summaries); assertEquals(2, summaries.length); for (MatchDocumentSummary summary : summaries) { ExtractedResult extracted = summary.getExtracted(); assertTrue(extracted.isEmpty()); } // test JSON response with XML and JSON document matches with path that does not match jsonResults = queryMgr.search(rawCombinedQueryDefinition, new JacksonHandle()).get(); jsonSummaries = jsonResults.get("results"); assertNotNull(jsonSummaries); assertEquals(2, jsonSummaries.size()); for (int i = 0; i < jsonSummaries.size(); i++) { JsonNode summary = jsonSummaries.get(i); JsonNode extractedNone = summary.get("extracted-none"); assertNotNull(extractedNone); assertEquals(0, extractedNone.size()); } }
From source file:org.gvnix.web.report.roo.addon.addon.ReportConfigServiceImpl.java
/** * Add the ViewResolver config to webmvc-config.xml *//*from ww w . jav a 2s . c o m*/ public final void addJasperReportsViewResolver() { PathResolver pathResolver = projectOperations.getPathResolver(); // Add config to MVC app context String mvcConfig = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), "WEB-INF/spring/webmvc-config.xml"); MutableFile mutableMvcConfigFile = fileManager.updateFile(mvcConfig); Document mvcConfigDocument; try { mvcConfigDocument = XmlUtils.getDocumentBuilder().parse(mutableMvcConfigFile.getInputStream()); } catch (Exception ex) { throw new IllegalStateException("Could not open Spring MVC config file '" + mvcConfig + "'", ex); } Element beans = mvcConfigDocument.getDocumentElement(); if (null == XmlUtils.findFirstElement("/beans/bean[@id='jasperReportsXmlViewResolver']", beans)) { InputStream configTemplateInputStream = null; OutputStream mutableMvcConfigFileOutput = null; try { configTemplateInputStream = FileUtils.getInputStream(getClass(), "jasperreports-mvc-config-template.xml"); Validate.notNull(configTemplateInputStream, "Could not acquire jasperreports-mvc-config-template.xml file"); Document configDoc; try { configDoc = XmlUtils.getDocumentBuilder().parse(configTemplateInputStream); } catch (Exception e) { throw new IllegalStateException(e); } Element configElement = (Element) configDoc.getFirstChild(); Element jasperReportsBeanConfig = XmlUtils.findFirstElement("/config/bean", configElement); Node importedElement = mvcConfigDocument.importNode(jasperReportsBeanConfig, true); beans.appendChild(importedElement); mutableMvcConfigFileOutput = mutableMvcConfigFile.getOutputStream(); XmlUtils.writeXml(mutableMvcConfigFileOutput, mvcConfigDocument); } finally { IOUtils.closeQuietly(mutableMvcConfigFileOutput); IOUtils.closeQuietly(configTemplateInputStream); } } if (fileManager.exists( pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), JASPER_VIEWS_XML))) { fileManager.scan(); // This file already exists, nothing to do return; } // Add jasper-views.xml file MutableFile mutableFile; InputStream jRepTInStrm; try { jRepTInStrm = FileUtils.getInputStream(getClass(), "jasperreports-views-config-template.xml"); } catch (Exception ex) { throw new IllegalStateException("Unable to load jasperreports-views-config-template.xml", ex); } String jasperViesFileDestination = pathResolver .getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), JASPER_VIEWS_XML); if (!fileManager.exists(jasperViesFileDestination)) { mutableFile = fileManager.createFile(jasperViesFileDestination); Validate.notNull(mutableFile, "Could not create JasperReports views definition file '" .concat(jasperViesFileDestination).concat("'")); } else { mutableFile = fileManager.updateFile(jasperViesFileDestination); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = jRepTInStrm; outputStream = mutableFile.getOutputStream(); IOUtils.copy(inputStream, outputStream); } catch (IOException ioe) { throw new IllegalStateException("Could not output '".concat(mutableFile.getCanonicalPath()).concat("'"), ioe); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } fileManager.scan(); }
From source file:lineage2.gameserver.instancemanager.CursedWeaponsManager.java
/** * Method load.//from w w w . j a v a 2s .com */ private void load() { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); File file = new File(Config.DATAPACK_ROOT, "data/xml/other/cursed_weapons.xml"); if (!file.exists()) { return; } Document doc = factory.newDocumentBuilder().parse(file); for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("item".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue()); int skillId = Integer.parseInt(attrs.getNamedItem("skillId").getNodeValue()); String name = "Unknown cursed weapon"; if (attrs.getNamedItem("name") != null) { name = attrs.getNamedItem("name").getNodeValue(); } else if (ItemHolder.getInstance().getTemplate(id) != null) { name = ItemHolder.getInstance().getTemplate(id).getName(); } if (id == 0) { continue; } CursedWeapon cw = new CursedWeapon(id, skillId, name); for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { if ("dropRate".equalsIgnoreCase(cd.getNodeName())) { cw.setDropRate(Integer .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue())); } else if ("duration".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); cw.setDurationMin(Integer.parseInt(attrs.getNamedItem("min").getNodeValue())); cw.setDurationMax(Integer.parseInt(attrs.getNamedItem("max").getNodeValue())); } else if ("durationLost".equalsIgnoreCase(cd.getNodeName())) { cw.setDurationLost(Integer .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue())); } else if ("disapearChance".equalsIgnoreCase(cd.getNodeName())) { cw.setDisapearChance(Integer .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue())); } else if ("stageKills".equalsIgnoreCase(cd.getNodeName())) { cw.setStageKills(Integer .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue())); } else if ("transformationId".equalsIgnoreCase(cd.getNodeName())) { cw.setTransformationId(Integer .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue())); } else if ("transformationTemplateId".equalsIgnoreCase(cd.getNodeName())) { cw.setTransformationTemplateId(Integer .parseInt(cd.getAttributes().getNamedItem("val").getNodeValue())); } else if ("transformationName".equalsIgnoreCase(cd.getNodeName())) { cw.setTransformationName(cd.getAttributes().getNamedItem("val").getNodeValue()); } } _cursedWeaponsMap.put(id, cw); } } } } _cursedWeapons = _cursedWeaponsMap.values(new CursedWeapon[_cursedWeaponsMap.size()]); } catch (Exception e) { _log.error("CursedWeaponsManager: Error parsing cursed_weapons file. " + e); } }
From source file:net.sourceforge.eclipsetrader.yahoo.ItalianNewsProvider.java
private void update() { Object[] o = oldItems.toArray(); for (int i = 0; i < o.length; i++) { ((NewsItem) o[i]).setRecent(false); CorePlugin.getRepository().save((NewsItem) o[i]); }/* ww w . ja va 2 s .c o m*/ oldItems.clear(); Job job = new Job(Messages.ItalianNewsProvider_JobName) { @Override protected IStatus run(IProgressMonitor monitor) { IPreferenceStore store = YahooPlugin.getDefault().getPreferenceStore(); List urls = new ArrayList(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(FileLocator.openStream(YahooPlugin.getDefault().getBundle(), new Path("categories.it.xml"), false)); //$NON-NLS-1$ org.w3c.dom.NodeList childNodes = document.getFirstChild().getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { org.w3c.dom.Node node = childNodes.item(i); String nodeName = node.getNodeName(); if (nodeName.equalsIgnoreCase("category")) //$NON-NLS-1$ { String id = (node).getAttributes().getNamedItem("id").getNodeValue(); //$NON-NLS-1$ org.w3c.dom.NodeList list = node.getChildNodes(); for (int x = 0; x < list.getLength(); x++) { org.w3c.dom.Node item = list.item(x); nodeName = item.getNodeName(); org.w3c.dom.Node value = item.getFirstChild(); if (value != null) { if (nodeName.equalsIgnoreCase("url")) //$NON-NLS-1$ { if (store.getBoolean(id)) urls.add(value.getNodeValue()); } } } } } } catch (Exception e) { log.error(e, e); } List securities = CorePlugin.getRepository().allSecurities(); monitor.beginTask(Messages.ItalianNewsProvider_TaskName, urls.size() + securities.size()); log.info("Start fetching Yahoo! News (Italy)"); //$NON-NLS-1$ for (Iterator iter = securities.iterator(); iter.hasNext();) { Security security = (Security) iter.next(); try { String url = "http://it.finance.yahoo.com/rss/headline?s=" //$NON-NLS-1$ + security.getCode().toUpperCase(); monitor.subTask(url); update(new URL(url), security); monitor.worked(1); } catch (Exception e) { log.error(e, e); } } for (Iterator iter = urls.iterator(); iter.hasNext();) { String url = (String) iter.next(); monitor.subTask(url); parseNewsPage(url); monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } }; job.setUser(false); job.schedule(); }
From source file:me.willowcheng.makerthings.ui.OpenHABWidgetListFragment.java
/** * Parse XML sitemap page and show it/*from ww w .jav a 2 s . c om*/ * * @param document XML Document * @return void */ public void processContent(String responseString, boolean longPolling) { // As we change the page we need to stop all videos on current page // before going to the new page. This is quite dirty, but is the only // way to do that... Log.d(TAG, "processContent() " + this.displayPageUrl); Log.d(TAG, "isAdded = " + isAdded()); openHABWidgetAdapter.stopVideoWidgets(); openHABWidgetAdapter.stopImageRefresh(); // If openHAB verion = 1 get page from XML if (mActivity.getOpenHABVersion() == 1) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(responseString))); if (document != null) { Node rootNode = document.getFirstChild(); openHABWidgetDataSource.setSourceNode(rootNode); widgetList.clear(); for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) { // Remove frame widgets with no label text if (w.getType().equals("Frame") && TextUtils.isEmpty(w.getLabel())) continue; widgetList.add(w); } } else { Log.e(TAG, "Got a null response from openHAB"); showPage(displayPageUrl, false); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Later versions work with JSON } else { try { JSONObject pageJson = new JSONObject(responseString); openHABWidgetDataSource.setSourceJson(pageJson); widgetList.clear(); for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) { // Remove frame widgets with no label text if (w.getType().equals("Frame") && TextUtils.isEmpty(w.getLabel())) continue; widgetList.add(w); } } catch (JSONException e) { e.printStackTrace(); } } openHABWidgetAdapter.notifyDataSetChanged(); if (!longPolling && isAdded()) { getListView().clearChoices(); Log.d(TAG, String.format("processContent selectedItem = %d", mCurrentSelectedItem)); if (mCurrentSelectedItem >= 0) getListView().setItemChecked(mCurrentSelectedItem, true); } if (getActivity() != null && mIsVisible) getActivity().setTitle(openHABWidgetDataSource.getTitle()); // } // Set widget list index to saved or zero position // This would mean we got widget and command from nfc tag, so we need to do some automatic actions! if (this.nfcWidgetId != null && this.nfcCommand != null) { Log.d(TAG, "Have widget and command, NFC action!"); OpenHABWidget nfcWidget = this.openHABWidgetDataSource.getWidgetById(this.nfcWidgetId); OpenHABItem nfcItem = nfcWidget.getItem(); // Found widget with id from nfc tag and it has an item if (nfcWidget != null && nfcItem != null) { // TODO: Perform nfc widget action here if (this.nfcCommand.equals("TOGGLE")) { if (nfcItem.getType().equals("RollershutterItem")) { if (nfcItem.getStateAsBoolean()) this.openHABWidgetAdapter.sendItemCommand(nfcItem, "UP"); else this.openHABWidgetAdapter.sendItemCommand(nfcItem, "DOWN"); } else { if (nfcItem.getStateAsBoolean()) this.openHABWidgetAdapter.sendItemCommand(nfcItem, "OFF"); else this.openHABWidgetAdapter.sendItemCommand(nfcItem, "ON"); } } else { this.openHABWidgetAdapter.sendItemCommand(nfcItem, this.nfcCommand); } } this.nfcWidgetId = null; this.nfcCommand = null; if (this.nfcAutoClose) { getActivity().finish(); } } showPage(displayPageUrl, true); }
From source file:org.openhab.habdroid.ui.OpenHABRoomSettingActivity.java
/** * Parse XML sitemap page and show it//from w ww . j a va2s .com * * @param content XML as a text * @return void */ public void processContent(String content) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = factory.newDocumentBuilder(); Document document; // TODO: fix crash with null content document = builder.parse(new ByteArrayInputStream(content.getBytes("UTF-8"))); Node rootNode = document.getFirstChild(); openHABWidgetDataSource.setSourceNode(rootNode); widgetList.clear(); // As we change the page we need to stop all videos on current page // before going to the new page. This is quite dirty, but is the only // way to do that... openHABWidgetAdapter.stopVideoWidgets(); openHABWidgetAdapter.stopImageRefresh(); if (isSitemap()) groupList.clear(); for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) { widgetList.add(w); if (isSitemap() && w.getType().equals("Group")) groupList.add(w); } openHABWidgetAdapter.notifyDataSetChanged(); setTitle(openHABWidgetDataSource.getTitle()); setProgressBarIndeterminateVisibility(false); getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i(TAG, "Widget clicked " + String.valueOf(position)); OpenHABWidget openHABWidget = openHABWidgetAdapter.getItem(position); if (openHABWidget.hasLinkedPage()) { currPID = openHABWidget.getWidgetId(); tvtitle.setText(openHABWidget.getLabel()); pageStack.add(0, new OpenHABPage(displayPageUrl, OpenHABRoomSettingActivity.this.getListView().getFirstVisiblePosition())); displayPageUrl = openHABWidget.getLinkedPage().getLink(); showPage(openHABWidget.getLinkedPage().getLink(), false); } } }); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.spinn3r.api.BaseClient.java
/** * We've received a response from the API so parse it out. * *//* w w w . j a v a 2 s . c o m*/ protected List<ResultType> xmlParse(Document doc, Config<ResultType> config) throws Exception { Element root = (Element) doc.getFirstChild(); List<ResultType> result = new ArrayList<ResultType>(); NodeList items = root.getElementsByTagName("item"); for (int i = 0; i < items.getLength(); ++i) { Element current = (Element) items.item(i); result.add(config.createResultObject(current)); } return result; }