phantomjs exception error on Linux(64bit) org.openqa.selenium.NoSuchElementException - linux

the code runs well in my localhost(win10), but exception error on Linux(64bt) :
org.openqa.selenium.NoSuchElementException: {"errorMessage":"Unable to find element with id 'magix_vf_root'","request":{"headers":{"Accept":"application/json, image/png","Connection":"Keep-Alive","Content-Length":"38","Content-Type":"application/json; charset=utf-8","Host":"localhost:12709"},"httpVersion":"1.1","method":"POST","post":"{\"using\":\"id\",\"value\":\"magix_vf_root\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/350bd6e0-8784-11e6-b57c-35629091c8a9/element"}}
Command duration or timeout: 60.32 seconds
Here is my code:
public static void testPhantomjs() throws IOException{
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", true);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "F:\\selenium\\phantomjs.exe");
//caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/opt/phantomjs");
//System.setProperty("webdriver.chrome.driver", "F:\\selenium\\phantomjs.exe");
WebDriver d = new PhantomJSDriver(caps);
try{
//d.manage().timeouts().setScriptTimeout(20L, TimeUnit.SECONDS);
d.manage().timeouts().implicitlyWait(60L, TimeUnit.SECONDS);
d.get("http://www.alimama.com/member/login.htm?forward=http%3A%2F%2Fpub.alimama.com%2Fmyunion.htm");
d.manage().window().maximize();
d = d.switchTo().frame(d.findElement(By.name("taobaoLoginIfr")));
//WebElement quick = new WebDriverWait(d, 10).until(ExpectedConditions.visibilityOfElementLocated(By.id("J_Quick2Static")));
//new Actions(d).moveToElement(quick).click().perform();
//quick.click();
d.findElement(By.id("J_Quick2Static")).click();
//d.findElement(By.id("TPL_username_1")).clear();
d.findElement(By.id("TPL_username_1")).sendKeys("username");
//d.findElement(By.id("TPL_password_1")).clear();
d.findElement(By.id("TPL_password_1")).sendKeys("password");
getScreenshot(d, "1");
d.findElement(By.id("J_SubmitStatic")).click();
//d.switchTo().defaultContent();
getScreenshot(d , "2");
d.findElement(By.id("magix_vf_root"));
getScreenshot(d , "3");
Set<Cookie> cookies = d.manage().getCookies();
StringBuffer sb = new StringBuffer();
for (Cookie cookie : cookies) {
sb.append(cookie.getName() + "=" + cookie.getValue() + ";");
}
System.out.println("cookiestr:" + sb.toString());
}catch(Exception e){
e.printStackTrace();
}finally{
getScreenshot(d, "finally");
d.quit();
}
}
And the result message:

the code runs well in my localhost(win10),but exception error on Linux(64bt): org.openqa.selenium.NoSuchElementException: {"errorMessage":"Unable to find element with id 'magix_vf_root'"
It looks like timing issue, you should try using WebDriverWait to wait until element is present on the DOM as below :-
WebElement quick = new WebDriverWait(d, 10).until(ExpectedConditions.presenceOfElementLocated(By.id("magix_vf_root")));

Related

HtmlUnit does not load entire page

I have checked that HtmlUnit does not load part of this page:
https://www.milanuncios.com/mis-anuncios/
When inspected with a browser, the section:
<div class="ma-LayoutBasicMainContent">
Has into a lot of contents. But when loaded by HtmlUnit it is empty!
I have tried various webClient switches, including
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getOptions().setDownloadImages(true);
webClient.getOptions().setCssEnabled(true);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.setJavaScriptTimeout(10000);
But always with same result: The "ma-LayoutBasicMainContent" section is not loaded. This is the code I use:
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
class MarnvHtmlUnitTest {
public static void main(String[] args) {
WebClient webClient = null;
try {
final long javascriptTimeout = 10000;
webClient = new WebClient();
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getOptions().setDownloadImages(true);
webClient.getOptions().setCssEnabled(true);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.setJavaScriptTimeout(10000);
String loginURL = "https://www.milanuncios.com/mis-anuncios/";
System.out.println("Connecting to " + loginURL + " (" + webClient.getBrowserVersion() + ")");
HtmlPage page = webClient.getPage(loginURL);
System.out.print(" Waiting for Javascript to complete...");
long millis = System.currentTimeMillis();
webClient.waitForBackgroundJavaScript(javascriptTimeout);
System.out.println(System.currentTimeMillis() - millis + " milliseconds");
if (!page.asText().contains("gestiona tus anuncios")) {
System.out.println("ERROR!");
System.out.println(page.asXml());
System.out.println("EXITING. " + webClient.getWebWindows().size());
return;
}
System.out.println("OK");
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (webClient != null)
webClient.close();
}
}
}
In case of correct page loading, the page should contain the text "gestiona tus anuncios".
Note that the call to "waitForBackgroundJavaScript" returns inmediately, which for me it's strange... it normaly waits some seconds until the page is completely loaded. I am using HtmlUnit 2.36.0.

Load report failed- Crystal Report in c#

I have this application in C# on VS2012, in which I need to generate Crystal Report 13.0.x. This application has been running fine for last 2 years or so . Recently did some addons and after that its giving error
Load Report Fail
However strange thing is that , in a day around 100 times this Crystal report is generated and in between it gives out that error. After the whole application has to be exited and then it works fine too. Because of this I am not abel to replicate the error at me end.
Here my code:
public partial class ChangeOrderList : Form
{
ConnectionClass connectionclass = new ConnectionClass();
NewOrderBL NObl = new NewOrderBL();
DailySalesReportBL DSRbl = new DailySalesReportBL();
public ChangeOrderList()
{
InitializeComponent();
}
private void ChangeOrderList_Load(object sender, EventArgs e)
{
/////////////////////////To count Lunch Buffet///////////////////
DataTable dtlb = DSRbl.selectBuffet(DateTime.Today.Date.ToString(), DateTime.Today.Date.ToString());
string date = dtlb.Rows[0][0].ToString();
////////////////////////////////////////////////////////////////
try
{
string sqlqry = "Select KOTNo,TableNo,WaiterName,ItemCode,ItemName,Quantity,Status,Foodtype from tblOrderChange where KOTNo=#kotno and Quantity>'0.00' and (Category!='Appetizer' and Category!='Indian Breads' and Category!='Desserts' and Category!='Beverages' and Category!='Tandoori')";
SqlCommand cmd = new SqlCommand(sqlqry, connectionclass.con);
cmd.Parameters.AddWithValue("#kotno", NewOrderBL.KOTNo);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet1 ds = new DataSet1();
adapter.Fill(ds, "tblOrderChange");
if (ds.Tables["tblOrderChange"].Rows.Count == 0)
{
MessageBox.Show("No Data Found", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (deliverybl.order == "Delivery")
{
//PrintDelivery printorder = new PrintDelivery();
ChangeOrderdelivery printorder = new ChangeOrderdelivery();
printorder.SetDataSource(ds);
crystalReportViewer1.ReportSource = printorder;
System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
printorder.PrintOptions.PrinterName = printDocument.PrinterSettings.PrinterName;
printorder.PrintOptions.PrinterName = "EPSON TM-U220 Receipt";
printorder.PrintToPrinter(1, false, 0, 0);
}
else
{
crystalReportViewer1.RefreshReport();
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
paramField.Name = "LBqty";
paramDiscreteValue.Value = date;
paramField.CurrentValues.Add(paramDiscreteValue);
paramFields.Add(paramField);
PrintChangeOrderList printchangeorder = new PrintChangeOrderList();
printchangeorder.SetDataSource(ds);
printchangeorder.SetParameterValue("LBqty", date);
crystalReportViewer1.ReportSource = printchangeorder;
System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
printchangeorder.PrintOptions.PrinterName = printDocument.PrinterSettings.PrinterName;
printchangeorder.PrintOptions.PrinterName = "EPSON TM-U220 Receipt";
printchangeorder.PrintToPrinter(1, false, 0, 0);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally { connectionclass.disconnect(); }
onlinebl.crystalreport = "";
this.DialogResult = DialogResult.OK;
}
private void btnExit_Click(object sender, EventArgs e)
{
onlinebl.crystalreport = "";
this.DialogResult = DialogResult.OK;
}
I have been banging my head for long . Every where I search it says about the path and I am not using the path anywhere so not able to understand where the fault is.
If you need any more info or the code please let me know. Thanks
Check your class:
<pre>
ChangeOrderdelivery printorder = new ChangeOrderdelivery();
printorder.SetDataSource(ds);
crystalReportViewer1.ReportSource = printorder;
this one has a report Path hidding i guess
ChangeOrderdelivery printorder = new ChangeOrderdelivery();
</pre>
I just deleted internet temp files and after that client has not yet complained about the error. So I am keeping an eye on it if it resolved the issue

SparkStreaming either running 2 times the same command or mail sending 2 times same mail

My spark application sends two mails when I send just 1 string to my Kafka Topic. Here is the interested part of code:
JavaDStream<String> lines = kafkaStream.map ( [returns the 2nd value of the tuple];
lines.foreachRDD(new VoidFunction<JavaRDD<String>>() {
[... some stuff ...]
JavaRDD<String[]> flagAddedRDD = associatedToPersonRDD.map(new Function<String[],String[]>(){
#Override
public String[] call(String[] arg0) throws Exception {
String[] s = new String[arg0.length+1];
System.arraycopy(arg0, 0, s, 0, arg0.length);
int a = FilePrinter.getAge(arg0[CSVExampleDevice.LENGTH+People.BIRTH_DATE]);
int p = Integer.parseInt(arg0[CSVExampleDevice.PULSE]);
if(
((p<=45 || p>=185)&&(a<=12 || a>=70))
||
(p>=190 || p<=40)){
s[arg0.length]="1";
Mailer.sendMail(mailTo, arg0);
}
else
s[arg0.length]="0";
return s;
}
});`
I cannot understand if the mail sends two emails, because the transformation after this one is a save on file and this only return 1 line. The mailer.sendMail:
public static void sendMail(String whoTo, String[] whoIsDying){
Properties props = new Properties();
props.put("mail.smtp.host", "mail.***.com"); //edited
props.put("mail.smtp.port", "25");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("***my-email***")); //edited
for (String string : whoTo.split(","))
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(string));
message.setSubject(whoIsDying[PersonClass.TIMESTAMP]);
message.setText("trial");
System.out.println("INFO: sent mail");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
The reason this happens is because I called two actions at the end of the transformation:
FilePrinter.saveAssociatedAsCSV(associatedSavePath, unifiedAssociatedStringRDD.collect()); //first action
JavaRDD<String[]> enrichedWithWeatherRDD = flagAddedRDD.map(new Function<String[],String[]>(){ [some more stuff] });
JavaRDD<String> unifiedEnrichedStringRDD = enrichedWithWeatherRDD.map(unifyArrayIntoString);
FilePrinter.saveEnrichedAsCSV(enrichedSavePath, unifiedEnrichedStringRDD.collect()); //second action
and thus the whole transformation is called again and the mailer part is above both of these actions.

J2ME XML Parsing

I have another question about a "JDWP Error: 21" logged: Unexpected JDWP Error 21
I am trying to parse some XML I gather from a servlet into a J2ME MIDlet with the code below. So far unsuccessfully, I think due to the JDWP error on my HttpConnection how ever the InputStream is filled with XML and once parsed everything inside the Document is null.
Has anyone got and ideas about the JDWP error, and also does that code look like it should work?
In MIDlet I am using JSR-172 API javax.xml.parsers.*.
if(d==form1 && c==okCommand)
{
// Display Webpage
webPage = new TextBox(txtField.getString(),
"",
100000,
TextField.ANY
);
Display.getDisplay(this).setCurrent(webPage);
try
{
HttpConnection conn = (HttpConnection)Connector.open("http://localhost:8080/Blogging_Home/Interface?Page=Bloggers&Action=VIEW&Type=XML");
conn.setRequestMethod(HttpConnection.GET);
int rc = conn.getResponseCode();
getConnectionInformation(conn, webPage);
webPage.setString(webPage.getString() + "Starting....");
String methodString = getStringFromURL("");
if (rc == HttpConnection.HTTP_OK)
{
InputStream is = null;
is = createInputStream(methodString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document;
try
{
builder = factory.newDocumentBuilder();
document = builder.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
webPage.setString(webPage.getString() + "ERROR:" + rc);
}
}
catch(Exception ex)
{
// Handle here
webPage.setString("Error" + ex.toString());
}

groovy HTTP Builder not returning results

I have the following code in groovy
HTTPBuilder http = new HTTPBuilder("https://ronna-afghan.harmonieweb.org/_layouts/searchrss.aspx")
http.request(Method.GET, groovyx.net.http.ContentType.XML) {
// set username and password for basic authentication
// set username and password for basic auth
//http.auth.basic(ConfigurationHolder.config.passportService.userName,
// ConfigurationHolder.config.passportService.password)
headers.'User-Agent' = 'Mozilla/5.0'
uri.query = [k:'execution']
// response handler for a success response code:
response.success = {resp, xml ->
println resp.statusLine
log.debug "response status: ${resp.statusLine}"
log.debug xml.toString()
}
// handler for any failure status code:
response.failure = {resp ->
log.error " ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
when I run the code, it doesn't give me the rss feed which I'm suppose to get
When I have the same code in java
try {
// Create a URLConnection object for a URL
URL oracle = new URL(
"https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
it returns the xml Rss. I can't figure what the issue might be. Everything looks okay to me in the groovy code and also the Http return code is 200.
The code that you have described in Java is the equivalent of the following code in Groovy:
def oracle = "https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss".toURL().text

Resources