I access Websites in a loop via selenium Java based. Some of the sites crash imediately so that i get the error
[1618982990.911][WARNING]: Timed out connecting to Chrome, retrying...
after a short time.
So this is not a selenium issue i assume, since even chrome crashes if i visit the site manually because of js errors, saying unresonsive Website
My problem is, that every time a site crashes, chromedriver and a chrome instance will stay alive so that i have high CPU usage after a short time.
Can i tell selenium to quit the instance if it is frozen? But i dont know how this should be possible if it does not get answer from chrome anymore?
Thankful for any solution or idea
Sometimes with some Windows version driver.quit() will not kill the chrome process which I have come across.
So at the end of the script you can kill the chrome processes if exists using java code, if the driver.quit doesn't work.
Please refer stackoverflow link which has the code to kill the process if exists in Java and pass the chrome process to it.
i found a workaround for anyone who would be interested. First setting up a pageLoadTimeout, after that force any chrome instance to be killed if an Exception is being thrown.
try{
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
//some excecution code....
}
catch (Exception e) {
System.out.println("Error. Closing");
driver.quit();
Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");}
timerChromeKillListener = new Timer();
timerChromeKillListener.schedule(new TimerTask()
{
#Override
public void run()
{
if (driver != null)
{
try
{
final Logs logs = driver.manage().logs();
final LogEntries driverLog = logs.get("driver");
if (driverLog != null)
{
final List<LogEntry> logEntries = driverLog.getAll();
for (final LogEntry logEntry : logEntries)
{
final String message = logEntry.getMessage();
if (message.contains("Unable to evaluate script: disconnected: not connected to DevTools") || message.contains("Timed out connecting to Chrome, retrying..."))
{
disconnect();
}
}
}
}
catch (Exception ignored)
{
}
}
}
} , 1 , 100);
Related
I have trying trouble with trying to run Selenium in headless mode. I have using a find element for an out of stock button, when I run normal with the headless option commented out, I get expected behavior. When I run in headless, I get the wrong result. This is on the new Selenium beta for Java. (4.0) I'm using the beta because the old version does not have options to run Edge headless.
I have tried setting a duration, just takes longer to get the same wrong answer. And I have tried enabling the window size to full screen. No dice.
public class BestBuy extends Thread
{
public static void main(String[] args)
{
System.setProperty("webdriver.edge.driver", "Driver file path");
final EdgeOptions edgeOptions = new EdgeOptions();
//edgeOptions.addArguments("--headless");
WebDriver BestBuyDriver = new EdgeDriver(edgeOptions);
BestBuyDriver.get("https://www.bestbuy.com/site/dyson-airwrap-complete-styler-for-multiple-hair-types-and-styles-fuchsia-nickel/6284230.p?skuId=6284230");
try
{
List<WebElement> buttonText = BestBuyDriver.findElements(By.xpath("//button[text()='Sold Out']"));
List<WebElement> text = BestBuyDriver.findElements(By.xpath("//*[contains(text(),'Sold Out')]"));
//BestBuyDriver.findElement(By.className("btn-disabled"));
if(buttonText.size() > 0 || text.size() > 0)
System.out.println("Item out of stock");
else
System.out.println("Item in Stock");
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
System.out.println("Exception");
}
}
}
I am using Epson_JavaPOS_ADK_11414_for_Linux_x64 for installing the JavaPOS with pcs ( sh installJavaPOSFull-64.sh )
I ran this program one after the other in different shells and the second process crashes for some reason:
import jpos.JposException;
import jpos.POSPrinter;
import jpos.util.JposPropertiesConst;
import java.time.Duration;
import java.time.Instant;
public class POSPrinterClaimTest {
static POSPrinter posPrinter;
private static Boolean isOpen = false;
private static Boolean isClaimed = false;
private static Boolean isEnabled = false;
static {
System.setProperty(
JposPropertiesConst.JPOS_POPULATOR_FILE_PROP_NAME, "jpos.xml");
}
public static void main(String[] args) {
try {
posPrinter = new POSPrinter();
Instant start = Instant.now();
Instant finish = null;
Long timeElapsed = null;
openConnection("POSPrinter1");
finish = Instant.now();
timeElapsed = Duration.between(start, finish).toMillis();
System.out.println("Time taken to connect : " + timeElapsed.toString());
Thread.sleep(100000L);
terminate();
System.out.println("terminated from try block");
} catch (JposException | InterruptedException e) {
e.printStackTrace();
try {
terminate();
System.out.println("terminated from catch block");
Thread.sleep(5000);
} catch (JposException | InterruptedException jposException) {
jposException.printStackTrace();
}
} catch(Throwable t){
t.printStackTrace();
} finally {
posPrinter = null;
}
}
private static void openConnection(String printerName) throws JposException {
try {
String printerNamesss = printerName;
/**
* open the printer object according to the device logical name defined in jpos.xml
*/
posPrinter.open(printerName);
isOpen = true;
System.out.println("opened");
/**
* Get the exclusive control right for the opened device.
* Then the device is disable from other application.
* */
posPrinter.claim(3000);
isClaimed = true;
System.out.println("claimed");
/**
* enable the device for input and output
*/
posPrinter.setDeviceEnabled(true);
isEnabled = true;
System.out.println("enabled");
} catch (JposException jposException) {
System.out.println("jpos exception in open : " + jposException.getMessage());
throw jposException;
} catch(Throwable t) {
System.out.println("unknown throwable open: " + t.getMessage());
}
}
public static void terminate() throws JposException {
try {
if(isOpen && isClaimed) {
posPrinter.clearOutput();
System.out.println("cleared output");
}
if(isEnabled) {
posPrinter.setDeviceEnabled(false);
isEnabled = false;
System.out.println("setDeviceEnabled false");
}
if(isClaimed) {
posPrinter.release();
isClaimed = false;
System.out.println("released");
}
if(isOpen) {
posPrinter.close();
isOpen = false;
System.out.println("closed");
}
} catch (JposException jposException) {
jposException.printStackTrace();
throw jposException;
} catch(Throwable t) {
System.out.println("unknown throwable terminate: " + t.getMessage());
}
}
}
First process output
opened
claimed
enabled
Time taken to connect : 7928 --> now I start the second process.
cleared output
setDeviceEnabled false
released
closed
terminated from try block
Second process output
opened
jpos exception in open : The port is already open.
jpos.JposException: The port is already open.
at jp.co.epson.upos.core.v1_14_0001.pntr.CommonUPOSExceptionCreator.createJposException(CommonUPOSExceptionCreator.java:138)
at jp.co.epson.upos.core.v1_14_0001.pntr.CommonUPOSExceptionCreator.createJposException(CommonUPOSExceptionCreator.java:99)
at jp.co.epson.upos.core.v1_14_0001.pntr.CommonPrinterService.openPort(CommonPrinterService.java:3341)
at jp.co.epson.upos.core.v1_14_0001.pntr.CommonPrinterService.claim(CommonPrinterService.java:3103)
at jpos.BaseJposControl.claim(Unknown Source)
at POSPrinterClaimTestThreads.openConnection(POSPrinterClaimTestThreads.java:73)
at POSPrinterClaimTestThreads.test(POSPrinterClaimTestThreads.java:36)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
closed
terminated from catch block
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007f43880ea9df, pid=12119, tid=0x00007f43690b0700
#
# JRE version: OpenJDK Runtime Environment (8.0_252-b09) (build 1.8.0_252-b09)
# Java VM: OpenJDK 64-Bit Server VM (25.252-b09 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C [libethernetio31.so+0x1f9df] CCommonPort::PortEvent(unsigned int, unsigned int, unsigned int*, unsigned int, unsigned char*)+0xf
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /POSPrinterTest/JavaPOS/hs_err_pid12119.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
#
Aborted
If you see the second process throws a JposException which then initiates its catch and closes the connection. Then it suddenly crashes instead of sleeping for 5sec.
Any help?
After discussing this problem with EPSON team, they were able to provide a fix for the same with a new libepsonjpos.so and epsonjpos.jar
It solved two problems for me:
The original claim issue in the post - resolved after using the latest libepsonjpos.so
Multi-threaded printing in a single process in non-install mode (No-SetupPOS-insall)
the Epson team said to synchronize the POSPrinter.open() in all the threads and update the epsonjpos.jar with their fix
Some quotes on the issue from Epson Team.
Multi-thread issue - "Change History
The fix that has been applied is in the device sharing logic. Only affects lite-mode (No-SetupPOS version)
The different objects falsely assumed as equal. As result only the first connected printer has been used.
The fix corrects that comparison logic."
Claim Issue - "We are glad we could help you.
As for the background of the issues. The multi-process usage with non-install mode was a corner case for our JavaPOS ADK. With your help we could improve our testing cases."
Epson team said that they will release the patches in the next version.
It seems that the exclusive control processing of JavaPOS Service Object does not work well.
You should get a timeout error instead of an error that the port is already open.
However, your program is also bad.
The range of one try, catch is too wide.
JposException takes the form of an exception, but it's really just an error code notification.
Just because a JposException was signaled does not mean it crashes.
Most of the time, it will work if you eliminate the cause of the error and try again.
To be correct, try and catch each method call and property access.
The Epson_JavaPOS_ADK sample program should have been made that way.
Please code the same as the sample program.
In Addition:
Is what you see different?
It does try and catch in small units for each method and property, and does not propagate it to the top with throw.
Some of the sources I have are:
from "Epson_JavaPOS_ADK_11414_for_Linux_x64\Sample\Samples\Printer\PrinterSample_Step15\src\printersample_step15\Step15Frame.java"
// JavaPOS's code for Step7
// Set OutputCompleteEvent listener
ptr.addOutputCompleteListener(this);
// JavaPOS's code for Step7--END
// JavaPOS's code for Step10
try {
//Open the device.
//Use the name of the device that connected with your computer.
ptr.open("POSPrinter");
}
catch(JposException ex){
JOptionPane.showMessageDialog(this, "This device has not been registered, or cannot use.",
"",JOptionPane.WARNING_MESSAGE);
//Nothing can be used.
changeButtonStatus();
return;
}
try {
//Get the exclusive control right for the opened device.
//Then the device is disable from other application.
ptr.claim(1000);
bCoverSensor = ptr.getCapCoverSensor();
}
catch(JposException ex){
JOptionPane.showMessageDialog(this, "Fails to get the exclusive access for the device.",
"",JOptionPane.WARNING_MESSAGE);
//Nothing can be used.
changeButtonStatus();
return;
}
Extracting the situation from the comment and posting:
Well, the error reported by Claim may be wrong, so why not contact EPSON support with detailed information about such a situation?
From OP:
Done that already but we don't know if they will respond back. So trying to find answer here; somewhere. :D
From OP:
I ran the same program in a single process with multiple threads in two pulses. I do now get the timeout error as you said. Only in different processes scenario, I am getting a crash
If so, there may be a problem with the interprocess exclusive control of the JavaPOS service object. That's the problem with it, but the crash could be a cleanup issue at the end of the exception, as I commented earlier. When an exception occurs in the Claim method, instead of ending the process by propagating the exception, call the Close method and try other cleanup to end normally.
From OP:
I wrote the posPrinter.close() in claim catch block. It worked and crash frequency reduced significantly when doing with two processes single threads. Still the crash happened once or twice. But in two processes each with 10 threads trying to claim printer results in one process able to claim and the other process crashing. try{ posPrinter.claim(3000); } catch(JposException ex) { posPrinter.close();}
It seems that the problem of exclusive control of JavaPOS service object of EPSON may remain. Please make additional inquiries to EPSON based on such survey information.
I am testing around with PhantomJS a bit.
But I am not sure how to make it work with a java application, th examples I have found are mostly just against files or sites.
So this is what I have now.
var page = require('webpage').create();
address = "http://localhost:8080/logon.do";
page.open(address, function(status) {
wait(5000);
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementsByTagName('html')[0].outerHTML;
});
console.log(ua);
}
phantom.exit();
});
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
Now I know this wait is ugly but it is not important right now.
The server is running and if I go to the url I get a log in page.
I was expecting this log in page to be the output of console.log(ua);
Instead I get the output:
<-html><-head><-/head><-body><-/body><-/html>
What am I missing?
OK this turned out to be very secific for our application so lets close this.
Sascha, yes it is the script called by phantomjs which in turn
Hello I want to learn how to switch in in to a new windows without using thread sleep. I was trying to use awaitility artifact but I was not able to done it correctly. I was trying to automate print window. When I click on print icons on my web page I navigate to print window I want to wait while navigating to print window and once print window displayed I want to click on cancel button. Can someone help me for that
Print_icon.click();
await().atMost(10,TimeUnit.SECOND).pollInterval(1,TimeUnit.SECONDS);
Cancel_button.click();
You can try this :
Print_icon.click();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
boolean elmnt = false;
boolean timeOut = false;
int second = 1;
do {
try {
if(second>30) {
timeOut = true;
}
Cancel_button.click();
elmnt=true;
} catch (Exception e) {
TimeUnit.SECONDS.sleep(1);
second++;
}
}while(elmnt==false && timeOut==false);
You can't handle windows dialogs so I suggest you review your page code and find the name of the method that opens the print window and override it. In your test case for example you can override print method to do nothing, like this:
((JavascriptExecutor)driver).executeScript("window.print=function(){};");
Working on a imgui port in kotlin, I have a metrics menu where I display the number of allocations
This is the init code I wrote:
try {
var ac: AttachingConnector? = null
for (x in Bootstrap.virtualMachineManager().attachingConnectors()) {
if (x.javaClass.name.toLowerCase().indexOf("socket") != -1) {
ac = x
break
}
}
if (ac == null) {
throw Error("No socket attaching connector found")
}
val connectArgs = HashMap<String, Argument>(ac.defaultArguments())
connectArgs["hostname"]!!.setValue("127.0.0.1")
connectArgs["port"]!!.setValue(Integer.toString(3001))
connectArgs["timeout"]!!.setValue("3000")
vm = ac.attach(connectArgs)
} catch (error: Exception) {
System.err.println("Couldn't retrieve the number of allocations, $error")
}
And these are the arguments I pass in as 'VM options'
-Xdebug -Xrunjdwp:transport=dt_socket,address=3001,server=y,suspend=n
Whenever I run it normally, it works. But if I run it in debug mode, it doesnt, returning the following error:
java.net.ConnectException: Connection refused: connect
I couldn't find yet a solution for that, at the moment I simply display a -1 to indicate an error
Does anyone have a solution/explanation about?
Specs:
Kotlin 1.2-m1
Idea 2017.2.1
I guess the problem is that you try to use the same port for the debugger as the one used by the program. Try to use a different port for the debugger.