proc.wait(10,TimesUnit.Seconds) is not working and its not destroying firefox.exe. here's my code. Can somebody tell me what I am doing wrong? When I execute the code, Firefox just opens and the program finishes. It should destroy the process Firefox after 10 seconds. Is the code correct as it should be?
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.io.*;
import java.lang.management.*;
public class JavaFirefox
{
public static void main(String args[])
{
try
{
System.out.println("Creating Process");;
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("C:/Program Files/Mozilla Firefox/firefox");
proc.waitFor(10,TimeUnit.SECONDS);
proc.destroy();
}
catch (Exception t)
{
t.printStackTrace();
}
}
}
I am expecting that when firefox opens it will wait for 10 seconds and then it will destroy the process.
The issue has been resolved. Strangely the code was correct. I just changed my default browser from Firefox and to Google Chrome and the code started working.
Related
I've tried to debug Runtime.getRuntime().addShutdownHook(unfortunateHook); in sample tapestry application created with Maven quickstart, but it seems that it doesn't work - Debugger doesn't stop at trap set to line set at LOGGER.debug("In the main hook!!!");
Example code:
package org.example.spring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class App extends SpringBootServletInitializer {
private static final Logger LOGGER= LoggerFactory.getLogger(App.class);
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AppConfiguration.class);
}
public static void main(String[] args) throws Exception {
Thread unfortunateHook = new Thread(() -> {
LOGGER.debug("In the main hook!!!");
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
});
Runtime.getRuntime().addShutdownHook(unfortunateHook);
LOGGER.debug("Simple log statement with inputs {}, {} and {}", 1,2,3);
SpringApplication application = new SpringApplication(App.class);
SpringApplication.run(App.class, args);
}
}
Is it possible to debug code inside shutdown hook thread? I'm using InteliJ Idea 2022.01. Killing application with standard Intelij Idea way (red square).
Ok, after some more digging I have found this: https://youtrack.jetbrains.com/issue/IDEA-170313/Breakpoints-not-working-after-stop-signal and many more simmilar threads.
In short, Idea is disconnecting debugger in a moment that you click red square and sends signal to app to kill itself. Because of these, traps are not working any more.
Workaround to this is to send kill signal from external source. In Linux it's pretty easy but in windows (which is I'm using) you should:
Put a break point any place in your code that will be executed
When code stops at your trap, you go to "evaulate expression" (alt+f8 or from degug acctions) and write System.exit(0)
You breakpoint may need to be set up as a thread one - to do that, click right button on it and switch to "Thread"
Then breakpoint should work.
I am a total noob at Automation Testing and i am trying to learn through Youtube how to do it.
https://youtu.be/FRn5J31eAMw?t=12405
On this course from Edureka there is an example where they are trying to handle an exception, where after they run the script the system shows them a message in the console which i cannot get.
package co.edureka.selenium.demo;
import java.util.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingExceptions {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
Thread.sleep(3000);
try {
driver.findElement(By.name("fake")).click();
}catch (NoSuchElementException e) {
System.out.println("element is not found");
System.out.println("Hello");
//throw(e);
}
System.out.println("Hello");
}
}
this is the script in Java they are running and at the end in the console they are getting this as a result
Edureka Console
But i am getting something totally different even though my code is exactly the same.
My Console
What am i doing wrong?
your are using "import java.util.NoSuchElementException;
" at top of file so please remove and use below one
org.openqa.selenium.NoSuchElementException
I'm currently taking my first automated test class and the instructor has us creating a program in Eclipse after loading Selenium and create a step in the program to look at an executable to bring up chrome then designate a website to check. It looks like i am stuck in a loop?
Here is the program:
java program
Here is the result:
program result
any and all help would be appreciated. Thank you for your time.
I think this is what you want
This code is to open the default browser and go to a specific link
You can specify the path of any browser you want from the path in the code
import java.awt.Desktop;
import java.net.URI;
public class openBrowser {
public openBrowser() {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("https://www.google.com"));
}
}catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[]args) {
new openBrowser();
}
}
For your code you can follow the following steps
Download ChromeDriver from here
Extract the zip file and follow the path ( because it is easy ) C:\\chromeDriver\\chromedriver.exe
include the ChromeDriver location in your PATH environment variable
Download the required Libraries from the following junit openqa
Add the Libraries to your project ( Build Path )
then this is your code
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.junit.Test;
public class WebDriverDemo {
#Test
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\chromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(WebDriverDemo.class.getName()).log(Level.SEVERE, null, ex);
}
driver.quit();
}
}
During the implementation of the code in the eclipse, many problems occurred, so I advise you to implement the project on NetBeans
I use Java 8 and Windows 8.1
This is my code.
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "data/chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "logs/ss/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
}
All time when driver.get() throw TimeoutException I want to take a screenshot at browser.
But when throw TimeoutException, getScreenshotAs() from printSS() don't take screenshot because throw another TimeoutException.
Why getScreenshotAs() throw TimeoutException and how to take screenshot at browser
P.S.: Increase pageLoadTimeout time is not the answer I want.
While working with Selenium 3.x, ChromeDriver 2.36 and Chrome 65.x you need to mention the relative path of the location (with respect of your project) where you intend to store the screenshot.
I took you code and did a few minor modification as follows :
Declared driver as WebDriver instance as static and added #Test annotation.
Reduced pageLoadTimeout to 2 seconds to purposefully raise the TimeoutException.
Changed the location of String path to a sub-directory wthin the project scope as follows :
String path = "./ScreenShots/";
Added a log as :
System.out.println("Screenshot Taken");
Here is the code block :
package captureScreenShot;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class q49319748_captureScreenshot
{
public static WebDriver drive;
#Test
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "./ScreenShots/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
System.out.println("Screenshot Taken");
}
}
Console Output :
[TestNG] Running:
C:\Users\username\AppData\Local\Temp\testng-eclipse--153679036\testng-customsuite.xml
Starting ChromeDriver 2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91) on port 42798
Only local connections are allowed.
Mar 16, 2018 5:37:59 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Screenshot Taken
PASSED: test1
Screenshot :
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
The problem is that while Selenium waits for the page to complete loading it cannot take any other command. This is why it throws TimeoutException also from the exception handler when you try take the screenshot.
The only option I see is to take the screenshot not through Selenium, but using other means that take a screenshot of the entire desktop. I've written such a thing in C#, but I'm pretty sure you can either find a way to do it in Java too.
Edit: Got it to work. My problem was I was using cmd to compile which exited the vm before the delay ended. Switched to jGrasp and the program worked as intended. Next I need to learn how to actually make a java applet to properly run on my computer. Thanks for your help everyone
I'm trying to set an alarm of sorts using java. I'd like to open a webpage after a set delay. The code below compiles and runs without errors or warnings but running the code does nothing. Just starts and stops the program. I have a feeling the issue arises from how I catch the exceptions but I'm not sure. I also am a little lost on what the actionPerformed() method does. Any help or insight is greatly appreciated
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.IOException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
public class YtAlarmTest
{
public static void main (String [] args)
{
String url = "https://stackoverflow.com/questions/ask";
int delay = 1000;
ActionListener task = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
try
{
if (Desktop.isDesktopSupported())
{
Desktop.getDesktop().browse(new URI(url));
}
}
catch (URISyntaxException e)
{
System.out.println("exception");
}
catch (IOException e)
{
System.out.println("exceptio");
}
}
};
new Timer(delay, task).start();
}
}