org.unitils.selenium.downloader.impl.AbstractRobotDownloader Maven / Gradle / Ivy
The newest version!
/*
* Copyright (c) Smals
*/
package org.unitils.selenium.downloader.impl;
import java.io.File;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.unitils.selenium.downloader.RobotDownloader;
/**
* Abstract class with all the basic methods for the {@link RobotDownloader}.
*
* @author Willemijn Wouters
*
* @since 1.0.8
*
*/
public abstract class AbstractRobotDownloader implements RobotDownloader {
private static final Log LOGGER = LogFactory.getLog(AbstractRobotDownloader.class);
@Override
public File getDownloadFolder() {
return new File(System.getenv("USERPROFILE") + File.separator + "Downloads");
}
@Override
public void checkIfDownloadedFileExists(WebElement element) {
checkIfDownloadedFileExists(getDownloadedFile(element));
}
/**
* @see org.unitils.selenium.downloader.RobotDownloader#checkIfDownloadedFileExists(java.lang.String)
*/
@Override
public void checkIfDownloadedFileExists(String file) {
checkIfDownloadedFileExists(new File(getDownloadFolder(), file));
}
public void checkIfDownloadedFileExists(File expectedFile) {
if (!expectedFile.exists()) {
Assert.fail("The file should be downloaded in the Downloads folder of your user profile, but it cannot be found. The name of the file should be: " + expectedFile.getAbsolutePath());
}
}
@Override
public boolean deleteDownloadedFile(WebElement element) {
return deleteDownloadedFile(getDownloadedFile(element));
}
protected boolean deleteDownloadedFile(File expectedFile) {
if (expectedFile.exists()) {
expectedFile.delete();
return true;
}
return false;
}
/**
* @see org.unitils.selenium.downloader.RobotDownloader#deleteDownloadedFile(java.lang.String)
*/
@Override
public boolean deleteDownloadedFile(String fileName) {
return deleteDownloadedFile(new File(getDownloadFolder(), fileName));
}
@Override
public File getDownloadedFile(WebElement element) {
String location = getAttributesLocationFromElement(element);
//Get the filename.
String filename = location.substring(location.lastIndexOf("/") + 1);
return new File(getDownloadFolder(), filename);
}
/**
* @see org.unitils.selenium.downloader.RobotDownloader#getDownloadedFile(java.lang.String)
*/
@Override
public File getDownloadedFile(String fileName) {
return new File(getDownloadFolder(), fileName);
}
protected String getAttributesLocationFromElement(WebElement element) {
String tagname = element.getTagName().toLowerCase();
String attribute;
if (tagname.equals("input") || tagname.equals("a")) {
//type is a file
attribute = "href";
} else if (tagname.equals("img")) {
attribute = "src";
} else {
LOGGER.error("Oops, this type cannot be handled by this method. The element was of type: " + element.getTagName());
return "";
}
return element.getAttribute(attribute);
}
}