I am trying to get the values inside this soap fault's "detail", but I haven't found any ways of doing so.
The response from the server:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Many Errors</faultstring>
<detail>
<error_id>2</error_id>
<errors>
<error>
<error_id>1</error_id>
<error_description>Unknown Error</error_description>
</error>
<error>
<error_id>5</error_id>
<error_description>Not Authorized</error_description>
</error>
<error>
<error_id>9</error_id>
<error_description>Password should be at least 6 characters including one letter and one number</error_description>
</error>
</errors>
</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I need to get the error_ids along with their respective error_descriptions. So far I've only managed to get the detail via kSOAP with the following way:
if (envelope.bodyIn instanceof SoapObject) {
return envelope.bodyIn.toString();
} else if (envelope.bodyIn instanceof SoapFault) {
SoapFault e = (SoapFault) envelope.bodyIn;
Node details = ((SoapFault) envelope.bodyIn).detail;
}
but I haven't managed to get a single value I need when I try to "navigate" through it.
Any help is greatly appreciated. I have found little to non information about handling soap faults with ksoap2 online...
The following code handles better
Iterator it = soapFaultClientException.getSoapFault().getFaultDetail().getDetailEntries();
while (it.hasNext())
{
Source errSource = it.next().getSource();
#SuppressWarnings("unchecked")
JAXBElement errJaxb = (JAXBElement) springWebServiceTemplate.getUnmarshaller().unmarshal(errSource);
ServerCustomizedError err = errJaxb.getValue();
....
}
Figured it out after all. Here is the way to do it:
Node details = ((SoapFault) envelope.bodyIn).detail;
Element detEle = details.getElement(NAMESPACE, "detail");
List<Error> errorList = new ArrayList<NewConnector.Error>();
Element idEle = detEle.getElement(NAMESPACE, "error_id");
str.append("id: " + idEle.getText(0));
str.append("\n");
Integer id = Integer.valueOf(idEle.getText(0));
if (id == 2) {
// many errors
Element errors = detEle.getElement(NAMESPACE, "errors");
int errorChildCount = errors.getChildCount();
for (int i = 0; i < errorChildCount; i++) {
Object innerError = errors.getChild(i);
if (innerError instanceof Element) {
Element error_id = ((Element) innerError).getElement(
NAMESPACE, "error_id");
Element error_descrion = ((Element) innerError)
.getElement(NAMESPACE, "error_description");
Error singleError = new Error(Integer.valueOf(error_id
.getText(0)), error_descrion.getText(0));
errorList.add(singleError);
str.append(singleError.toString() + "\n");
}
}
str.append("Found " + errorList.size() + " errors.\n");
str.append("errorscount:" + errors.getChildCount());
The code obviously needs improvements, but it's just a showcase of how to get each value. Cheers
I use the following method:
/**
* Method to retrieve the errorMessage from the given SoapFault.
* #param soapFault
* #return String representing the errorMessage found in the given SoapFault.
*/
private static String getSoapErrorMessage (SoapFault soapFault) {
String errorMessage;
try {
Node detailNode = soapFault.detail;
Element faultDetailElement = (Element)detailNode.getElement(0).getChild(1);
Element errorMessageElement = (Element)faultDetailElement.getChild(0);
errorMessage = errorMessageElement.getText(0);
}
catch (Exception e) {
e.printStackTrace();
errorMessage = "Could not determine soap error.";
}
return errorMessage;
}
Related
Here I have written code for Gmail API to fetch mail with date filter
I am able to fetch MessageId and ThreadId using the First API. On the basis of MessageId, I put that messageId parameter in a List object and I have sent this parameter in foreach loop from List to the next API to fetch email body on basis of messageID. But the process is very slow for fetching messages from Gmail
public async Task<ActionResult> DisplayEmailWithFilter (string fromDate, string toDate) {
Message messageObj = new Message ();
Example exampleObj = new Example ();
List<GmailMessage> gmailMessagesList = new List<GmailMessage> ();
GmailMessage gmailMessage = new GmailMessage ();
var responseData = "";
//dateFilter string parameter Created with Date Values
string dateFilter = "in:Inbox after:" + fromDate + " before:" + toDate;
try {
// calling Gmail API to get MessageID Details by Date Filter
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue (scheme: "Bearer",
parameter : Session["Token"].ToString ());
HttpResponseMessage responseMessage = await client.GetAsync ("https://www.googleapis.com/gmail/v1/users/me/messages?q=" + dateFilter);
if (responseMessage.IsSuccessStatusCode) {
var data = responseMessage.Content;
}
try {
responseData = responseMessage.Content.ReadAsStringAsync ().Result;
//This Json Data Converted into List Object
var msgList = JsonConvert.DeserializeObject<Root1> (responseData);
//loop for Fetching EmailMessageData by MessageID
if (msgList.resultSizeEstimate != 0) {
foreach (var msgItem in msgList.messages) {
messageObj.id = msgItem.id;
//Calling API with MessageID Parameter to fetch Respective Message Data
HttpResponseMessage responseMessageList = await client.GetAsync ("https://www.googleapis.com/gmail/v1/users/userId/messages/id?id=" + messageObj.id.ToString () + "&userId=me&format=full");
if (responseMessageList.IsSuccessStatusCode) {
var dataNew = responseMessageList.Content;
var responseDataNew = responseMessageList.Content.ReadAsStringAsync ().Result;
//Converting json string in Object
exampleObj = JsonConvert.DeserializeObject<Example> (responseDataNew);
gmailMessage.Body = exampleObj.snippet;
//fetching Header Values comparing with string to get Data
for (int i = 1; i < exampleObj.payload.headers.Count; i++) {
if (exampleObj.payload.headers[i].name.ToString () == "Date") {
gmailMessage.RecievedDate = exampleObj.payload.headers[i].value;
}
if (exampleObj.payload.headers[i].name.ToString () == "Subject") {
gmailMessage.Subject = exampleObj.payload.headers[i].value;
}
if (exampleObj.payload.headers[i].name.ToString () == "Message-ID") {
gmailMessage.SenderEmailID = exampleObj.payload.headers[i].value;
}
if (exampleObj.payload.headers[i].name.ToString () == "From") {
gmailMessage.SenderName = exampleObj.payload.headers[i].value;
}
}
//Adding This Object Values in GmailMessgage List Object
gmailMessagesList.Add (
new GmailMessage {
Body = exampleObj.snippet,
SenderEmailID = gmailMessage.SenderEmailID,
RecievedDate = gmailMessage.RecievedDate,
SenderName = gmailMessage.SenderName,
Subject = gmailMessage.Subject,
});
}
}
}
} catch (Exception e) {
string errorMgs = e.Message.ToString ();
throw;
}
} catch (Exception e) {
string errorMgs = e.Message.ToString ();
throw;
}
return View (gmailMessagesList);
}
I can fetch Gmail email datewise but it took so much time to fetch. how can I improve my code and performance faster?
The query seems like the most you can do. If you know more information about those emails, like a specific subjects or there always come from the same sender you can try to filter that too, like you would in the Gmail interface.
Other way you would be kind of out of luck. You are limited by the files retrieved from User.messages.list.
If you need to escape from the API limitations maybe trying to retrieve the message other way would be the correct way to go. Considerate creating a small code to retrieve message by the IMAP protocol. Several questions in this topic may help you:
Reading Gmail messages using Python IMAP
Reading Gmail Email in Python
How can I get an email message's text content using Python?
I want to update my max cpc bid for a specific product in adwords.
Via the webui of adwords this is a trivial task, but I cant get it to work in code, this is what I have so far.
import com.google.api.ads.adwords.axis.factory.AdWordsServices;
import com.google.api.ads.adwords.axis.v201607.cm.*;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.client.auth.oauth2.Credential;
import java.rmi.RemoteException;
public class ChangeBidOnSpecificProduct {
public static void main(String[] args) throws Exception {
OfflineCredentials build = new OfflineCredentials.Builder()
.forApi(OfflineCredentials.Api.ADWORDS)
.fromFile()
.build();
Credential oAuth2Credential = build
.generateCredential();
// Construct an AdWordsSession.
AdWordsSession session = new AdWordsSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
String accountId = "ACCOUNT_ID";
Long campaignId = Long.valueOf("CAMPAIGN_ID");
long adGroupId = Long.valueOf("ADGROUP_ID");
session.setClientCustomerId(accountId);
Money money = new Money(null, 40000L);
String productId = "9200000050670959";
changeBidViaApi(session, campaignId, adGroupId, productId, money);
}
private static void changeBidViaApi(AdWordsSession session, Long campaignId, long adGroupId, String productId, Money newValue) throws RemoteException {
ProductOfferId productOfferId = new ProductOfferId();
productOfferId.setValue(productId);
ProductScope productScope = new ProductScope();
productScope.setDimensions(new ProductDimension[] {productOfferId});
BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
biddableAdGroupCriterion.setAdGroupId(adGroupId);
biddableAdGroupCriterion.setCriterion(productScope);
BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
CpcBid bid = new CpcBid();
bid.setBid(newValue);
biddingStrategyConfiguration.setBids(new Bids[]{bid});
biddableAdGroupCriterion.setBiddingStrategyConfiguration(biddingStrategyConfiguration);
AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
operation.setOperand(biddableAdGroupCriterion);
operation.setOperator(Operator.SET);
AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[]{operation};
AdWordsServices adWordsServices = new AdWordsServices();
AdGroupCriterionServiceInterface adGroupCriterionService =
adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations);
}
}
Executing this results in an error: 'Unmarshalling Error: cvc-elt.4.2: Cannot resolve 'ns2:ProductScope' to a type definition for element 'ns2:criterion''.
This is the (anonimized) data that is send to google:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
<ns1:RequestHeader soapenv:mustUnderstand="0" xmlns:ns1="https://adwords.google.com/api/adwords/cm/v201607">
<ns1:clientCustomerId>ACCOUNT_ID</ns1:clientCustomerId>
<ns1:developerToken>MY_DEV_TOKEN</ns1:developerToken>
<ns1:userAgent>MY_UA</ns1:userAgent>
<ns1:validateOnly>false</ns1:validateOnly>
<ns1:partialFailure>false</ns1:partialFailure>
</ns1:RequestHeader>
</soapenv:Header>
<soapenv:Body>
<mutate xmlns="https://adwords.google.com/api/adwords/cm/v201607">
<operations>
<operator>SET</operator>
<operand xsi:type="ns2:BiddableAdGroupCriterion" xmlns:ns2="https://adwords.google.com/api/adwords/cm/v201607">
<ns2:adGroupId>ADGROUP_ID</ns2:adGroupId>
<ns2:criterion xsi:type="ns2:ProductScope">
<ns2:dimensions xsi:type="ns2:ProductOfferId">
<ns2:value>9200000050670959</ns2:value>
</ns2:dimensions>
</ns2:criterion>
<ns2:biddingStrategyConfiguration>
<ns2:bids xsi:type="ns2:CpcBid">
<ns2:bid>
<ns2:microAmount>1</ns2:microAmount>
</ns2:bid>
</ns2:bids>
</ns2:biddingStrategyConfiguration>
</operand>
</operations>
</mutate>
</soapenv:Body>
</soapenv:Envelope>
Any suggestions as the reason for the error or what I'm doing wrong here?
I managed to get it working by accessing the adwords items as a graph, iterating it and changing it bid value when I find a match.
private static void changeBidViaApi(AdWordsSession session, long adGroupId, String productId, Money newValue) throws RemoteException {
AdWordsServices adWordsServices = new AdWordsServices();
ProductPartitionTree partitionTree =
ProductPartitionTree.createAdGroupTree(adWordsServices, session, adGroupId);
for (ProductPartitionNode node : partitionTree.getRoot().getChildren()) {
ProductPartitionNode productPartitionNode = node.asBiddableUnit();
try {
ProductOfferId dimension = (ProductOfferId) productPartitionNode.getDimension();
if (dimension != null) {
String productIdInShopping = dimension.getValue();
if (productId.equals(productIdInShopping)) {
Long newBid = newValue.getMicroAmount();
productPartitionNode.setBid(newBid);
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
AdGroupCriterionServiceInterface adGroupCriterionService =
adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
List<AdGroupCriterionOperation> mutateOperations = partitionTree.getMutateOperations();
if (mutateOperations.isEmpty()) {
System.out.println("Nothing to do.");
} else {
adGroupCriterionService.mutate(mutateOperations.toArray(new AdGroupCriterionOperation[0]));
}
}
This is the working source code. It changes bid (max cpc) of product partition group. It is written in php, but you can modify this code to java.
$adWordsServices = new AdWordsServices();
$session = $this->getSession();
$adGroupCriterionService = $adWordsServices->get($session, AdGroupCriterionService::class);
$operations = [];
$adGroupCriterion = new BiddableAdGroupCriterion();
$adGroupCriterion->setAdGroupId(22122723325); // id of my adgroup
$adGroupCriterion->setCriterion(new Criterion(302190832)); // id of partition group. you can get find this id in PRODUCT_PARTITION_REPORT in ID field (which full name is Criterion ID)
//
$bid = new CpcBid();
$money = new Money();
$money->setMicroAmount(((float)4)*1000000);
$bid->setBid($money);
$biddingStrategyConfiguration = new BiddingStrategyConfiguration();
$biddingStrategyConfiguration->setBids([$bid]);
$adGroupCriterion->setBiddingStrategyConfiguration($biddingStrategyConfiguration);
$operation = new AdGroupCriterionOperation();
$operation->setOperand($adGroupCriterion);
$operation->setOperator(Operator::SET);
$operations[] = $operation;
//
$adGroupCriterionService->mutate($operations);
I am making a crawler application in Groovy on Grails. I am using Crawler4j and following this tutorial.
I created a new grails project
Put the BasicCrawlController.groovy file in controllers->package
Did not create any view because I expected on doing run-app, my crawled data would appear in my crawlStorageFolder (please correct me if my understanding is flawed)
After that I just ran the application by doing run-app but I didn't see any crawling data anywhere.
Am I right in expecting some file to be created at the crawlStorageFolder location that I have given as C:/crawl/crawler4jStorage?
Do I need to create any view for this?
If I want to invoke this crawler controller from some other view on click of a submit button of a form, can I just write <g:form name="submitWebsite" url="[controller:'BasicCrawlController ']">?
I asked this because I do not have any method in this controller, so is it the right way to invoke this controller?
My code is as follows:
//All necessary imports
public class BasicCrawlController {
static main(args) throws Exception {
String crawlStorageFolder = "C:/crawl/crawler4jStorage";
int numberOfCrawlers = 1;
//int maxDepthOfCrawling = -1; default
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setPolitenessDelay(1000);
config.setMaxPagesToFetch(100);
config.setResumableCrawling(false);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://en.wikipedia.org/wiki/Web_crawler")
controller.start(BasicCrawler.class, 1);
}
}
class BasicCrawler extends WebCrawler {
final static Pattern FILTERS = Pattern
.compile(".*(\\.(css|js|bmp|gif|jpe?g"+ "|png|tiff?|mid|mp2|mp3|mp4" +
"|wav|avi|mov|mpeg|ram|m4v|pdf" +"|rm|smil|wmv|swf|wma|zip|rar|gz))\$")
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
#Override
boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase()
!FILTERS.matcher(href).matches() && href.startsWith("http://en.wikipedia.org/wiki/Web_crawler/")
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
#Override
void visit(Page page) {
int docid = page.getWebURL().getDocid()
String url = page.getWebURL().getURL()
String domain = page.getWebURL().getDomain()
String path = page.getWebURL().getPath()
String subDomain = page.getWebURL().getSubDomain()
String parentUrl = page.getWebURL().getParentUrl()
String anchor = page.getWebURL().getAnchor()
println("Docid: ${docid} ")
println("URL: ${url} ")
println("Domain: '${domain}'")
println("Sub-domain: ' ${subDomain}'")
println("Path: '${path}'")
println("Parent page:${parentUrl} ")
println("Anchor text: ${anchor} " )
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData()
String text = htmlParseData.getText()
String html = htmlParseData.getHtml()
List<WebURL> links = htmlParseData.getOutgoingUrls()
println("Text length: " + text.length())
println("Html length: " + html.length())
println("Number of outgoing links: " + links.size())
}
Header[] responseHeaders = page.getFetchResponseHeaders()
if (responseHeaders != null) {
println("Response headers:")
for (Header header : responseHeaders) {
println("\t ${header.getName()} : ${header.getValue()}")
}
}
println("=============")
}
}
I'll try to translate your code into a Grails standard.
Use this under grails-app/controller
class BasicCrawlController {
def index() {
String crawlStorageFolder = "C:/crawl/crawler4jStorage";
int numberOfCrawlers = 1;
//int maxDepthOfCrawling = -1; default
CrawlConfig crawlConfig = new CrawlConfig();
crawlConfig.setCrawlStorageFolder(crawlStorageFolder);
crawlConfig.setPolitenessDelay(1000);
crawlConfig.setMaxPagesToFetch(100);
crawlConfig.setResumableCrawling(false);
PageFetcher pageFetcher = new PageFetcher(crawlConfig);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(crawlConfig, pageFetcher, robotstxtServer);
controller.addSeed("http://en.wikipedia.org/wiki/Web_crawler")
controller.start(BasicCrawler.class, 1);
render "done crawling"
}
}
Use this under src/groovy
class BasicCrawler extends WebCrawler {
final static Pattern FILTERS = Pattern
.compile(".*(\\.(css|js|bmp|gif|jpe?g"+ "|png|tiff?|mid|mp2|mp3|mp4" +
"|wav|avi|mov|mpeg|ram|m4v|pdf" +"|rm|smil|wmv|swf|wma|zip|rar|gz))\$")
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
#Override
boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase()
!FILTERS.matcher(href).matches() && href.startsWith("http://en.wikipedia.org/wiki/Web_crawler/")
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
#Override
void visit(Page page) {
int docid = page.getWebURL().getDocid()
String url = page.getWebURL().getURL()
String domain = page.getWebURL().getDomain()
String path = page.getWebURL().getPath()
String subDomain = page.getWebURL().getSubDomain()
String parentUrl = page.getWebURL().getParentUrl()
String anchor = page.getWebURL().getAnchor()
println("Docid: ${docid} ")
println("URL: ${url} ")
println("Domain: '${domain}'")
println("Sub-domain: ' ${subDomain}'")
println("Path: '${path}'")
println("Parent page:${parentUrl} ")
println("Anchor text: ${anchor} " )
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData()
String text = htmlParseData.getText()
String html = htmlParseData.getHtml()
List<WebURL> links = htmlParseData.getOutgoingUrls()
println("Text length: " + text.length())
println("Html length: " + html.length())
println("Number of outgoing links: " + links.size())
}
Header[] responseHeaders = page.getFetchResponseHeaders()
if (responseHeaders != null) {
println("Response headers:")
for (Header header : responseHeaders) {
println("\t ${header.getName()} : ${header.getValue()}")
}
}
println("=============")
}
}
I am running in a strange problem. Let me explain:
I am passing set of input data from xml and then using JAXB to parse xml. This java object is then passed to my test method using testng dataprovider.
Here are some related code:
Testdata xml:
<TestData>
<TestDetails>
<testcasename>itemStatusTest</testcasename>
<testcasedetails>App in SUPPRESSED Status</testcasedetails>
<appid>28371</appid>
<status>SUPPRESSED</status>
<marketplace />
</TestDetails>
<TestDetails>
<testcasename>itemStatusTest</testcasename>
<testcasedetails>App in REVIEW Status</testcasedetails>
<appid>22559</appid>
<status>REVIEW</status>
<marketplace />
</TestDetails>
</TestData>
Method which returns object:
private static Object[][] generateTestData(String dataProvider,TestCaseName tcName) throws Exception {
Object[][] obj = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(TestData.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
TestData testData = (TestData) jaxbUnmarshaller
.unmarshal(new FileInputStream(new File(dataProvider)
.getAbsoluteFile()));
List<TestDetails> testcaseList = testData.getTestDetails();
obj = new Object[testcaseList.size()][];
for (int i = 0; i < testcaseList.size(); i++) {
if (testcaseList
.get(i)
.getTestcasename()
.equalsIgnoreCase(tcName.testCaseName()))
obj[i] = new Object[] { testcaseList.get(i) };
}
} catch (JAXBException e) {
e.getMessage();
return null;
}
return obj;
}
and my dataprovider:
#DataProvider(parallel = true, name = "TestData")
public Object[][] TestData() {
try {
Object obj[][]= IngestionTestHelper
.generateTestDataForItemStatus(dataProvider);
Reporter.log("Size "+obj.length, true);
return obj;
} catch (Exception e) {
Reporter.log(
"Either XML input is in wrong format or XML is not parsed correctly",
true);
return null;
}
}
Till now everything works like a charm and I am not seeing any issue.
Now i am writing another test method for another test-case. For that I have added following in my exisitng xml like this:
<TestDetails>
<testcasename>itemWorkflowTest</testcasename>
<testcasedetails>Validate workflow for iap</testcasedetails>
<appid>26120</appid>
<status />
<marketplace />
</TestDetails>
Now once i have added this in my existing xml my existing test method is not working. When running I am getting following exception:
java.lang.NullPointerException
at org.testng.internal.Invoker.injectParameters(Invoker.java:1333)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1203)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1197)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1122)
at org.testng.TestNG.run(TestNG.java:1030)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
If i remove the newly added block in xml it starts working.
Please someone help!!!
Well, based on the code, and if I understood correctly :)
When you add the third item the name is different,
You have initialized the Object array with the size of the total number of elements,
obj = new Object[testcaseList.size()][];
But you are adding to the array selectively based on name, so though the init has been done for 3 objects, the data is available only for 2 - this may be causing the NPE..
List<TestDetails> testcaseList = testData.getTestDetails();
obj = new Object[testcaseList.size()][];
for (int i = 0; i < testcaseList.size(); i++) {
if (testcaseList
.get(i)
.getTestcasename()
.equalsIgnoreCase(tcName.testCaseName()))
obj[i] = new Object[] { testcaseList.get(i) };
}
I am trying to parse an RSS feed using Linq to XML like so:
XNamespace slashNamespace = "http://purl.org/rss/1.0/modules/slash/";
XDocument rssFeed = XDocument.Load(#"http://blog.daimokuchart.com/index.php/feed/");
var posts = from item in rssFeed.Descendants("item")
select new RSSData {
Title = item.Element("title").Value,
Published = DateTime.Parse(item.Element("pubDate").Value),
Url = item.Element("link").Value,
Content = item.Element("content:encoded").Value
};
However; it is having a problem with with the content:encoded item I get this error "The ':' character, hexadecimal value 0x3A, cannot be included in a name. "
How the heck to I parse this item element?
XNamespace nsContent = "http://purl.org/rss/1.0/modules/content/";
// ...
Content = item.Element(nsContent + "encoded").Value
// ...
There is a much simpler way to parse a RSS feed : the SyndicationFeed class
More details here
Hi i used Linqtoxml and successfully able to parse Rss feed try below code
public apheadlines()
{
InitializeComponent();
InitializeComponent();
WebClient downloader = new WebClient();
Uri rssurl = new Uri("http://ibnlive.in.com/ibnrss/rss/southcinema/telugunews.xml", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(downloads);
downloader.DownloadStringAsync(rssurl);
}
private void downloads(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null)
{
MessageBox.Show("Error in download");
}
var Rss = from rss in XElement.Parse(e.Result).Descendants("item")
select new Data
{
Titles = rss.Element("title").Value.ToUpper(),
pubDate = rss.Element("pubDate").Value.Substring(0, 17)
};
listBox1.ItemsSource = Rss;
}