When I run this code with commented //driver = new PhantomJSDriver(desiredCapabilities);, All works fine. I can see only two "PhantomJS" system process.
2 process But if I run this code with uncommented driver = new PhantomJSDriver(desiredCapabilities);, The amount "PhantomJS" system processes more than 2 : more than 2 ... Why?
PhantomJsDriverManager.getInstance().setup();
Semaphore s = new Semaphore(2);
for (int i = 0; i < 10; i++) {
s.acquire();
new Thread() {
public void run() {
PhantomJSDriver driver = new PhantomJSDriver();
try {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
System.out.println("Start: " + getName());
desiredCapabilities.setJavascriptEnabled(true);
driver = new PhantomJSDriver(desiredCapabilities);
driver.get("https://community.oracle.com/");
driver.quit();
System.out.println("Stop: " + getName());
} catch (Exception e) {
driver.quit();
} finally {
driver.quit();
s.release();
}
}
}.start();
}
}
Related
I got the following code:
exch.setOnAction(e -> {
for (int i = 0; i < 10; i++) {
BrowserThread.driver.findElement(By.linkText("Premium Exchange")).click();
String strVal = BrowserThread.driver.findElement(By.id("premium_exchange_stock_wood")).getText();
String strVal2 = BrowserThread.driver.findElement(By.id("premium_points")).getText();
int intVal = Integer.parseInt(strVal);
int intVal2 = Integer.parseInt(strVal2);
if (intVal >= 64 && intVal2 >= 1) {
BrowserThread.driver.findElement(By.name("buy_wood")).clear();
BrowserThread.driver.findElement(By.name("buy_wood")).sendKeys("64"); //enter 64 in the 'buy box'
BrowserThread.driver.findElement(By.xpath("//input[#value='Calculate best offer ']")).click(); //click calculate best offer
BrowserThread.driver.findElement(By.xpath("//div[#id='premium_exchange']/div/div[2]/button")).click(); //click buy
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(BrowserTab.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
LogTab.log.appendText("Not enough premium points.\n");
}
if (stop.isPressed()) {
LogTab.log.appendText("Stopped task.\n");
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(MarketTab.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
It basically refreshes a webpage infinitely when a button is pressed on the GUI.
There is a button to start the loop (exch), and a button to break the loop (stop). But my problem is, the GUI freezes when it executes tasks on the browser. This applies to everything, not just this for-loop.
For example, I have a run-button to open the selenium web browser. The GUI freezes until the web browser has loaded completely.
I checked around and found out I have to use threads, but I have no idea where to start. I tried making a separate class for the browser to run on a different thread, but that didn't work and I can't seem to find out what I did wrong.
BrowserThread class:
public class BrowserThread extends Thread {
static WebDriver driver;
private String baseUrl;
private String browsertype;
public BrowserThread(String name, String browsertype) {
super(name);
this.browsertype = browsertype;
}
// set up method to initialize driver object
public void setUp(String browsertype) throws Exception {
if (browsertype.contains("Chrome")) {
System.setProperty("webdriver.chrome.driver","res\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browsertype.contains("PhantomJS")) {
driver = new PhantomJSDriver();
System.setProperty("phantomjs.binary.path", "res\\phantomjs.exe");
} else if (browsertype.contains("PhantomJS Linux")) {
driver = new PhantomJSDriver();
System.setProperty("phantomjs.binary.path", "res/phantomjs.exe");
}
baseUrl = "https://www.google.com/";
driver.get(baseUrl);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am learning appium and trying to call an object from one class to another and facing null pointer exception.
Below is my code :
public class TestCommons {
public AndroidDriver driver;
public void setUp() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "MotoE");
File file = new File("D:/APK1/com.vector.guru99.apk");
capabilities.setCapability("app", file);
try {
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public void tearDown() {
driver.closeApp();
}
}
I wanted to use above class i.e "TestCommons" in other class. I want to use driver object.
Second class is below :
public class Day03 extends TestCommons {
TestCommons commons = new TestCommons();
#BeforeClass
public void beforeClass() {
commons.setUp();
}
#Test(enabled = true)
public void f() {
if (driver.findElement(By.id("com.vector.guru99:id/action_quiz")).isDisplayed()) {
System.out.println("Quiz is displayed");
driver.findElement(By.id("com.vector.guru99:id/action_quiz")).click();
System.out.println("quiz is click");
}
}
#AfterClass(enabled = true)
public void afterClass() {
commons.tearDown();
}
}
Getting null pointer in second program #:
if(driver.findElement(By.id("com.vector.guru99:id/action_quiz")).isDisplayed();
Can anyone clarify me please.
You have one of two issues.
1) driver was not set properly in setUp(). If this is the case you probably got an exception. Check your logs to make sure that there isn't an exception there.
2) driver.findElement(By.id("com.vector.guru99:id/action_quiz")) is returning null. You can check this by setting a debug point and running evaluate expression on that call.
try this way:
public class TestCommons {
public static AndroidDriver driver;
#BeforeClass
public void setUp() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "MotoE");
File file = new File("D:/APK1/com.vector.guru99.apk");
capabilities.setCapability("app", file);
try {
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#AfterClass
public void tearDown() {
driver.closeApp();
}
}
public class Day03 extends TestCommons {
#Test(enabled = true)
public void f() {
if (driver.findElement(By.id("com.vector.guru99:id/action_quiz")).isDisplayed()) {
System.out.println("Quiz is displayed");
driver.findElement(By.id("com.vector.guru99:id/action_quiz")).click();
System.out.println("quiz is click");
}
}
}
I'm new in java, using it for automatic tests. Please help me what I'm doing wrong with this code?
public static WebDriver driver = null;
public static WebDriver getDriver() {
if (driver == null) {
File fileIE = new File("src//test/java/iedriver.exe");
System.setProperty("webdriver.ie.driver", fileIE.getAbsolutePath());
}
try {
driver = new InternetExplorerDriver();
}
catch (Exception e)
e.printStackTrace();
}
Try to add DesiredCapabilities to your code.
if (driver == null) {
File fileIE = new File("src//test/java/iedriver.exe");
System.setProperty("webdriver.ie.driver", fileIE.getAbsolutePath());
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
try {
driver = new InternetExplorerDriver(ieCapabilities);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
the DesiredCapabilities help to set properties for the WebDriver. A typical usecase would be to set the path for any type of the WebDriver if your local installation doesn't correspond to the default settings.
You can read about class DesiredCapabilities and about its' using here: DesiredCapabilities
Hi I need to call a method "loop()" 500 times. Do I need to write "loop();" 500 times or is there any method to call it multiple times. Please help with this. The following code is in java and I am doing this with selenium webdriver.
public class Salesforce_login {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:/Users/Master/Desktop/chromedriver.exe");
driver = new ChromeDriver();
// driver = new FirefoxDriver();
Thread.sleep(1000);
// driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://login.com");
driver.findElement(
By.xpath(".//*[#id='loginSwitcher:loginSwitcherForm']/div[1]/div[1]/div/a"))
.click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='username']")).sendKeys(
"*****");
driver.findElement(By.xpath(".//*[#id='password']")).sendKeys(
"*****");
driver.findElement(By.xpath(".//*[#id='Login']")).click();
Thread.sleep(30000);
driver.findElement(By.xpath(".//*[#id='moreGroupMembersLink']"))
.click();
Thread.sleep(1000);
loop();
loop();
loop();
loop();
}
public static void loop() throws InterruptedException{
for (int i = 1; i < 25; i++) {
System.out.println(driver
.findElement(
By.xpath(".//*[#id='groupMembersDialogContent']/div/div[1]/div[2]/div/table/tbody/tr["+i+"]/td[2]/div/a"))
.getAttribute("href"));
}
driver.findElement(By.xpath(".//*[#id='groupMembersDialogContent']/div/div[1]/div[3]/div/span[2]/span[1]/a")).click();
Thread.sleep(2000);
}
}
for(int i = 0; i < 500; i++) {
loop();
}
I'm trying to setup a producers/consumers using the selenium webdriver as queries/browsers.
While running the following code, not all the queries are actually entered even though the output says they are. Some queries also either get doubled ( i.e. "Fish" becomes "FisFishh" ).
APP
public class App {
public static void main(String[] args) {
DriverHashMap.init();
Executor exec = new Executor();
// Add queries to list
Query query = new Query(exec);
query.addQuery("Cats");
query.addQuery("Dogs");
query.addQuery("Fish");
// query.addQuery("Bats");
// query.addQuery("Rats");
// query.addQuery("Geese");
ExecutorService threadPool = Executors.newFixedThreadPool(4);
// Submit queries to pool
Future queryStatus = threadPool.submit(query);
// Start browsers
threadPool.execute(new Browser("1", exec));
threadPool.execute(new Browser("2", exec));
// this will wait for the producer to finish its execution.
try {
queryStatus.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// Wait for pool to finish
threadPool.shutdown();
}
}
BROWSER
public class Browser implements Runnable {
private String name;
private Executor exec;
private static WebDriver driver;
private static String baseURL = "http://www.google.com";
private static String query;
public Browser(String name, Executor exec) {
synchronized (this) {
this.name = name;
this.exec = exec;
System.out.println("\tStart Browser-" + this.name);
driver = new FirefoxDriver();
// Wait up to 30 seconds for a response
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
DriverHashMap.addDriver(name, driver);
System.out.println("\tAdded Browser-" + name + " to hashmap");
}
}
private void enterQuery() {
synchronized (this) {
// Get driver for this browser
driver = DriverHashMap.getDriver(this.name);
System.out.println("Browser " + this.name
+ " entering query from executor: " + query);
// Search field qbqfq
driver.findElement(By.id("gbqfq")).clear();
// Enter query
driver.findElement(By.id("gbqfq")).sendKeys(query);
// Click search button
driver.findElement(By.id("gbqfb")).click();
}
}
public void run() {
try {
synchronized (this) {
// Receive first query
driver = DriverHashMap.getDriver(this.name);
query = exec.get();
System.out.println("Browser " + this.name
+ "\n\rReceived first query from executor: " + query);
}
do {
synchronized (this) {
// Process query
driver = DriverHashMap.getDriver(this.name);
driver.get(baseURL);
enterQuery();
}
synchronized (this) {
// Receive next query
query = exec.get();
driver = DriverHashMap.getDriver(this.name);
System.out.println("Browser " + this.name
+ "\n\rReceived new query from executor: " + query);
}
} while (query != null);
// Close this browser
synchronized (this) {
driver = DriverHashMap.getDriver(this.name);
System.out.println("Browser " + this.name
+ " finished its job; terminating.");
driver.close();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
QUERY
public class Query implements Runnable {
private Executor exec;
private List<String> queries = new ArrayList<String>();
public Query(Executor exec) {
this.exec = exec;
}
public void addQuery( String query ) {
System.out.println("Adding " + query + " to queries");
queries.add( query );
}
public void run() {
Iterator it = queries.iterator();
String currQuery = new String();
try {
while( it.hasNext()) {
currQuery = (String)it.next();
System.out.println("Adding " + currQuery + " to Executor");
exec.put(currQuery);
}
this.exec.continueProducing = Boolean.FALSE;
System.out.println("Query has finished its job; terminating.");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
EXECUTOR
public class Executor {
public ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(
100);
public Boolean continueProducing = Boolean.TRUE;
public void put(String query) throws InterruptedException {
this.queue.put(query);
}
public String get() throws InterruptedException {
return this.queue.poll(1, TimeUnit.SECONDS);
}
}
Webdriver is not threadsafe per se. Try wrapping it into a ThreadLocal.
That has helped me a lot in a similar situation.