How do i identify download is not completed /in progress ? because i want to close web driver after download finished.
WebDriver: Chrome
sample code like this ,assume chrome driver setup is ready.
#Test
public void testDownloadPdf(){
// here is the selenium java code to download pdf.
// when do i perform driver.close();
}
In general, better close the driver in #AfterClass.
If you know the exact file name and expected location, you can use Paths
String file_path_full = "C:\\users\\username\\downloads\\yourpdffile.pdf";
while(Files.notExists(Paths.get(file_path_full))) {Thread.sleep(10000);}
I found this... it work in my case
here i'm using FileUtils.sizeOfDirectory(downloadfolder) it will return size of directory and will check after every 5 sec is the size is equal or not.if file size is equal then download is completed .
private void waitForDownloadFinished() throws Exception {
try {
String path = "/Download/path/";
if (path != null) {
File folder = new File(path);
long size, reSize;
do {
size = FileUtils.sizeOfDirectory(folder);
Thread.sleep(5000);
reSize = FileUtils.sizeOfDirectory(folder);
} while (size != reSize);
System.out.println("Download completed");
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
getWebBrowser().quit();
}
}
Related
When i try to run my scripts and call this method, when i enter URL into address bar, loading starts and loading take much time,
but sometime when refresh page page proper loaded on the spot so please help me out.
How can i handle this issue in automation.
public static MainPage LaunchBrowserAndLogin(String currentScriptName, String LoginUser) throws Throwable {
try {
killprocess();
LaunchBrowser();
String siteUrl = null;
if (excelSiteURL != null) {
if (excelSiteURL.equalsIgnoreCase("")) {
siteUrl = CONFIG.getProperty("siteName");
}else{
if (excelSiteURL.contains("SiteName")) {
siteUrl=excelSiteURL;
}
}
} else {
siteUrl = CONFIG.getProperty("SiteName");
}
driver.get("https://QA.YYYY.com/ABC9/#/login");
System.out.println("URL for Login: "+siteUrl);
CheckErrorPageNotFound();
driver.manage().timeouts().pageLoadTimeout(Long.parseLong(CONFIG.getProperty("pageLoadTime")), TimeUnit.SECONDS);
enterUserID(currentScriptName, LoginUser);
enterPasswd(currentScriptName);
MandatoryFieldSkipErrMsg("~~~~~~ Mandatory Field is skipped, Getting Error: ");
ClickLoginButton();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
}catch(){
DesireScreenshot("AfterClickOnLoginButton");
String stackTrace = Throwables.getStackTraceAsString(t);
String errorMsg = t.getMessage();
errorMsg = "\n\n\n\n Login failed.See screenshot 'LoginFailed' \n\n\n\n" + errorMsg + stackTrace;
Exception c = new Exception(errorMsg);
ErrorUtil.addVerificationFailure(c);
killprocess();
IsBrowserPresentAlready = false;
throw new Exception(errorMsg);
}
return new MainPage(driver);
}
First you need to check whether page is fully loaded or not in that case we will use the below code.
new WebDriverWait(driver, 5).until(webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Then as per your question I believe that some web elements are not properly getting loaded. So what you can do add one more explicit wait and put that wait inside try catch block as shown below.
try
{
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(By.id("Abhishek")));
System.out.println("Completed");
}
catch( TimeoutException e)
{
System.out.println("Reloading");
driver.navigate().refresh();
}
If it is unable to find that element then in the catch block it will refresh the page and in this way you can proceed further.
Note: I could have written the script for you but application url is invalid.
using java 8, tomcat 8
Hi, i am loading a file using properties, but i have a check before loading which returns the same properties object if its already been loaded (not null). which is a normal case scenario but i want to know if there is any way that if any change occur in target file, and some trigger should be called and refreshes all the properties objects. here is my code.
public static String loadConnectionFile(String keyname) {
String message = "";
getMessageFromConnectionFile();
if (propertiesForConnection.containsKey(keyname))
message = propertiesForConnection.getProperty(keyname);
return message;
}
public static synchronized void getMessageFromConnectionFile() {
if (propertiesForConnection == null) {
FileInputStream fileInput = null;
try {
File file = new File(Constants.GET_CONNECTION_FILE_PATH);
fileInput = new FileInputStream(file);
Reader reader = new InputStreamReader(fileInput, "UTF-8");
propertiesForConnection = new Properties();
propertiesForConnection.load(reader);
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
} finally {
try {
fileInput.close();
} catch (Exception e) {
Utilities.printErrorLog(Utilities.convertStackTraceToString(e), logger);
}
}
}
}
the loadConnectionFile method executes first and calls getMessageFromConnectionFile which has check implemented for "null", now if we remove that check it will definitely load updated file every time but it will slower the performance. i want an alternate way.
hope i explained my question.
thanks in advance.
Java has a file watcher service. It is an API. You can "listen" for changes in files and directories. So you can listen for changes to your properties file, or the directory in which your properties file is located. The Java Tutorials on Oracle's OTN Web site has a section on the watcher service.
Good Luck,
Avi.
I am working in a old project.The project is in Spring MVC .In the project I have to generate a pdf file from a jsp page and store in a location and download that file. For that I am using wkhtmltopdf tool to convert the one specific jsp page into pdf format. Using wkhtmltopdf sometime works fine, it generate the pdf in specific location, but sometime it require more time. Also when I am trying to download the file from specific location , sometime it download a 0KB size file or sometime the downloaded file can't be open (with some size) but sometime download perfectly. If I check the file at define location, it exist and open normally.
Here is my code in controller class.
#RequestMapping(value="/dwn.htm",method=RequestMethod.GET)
public void dwAppFm(HttpSession session,HttpServletRequest request,HttpServletResponse response,#RequestParam String id) throws IOException,InterruptedException
{
final int BUFFER_SIZES=4096;
ServletContext context=request.getServletContext();
String savePath="/tmp/";//PDF file Generate Path
String fileName="PDFFileName"; //Pdf file name
FileInputStream inputStream=null;
BufferedInputStream bufferedInputStream=null;
OutputStream outputStream=null;
printApp(id,fileName);
Thread.sleep(1000);
printApp(id,fileName);
File download=new File(savePath+fileName+".pdf");
while(!download.canRead())
{
Thread.sleep(1000);
printApp(id,fileName);
download=new File(savePath+fileName+".pdf");
}
if(download.canRead()){//if the file can read
try{
Thread.sleep(1000);
inputStream=new FileInputStream(download);
bufferedInputStream=new BufferedInputStream(inputStream);
String mimeType = context.getMimeType(savePath+fileName+".pdf");
if (mimeType == null) {
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
response.setContentType(mimeType);
response.setContentLength((int)download.length());
String headerKey="Content-Disposition";
String headerValue=String.format("attachment;filename=\"%s\"", download.getName());
response.setHeader(headerKey, headerValue);
outputStream=response.getOutputStream();
byte[] buffer=new byte[BUFFER_SIZES];
int bytesRead=-1;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
try{
if(inputStream!=null)inputStream.close();
if(bufferedInputStream!=null)bufferedInputStream.close();
if(outputStream!=null)outputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
public void printApp(String id,String fileName)
{
try{
String urlPath="http://localhost:8080/proj";
urlPath+="/genApp.htm?id="+id;//generate url to execute wkhtmltopdf
String wxpath="/home/exm/wkhtmltopdf";//the path where wkhtmltopdf located
String save="/tmp/"+fileName+".pdf";//File save Pathname
Process process=null;
process=Runtime.getRuntime().exec(wxpath+" "+urlPath+" "+save);
}catch(Exception e)
{}
}
#RequestMapping(value="/genApp.htm",method=RequestMethod.GET)
public String getApplicationPDF(HttpServletRequest request,HttpSession session,#RequestParam String id)
{
UDets uDets=uService.getAllById(Long.parseLong(id));//Methods to get details
request.setAttribute("uDets",uDets );
return "makeApp";//Name of the jsp page
}
In my code I have use Thread.sleep(1000) and printApp(id,fileName) method three times , since sometime wkhtmltopdf fail to generate pdf in certain time and then probability of downloading 0KB file is more. I haven't share the jsp page since the jsp page contain simple jsp page code of lots of line (the size of the generated pdf file is two page).
So the problem is what should I change in my code so that the pdf file generated and download without a failure also in heavy load in server.
If there is any best procedure or idea please share.
I don't like to use itext, since the jsp page contain complex design. Any advise is also appreciable and also thanks in advance.
I would say that your code is flawed not just a little but big time. You are checking if a file can be read, if not you start again a proces writing to the same file (at least twice). At some time you will endup with multiple processes trying to write to the same file, resulting in strange behavior.
I would refactor the printApp method to return the Process it created. Then call waitFor on that process. If it returns 0 and doesn't get interrupted it completed successfully and you should be able to download the file.
#RequestMapping(value="/dwn.htm",method=RequestMethod.GET)
public void dwAppFm(HttpSession session,HttpServletRequest request,HttpServletResponse response,#RequestParam String id) throws IOException,InterruptedException
{
String savePath="/tmp/";//PDF file Generate Path
String fileName="PDFFileName.pdf"; //Pdf file name
File download = new File(savePath, fileName);
try {
Process process = printApp(id, download.getPath());
int status = process.waitFor();
if (status == 0) {
response.setContentType("application/pdf");
response.setContentLength((int)download.length());
String headerKey="Content-Disposition";
String headerValue=String.format("attachment;filename=\"%s\"", download.getName());
StreamUtils.copy(new FileInputStream(download), response.getOutputStream())
} else {
// do something if it fails.
}
} catch (IOException ioe) {
// Do something to handle exception
} catch (InterruptedException ie) {
// Do something to handle exception
}
}
}
public Process printApp(String id, String pdf) throws IOException {
String urlPath="http://localhost:8080/proj";
urlPath+="/genApp.htm?id="+id;//generate url to execute wkhtmltopdf
String wxpath="/home/exm/wkhtmltopdf";//the path where wkhtmltopdf located
String command = wxpath+" "+urlPath+" "+pdf;
return Runtime.getRuntime().exec(command);
}
Something like the code above should to the trick.
I have browse button to browse for the file. After browsing there is a import button which will actually import the file.
I'm able to browse the path using the following code:
public static void uploadFiles(String object, String data) {
try {
String filemode="";
Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
String browsername = cap.getBrowserName();
//System.out.println(browsername);
if (browsername.contains("chrome")){
filemode= "Open";
}
else if (browsername.contains("firefox")){
filemode= "File Upload";
}
else if (browsername.contains("explorer")){
filemode = "Choose File to Upload";
}
String EXE_FILE=DriverScript.EXE_FILENAME;
String[] command={EXE_FILE,filemode,data};
Runtime.getRuntime().exec(command);
Thread.sleep(5000);
} catch (Exception e) {
}
}
But when I click on the import button after that "JavaScript error (WARNING: The server did not provide any stacktrace information)" exception is thrown. EXE_FILE is the path to Fileload.exe which is used for browsing
Uploading a file using Selenium:
WebElement upload = driver.findElement(By.id("identifier of input tag"));
upload.sendKeys("path to file");
Remove capability INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS if you're using it in your test code and manually set your IE protected mode settings to be the same for all zones.
It should fix the problem.
My end goal is to confirm that I have Java, Selenium WebDriver, and JUnit functioning such that I can run an automated test case utilizing these technologies.
What I have done so far:
installed Selenium IDE (v 2.8.0) for Firefox (v 34.0.5)
recorded a simple test case using Selenium IDE and added the test case to a test suite
in Selenium IDE exported the test case using the option: File->Export Test Case As...->Java / JUnit 4 / WebDriver
downloaded and installed JUnit 4 from: https://github.com/junit-team/junit/wiki/Download-and-Install (Plain-old jar method)
downloaded and installed Selenium client and WebDriver Java language binding (v 2.44.0) from: http://www.seleniumhq.org/download/
performed some slight modifications to the code generated in step 3 such as removing the package statement at the beginning
compiled the code with the following command (windows command prompt):
C:\docs\tech\code\myCode\java\testing\selenium\utest\practice>C:\java\jdk\bin\javac.exe -cp C:\docs\installs\programming\automation\test\xUnit\java\jUnit\junit\v4_12\junit-4.12.jar;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\hamcrest\hamcrest-core-1.3.jar;C:\docs\installs\programming\automation\web\selenuim\webdriver\java\selenium-2.44.0\selenium-java-2.44.0.jar C:\docs\tech\code\myCode\java\testing\selenium\utest\practice\TestGooglePlayApp.java
this compiles with no warnings/errors
attempt to execute the code with the following command:
C:\docs\tech\code\myCode\java\testing\selenium\utest\practice>java -cp .;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\junit\v4_12\junit-4.12.jar;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\hamcrest\hamcrest-core-1.3.jar;C:\docs\installs\programming\automation\web\selenuim\webdriver\java\selenium-2.44.0\selenium-java-2.44.0.jar TestGooglePlayApp
Actual Result:
The output of this attempt is:
Exception in thread "main" java.lang.NoSuchMethodError: main
No other error/warning is given and no indication is given that the code begins to execute
Expected Result:
This is my first time interacting with these technologies so I'm learning as I go! However, based on the research I have done my expectation is that a local Selenium WebDriver instance will be initialized as a Firefox Driver. This Firefox Driver will be sent instructions by the Java code in order to carry out the steps in the test case. JUnit will then indicate somehow on the command line the Pass/Fail status of the test case.
The big assumption I have here is that the Selenium Server/Selenium RC is not required in this case since all I intend to do is execute a local Selenium WebDriver script. Furthermore, my hope is that this can be launched directly from the command-line independent of Eclipse, Maven, etc. I would like to be able to send the final Java class to a colleague and the only dependency for expected execution would be a working SDK of Java on the end machine.
What's Next?
I'm looking for advice on what I can do to get this code up and running under the restraints I have outlined. It may be that the code needs to be modified. It may be that my expectations need to be tempered down and it's just not possible to do everything I want directly from the command-line. It may be that I did not compile the code correctly or some library is missing. It may be that... okay you get the point!
Other Relevant Details:
OS = Windows 7 - 64 bit
Here is the contents of TestGoogleApp.java:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class TestGooglePlayApp {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test000() throws Exception {
driver.get("http://www.google.com/");
// COMMENT: Assert the 'Apps' icon is present and then click on it
assertTrue(isElementPresent(By.cssSelector("a.gb_C.gb_Sa")));
driver.findElement(By.cssSelector("a.gb_C.gb_Sa")).click();
// COMMENT: Assert the 'Play' app is present and then click on the 'Play' app and wait for the expected contents to load
assertTrue(isElementPresent(By.cssSelector("#gb78 > span.gb_s")));
driver.findElement(By.cssSelector("#gb78 > span.gb_s")).click();
// COMMENT: Assert that the input element associated with search queries is present and then type 'Testing' in the input element associated with search queries
assertTrue(isElementPresent(By.id("gbqfq")));
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("Testing");
// COMMENT: Click on the 'Search' element to perform a query for the input query term previously entered and wait for the expected contents to load
driver.findElement(By.id("gbqfb")).click();
// COMMENT: Assert that the desired result is contained in the search results returned and then click on the desired search result and wait for the expected contents to load
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.linkText("Software Testing Concepts"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.linkText("Software Testing Concepts")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("Software Testing Concepts - Android Apps on Google Play".equals(driver.getTitle())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
// COMMENT: Assert that the page contains the expected content as follows: 1) title of app 2) user rating 3) number of users who have rated the app 4) format of text value of user rating (4.0) 5) format of text value for number of user who have rated the app (128)
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("div.score"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("span.reviews-num"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
try {
assertTrue(Pattern.compile("[0-9]\\.[0-9]").matcher(driver.findElement(By.cssSelector("div.score")).getText()).find());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
assertTrue(Pattern.compile("[0-9]+").matcher(driver.findElement(By.cssSelector("span.reviews-num")).getText()).find());
} catch (Error e) {
verificationErrors.append(e.toString());
}
// COMMENT: store value for user rating and store value for number of users who have rated the app
String _currentUserRating = driver.findElement(By.cssSelector("div.score")).getText();
System.out.println(_currentUserRating);
String _numOfUserRatings = driver.findElement(By.cssSelector("span.reviews-num")).getText();
System.out.println(_numOfUserRatings + "HELLO");
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}