From 5ddbd63785e40f5e3ab1afbe04b4b4d2aa36addd Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Wed, 5 Apr 2017 13:16:37 -0400 Subject: [PATCH 01/10] Add files via upload Made changes for geckodriver --- ClientProperties.java | 695 ++++++++++++++++++++++++++++++++++++ DefaultSessionFactory.java | 700 +++++++++++++++++++++++++++++++++++++ pom.xml | 26 +- 3 files changed, 1412 insertions(+), 9 deletions(-) create mode 100644 ClientProperties.java create mode 100644 DefaultSessionFactory.java diff --git a/ClientProperties.java b/ClientProperties.java new file mode 100644 index 0000000..c8d8963 --- /dev/null +++ b/ClientProperties.java @@ -0,0 +1,695 @@ +/* + * (C) Copyright 2013 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.ewd.impl; + +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.configuration.PropertiesConfigurationLayout; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Enables storage of and access to driver and browser configuration. + * + */ +public class ClientProperties { + private final Logger logger = LoggerFactory.getLogger(ClientProperties.class.getPackage().getName()); + + private URL client; + + private final PropertiesConfiguration config; + private final PropertiesConfigurationLayout propertiesConfigurationLayout; + + private final String browser; + private final String browserVersion; + private final String proxy; + private final String proxyHttps; + + private int browserInitPositionX = 0; + private int browserInitPositionY = 0; + + private final String os; + private final String osVersion; + + private final String maxRequestTimeoutString; // For backwards-compatibility + private int maxRequestTimeout = 18000; + private String maxPageWaitString; + private int maxPageWait = 18000; + private final String appearWaitTimeString; + private int appearWaitTime; + private final int maxDownloadWaitTime; + private final String downloadFolder; + private final String uploadFolder; + + private final String maxAllowedSessions; + private final String binaryPath; + private final String webDriverIEDriver; + private final String webDriverChromeDriver; + private final String webDriverGeckoDriver; + private boolean isHighlight; + private final Map highlightColorMap; + + private final String firefoxProfileFolder; + private final String firefoxPropertiesFile; + private final List firefoxExtensions = new ArrayList(); + + private final String tempFolderNameContainsList; + private int numberOfDaysToKeepTempFolders = 7; + + private final boolean debugMode; + private final boolean doTaskKill; + private final boolean selectLastFrame; + + // Selenium Grid or Sauce labs + private final boolean useGrid; + private final String gridUrl; + private final String gridPlatform; + private final String gridProperties; + private final String gridSauceFile; + + /** + * Constructs a {@code ClientProperties} from the given file. + * + * @param filePath + * the file to be loaded + */ + public ClientProperties(String filePath) { + URL clientPath = this.getClass().getClassLoader().getResource(filePath); + this.config = new PropertiesConfiguration(); + this.config.setDelimiterParsingDisabled(true); + try { + client = clientPath; + // Disable delimiting values (default is comma delimited) + this.config.load(client); + } catch (ConfigurationException e) { + String message = "Client configuration could not be loaded from file: \"" + + filePath + "\""; + this.logger.error(message, e); + throw new RuntimeException(message, e); + } + propertiesConfigurationLayout = config.getLayout(); + + browser = load("browser", "htmlunit", "Browser name. See browsers supported by WebDriver."); + browserVersion = load("browser.version", null, "Version of the browser (if applicable)."); + proxy = load("proxy", null, null); + proxyHttps = load("proxy.https", null, null); + + String browserInitPositionXStr = load("browser.init.position.x", "0", + "Horizontal position for moving browser to. Useful for debugging tests."); + try { + browserInitPositionX = Integer.parseInt(browserInitPositionXStr); + } catch (NumberFormatException e) { + logger.error("Error parsing '" + + browserInitPositionXStr + + "' (value of 'browser.init.position.x' property from client properties file) as integer. Please fix your test configuration.",e); + } + + String browserInitPositionYStr = load("browser.init.position.y", "0", + "Vertical position for moving browser to. Useful for debugging tests."); + try { + browserInitPositionY = Integer.parseInt(browserInitPositionYStr); + } catch (NumberFormatException e) { + logger.error("Error parsing '" + + browserInitPositionYStr + + "' (value of 'browser.init.position.y' property from client properties file) as integer. Please fix your test configuration.",e); + } + + os = load("os", null, null); + osVersion = load("os.version", null, null); + maxPageWaitString = load("maxPageWait", "30000", + "Standard maximum page wait timeout throughout your automation project (in milliseconds)"); + try { + maxPageWait = Integer.parseInt(maxPageWaitString); + } catch (NumberFormatException e) { + logger.error("Error parsing '" + + maxPageWaitString + + "'",e); + } + + appearWaitTimeString = load("appearWaitTime", "5000", + "Maximum time for waiting of element appear (in milliseconds)"); + try { + appearWaitTime = Integer.parseInt(appearWaitTimeString); + } catch (NumberFormatException e) { + logger.error("Error parsing '" + + appearWaitTimeString + + "'",e); + } + + maxRequestTimeoutString = load("maxRequestTimeout", "30000", + "Standard maximum request wait timeout throughout your automation project (in milliseconds)"); + try { + maxRequestTimeout = Integer.parseInt(maxRequestTimeoutString); + } catch (NumberFormatException e) { + logger.error("Error parsing '" + + maxRequestTimeoutString + + "'",e); + } + + maxDownloadWaitTime = Integer.parseInt(load("download.time", "30000", + "Maximum download wait timeout")); + downloadFolder = load("download.folder", null, "Default download folder"); + binaryPath = load( + "binaryPath", + null, + "Path to Firefox executable (if you want to use specific version installed on your machine instead of default FF installation)"); + webDriverIEDriver = load("webdriver.ie.driver", null, "Path to IEDriverServer.exe"); + webDriverChromeDriver = load("webdriver.chrome.driver", null, + "Path to chromedriver executable"); + webDriverGeckoDriver = load("webdriver.gecko.driver", null, + "Path to GeckoDriver executable"); + + String uploadFolderStr = load("upload.folder", null, + "Default folder to grab files from to perform upload"); + if (uploadFolderStr != null && !uploadFolderStr.equals("")) { + File temp = new File(uploadFolderStr); + uploadFolder = temp.getAbsolutePath(); + } else { + uploadFolder = "."; + } + firefoxProfileFolder = load("firefoxProfile.folder", null, + "Path to custom Firefox profile (setup Firefox profile)"); + firefoxPropertiesFile = load( + "firefoxProfile.file", + null, + "Properties file containing configuration you want to load to current Firefox profile (setup Firefox properties file)"); + + // Check before 'webdriver.doTaskKill' + String useGridStr = load("useGrid", "false", + "Setting for running tests against Selenium Grid or Sauce Labs"); + useGrid = useGridStr != null && useGridStr.equalsIgnoreCase("true"); + + // Check after 'useGrid' + String taskCheck = load("webdriver.doTaskKill", "true", + "Gracefully kill all the driver server processes at the beginning of execution"); + if (taskCheck != null) { + if (taskCheck.equalsIgnoreCase("false") || taskCheck.equalsIgnoreCase("0") + || taskCheck.equalsIgnoreCase("no") || useGrid) { + doTaskKill = false; + } else if (taskCheck.equalsIgnoreCase("true") || taskCheck.equalsIgnoreCase("1") || taskCheck + .equalsIgnoreCase("yes")) { + doTaskKill = true; + } else { + logger.error("Property 'doTaskKill' is not within range of accepted values. (Range of accepted values are '1'/'0', 'Yes'/'No' and 'True'/'False')"); + doTaskKill = true; + } + } else { + // Default value + doTaskKill = true; + } + + String numberOfDaysToKeepTempFoldersStr = load( + "numberOfDaysToKeepTempFolders", + "7", + "Specify the period of which you want to keep temporary WebDriver folders created in temp directory"); + try { + numberOfDaysToKeepTempFolders = Integer.parseInt(numberOfDaysToKeepTempFoldersStr); + } catch (NumberFormatException e) { + logger.error("Error parsing '" + + numberOfDaysToKeepTempFoldersStr + + "'",e); + } + + tempFolderNameContainsList = load("tempFolderNameContainsList", null, + "Comma separated list of folders to clean with webDriver temp files"); + + for (int i = 1; config.containsKey("firefoxProfile.extension." + Integer.toString(i)); i++) { + String ext = config.getString("firefoxProfile.extension." + Integer.toString(i)); + firefoxExtensions.add(ext); + } + + String highlight = load("highlight", "false", "Highlighting web elements during execution"); + if (highlight.equalsIgnoreCase("true") || highlight.equalsIgnoreCase("yes") + || highlight.equalsIgnoreCase("1")) { + isHighlight = true; + } else if (highlight.equalsIgnoreCase("false") || highlight.equalsIgnoreCase("no") + || highlight.equalsIgnoreCase("0")) { + isHighlight = false; + } else { + logger.error("Error parsing client property 'highlight' ('" + highlight + + "'). It can be one of 'true / false', 'yes / no', '1 / 0'."); + } + + highlightColorMap = new HashMap(); + loadColorMapRgb(); + maxAllowedSessions = load("maxAllowedSessions", null, null); + + String debug = load("debugMode", "false", + "Test debug mode. If it is on, highlight will be turned on by default"); + + // If debug is on, then turn highlight on + if (debug != null && debug.equalsIgnoreCase("true")) { + debugMode = true; + isHighlight = true; + } else { + debugMode = false; + } + + String selectLastFrameStr = load("selectLastFrame", "true", + "Feature to select last frame automatically"); + if (selectLastFrameStr != null && selectLastFrameStr.equalsIgnoreCase("false")) { + selectLastFrame = false; + } else { + selectLastFrame = true; + } + + gridSauceFile = load("grid.saucefile", null, "grid sauce file goes here") ; + + gridUrl = load("grid.url", + "http://username-string:access-key-string@ondemand.saucelabs.com:80/wd/hub", + "Sauce labs URL (e.g. 'http://username-string:access-key-string@ondemand.saucelabs.com:80/wd/hub')"); + gridPlatform = load("grid.platform", "Windows 7", + "Selenium Grid OS Platform name (e.g. 'Windows 7')"); + gridProperties = load("grid.properties", "record-screenshots=true", + "Space separated Selenium Grid properties (e.g. 'record-screenshots=true')"); + } + + /** + * Loads the given key/value pair into the configuration. + *

+ * If the configuration already contains the given key, no change is made to + * the configuration. + * + * @param key + * the key to be put into the configuration + * @param defaultValue + * the value to be put into the configuration; if {@code null}, + * then no change is made to the configuration + * @param comment + * a comment to be set for the key/value pair; {@code null} + * values permitted + * @return the newly set value, or the current value if the configuration + * already contains the given key + */ + private final String load(String key, String defaultValue, String comment) { + if (config.getProperty(key) != null) { + return config.getString(key); + } else { + if (defaultValue != null) { + try { + config.addProperty(key, defaultValue); + if (comment != null) { + propertiesConfigurationLayout.setComment(key, comment); + } else { + propertiesConfigurationLayout + .setComment( + key, + "Automatically added default value. Please see Client Properties documentation on ExtWebDriver homepage."); + } + config.save(config.getPath()); + } catch (ConfigurationException e) { + logger.error("Error saving updated property file ('" + config.getPath() + "')" + + e); + } + } + return defaultValue; + } + } + + /** + * load the color mode and rgb values from the client properties file as + * key/value pairs in the highlighColorMap + * + */ + private final void loadColorMapRgb() { + Iterator colorKeys = config.getKeys("highlight"); + if(colorKeys!=null){ + while(colorKeys.hasNext()){ + String current = colorKeys.next(); + String[] splits = current.split("\\."); + if(splits.length > 1){ + String val = config.getString(current); + if(val.startsWith("rgb")) + highlightColorMap.put(splits[1].toUpperCase(), val); + else + logger.warn("Please check property " +current+ ". The highlight color has to specify RGB values in this format: eg. highlight.find=rgb(255,255,0)"); + } + else if(splits[0].equals("highlight")){ + + continue; + } + } + } + + + //default load + logger.warn("No RGB property for highlight was provided. Colors set to default."); + if(!highlightColorMap.containsKey("find")) + highlightColorMap.put("find".toUpperCase(), load("highlight.find", "rgb(255, 255, 0)", "color for highlight element during finding")); + if(!highlightColorMap.containsKey("get")) + highlightColorMap.put("get".toUpperCase(), load("highlight.get", "rgb(135, 206, 250)", "color for highlight element during finding")); + if(!highlightColorMap.containsKey("put")) + highlightColorMap.put("put".toUpperCase(), load("highlight.put", "rgb(152, 251, 152)", "color for highlight element during finding")); + + + + } + + public String getHighlightColor(String colorMode){ + return highlightColorMap.get( colorMode.toUpperCase()); + } + + public Map getHighlightColorMap(){ + return this.highlightColorMap; + } + + /** + * Returns the name of the browser. + * + * @return the name of the browser + */ + public final String getBrowser() { + return browser; + } + + /** + * Returns the version of the browser. + * + * @return the version of the browser + */ + public final String getBrowserVersion() { + return browserVersion; + } + + /** + * Returns the proxy. + * + * @return the proxy + */ + public final String getProxy() { + return proxy; + } + + /** + * Returns the name of the operating system. + * + * @return the name of the operating system + */ + public final String getOS() { + return os; + } + + /** + * Returns the version of the operating system. + * + * @return the version of the operating system + */ + public final String getOSVersion() { + return osVersion; + } + + /** + * Returns the maximum wait time for downloads. + * + * @return the maximum wait time for downloads + */ + public final int getMaxDownloadWaitTime() { + return maxDownloadWaitTime; + } + + /** + * Returns the directory for downloads. + * + * @return the directory for downloads + */ + public final String getDownloadFolder() { + return downloadFolder; + } + + /** + * Returns the directory for uploads. + * + * @return the directory for uploads + */ + public final String getUploadFolder() { + return uploadFolder; + } + + /** + * Returns the maximum timeout for requests as a {@code String}. + * + * @return the maximum timeout for requests as a {@code String} + */ + public final String getMaxRequestTimeoutString() { + return maxRequestTimeoutString; + } + + /** + * Returns the maximum time out for requests as an {@code int}. + * + * @return the maximum time out for requests as an {@code int} + */ + public final int getMaxRequestTimeout() { + return maxRequestTimeout; + } + + /** + * Returns the maximum wait time for pages. + * + * @return the maximum wait time for pages + */ + public int getMaxPageWait() { + return maxPageWait; + } + + /** + * Returns the maximum wait time for elements to appear. + * + * @return the maximum wait time for elements to appear + */ + public int getAppearWaitTime() { + return appearWaitTime; + } + + /** + * Returns the maximum allowed number of sessions. + * + * @return the maximum allowed number of sessions + */ + public String getMaxAllowedSessions() { + return maxAllowedSessions; + } + + /** + * Returns the path to the Firefox executable binary. + * + * @return the path to the Firefox executable binary + */ + public String getBinaryPath() { + return binaryPath; + } + + /** + * Returns the path to IEDriverServer.exe. + * + * @return the path to IEDriverServer.exe + */ + public String getWebDriverIEDriver() { + return webDriverIEDriver; + } + + /** + * Returns the path to chromedriver.exe. + * + * @return the path to chromedriver.exe + */ + public String getWebDriverChromeDriver() { + return webDriverChromeDriver; + } + + + public String getWebDriverGeckoDriver() { + return webDriverGeckoDriver; + } + + + /** + * Returns the name of the browser. + * + * @return the name of the browser + */ + public String getFirefoxProfileFolder() { + return firefoxProfileFolder; + } + + /** + * Returns the path to the Firefox profile. + * + * @return the path to the Firefox profile + */ + public String getFirefoxProfileFile() { + return firefoxPropertiesFile; + } + + /** + * Returns whether elements will be highlighted during execution. + * + * @return {@code true} if and only if elements will be highlighted during + * execution + */ + public boolean isHighlight() { + return isHighlight; + } + + + /** + * Returns a {@code List} of Firefox extensions. + * + * @return a {@code List} of Firefox extensions + */ + public List getFirefoxExtensions() { + return firefoxExtensions; + } + + /** + * Returns the number of days temporary folders are kept. + * + * @return the number of days temporary folders are kept + */ + public int getNumberOfDaysToKeepTempFolders() { + return numberOfDaysToKeepTempFolders; + } + + /** + * Returns the list of folder names to be cleaned with the temp folders. + * + * @return the list of folder names to be cleaned with the temp folders + */ + public String getTempFolderNameContainsList() { + return tempFolderNameContainsList; + } + + /** + * Returns whether debug mode is enabled. + * + * @return {@code true} if and only if debug mode is enabled + */ + public boolean getDebugMode() { + return debugMode; + } + + /** + * Returns whether running driver services are killed at the beginning of + * execution. + * + * @return {@code true} if and only if running driver services are killed at + * the beginning of execution + */ + public boolean isKillTasksAtStartup() { + return doTaskKill; + } + + /** + * Returns whther the last frame will be automatically selected. + * + * @return {@code true} if and only if the last frame will be automatically + * selected + */ + public boolean shouldSelectLastFrame() { + return selectLastFrame; + } + + /** + * Returns whether Selenium Grid or Saucelabs will be used. + * + * @return {@code true} if and only if Selenium Grid or Saucelabs will be + * used + */ + public boolean isUseGrid() { + return useGrid; + } + + /** + * Returns the Selenium Grid Sauce File. + * + * @return the Selenium Grid Sauce File + */ + public String getGridSaucefile() { + return gridSauceFile; + } + + /** + * Returns the Selenium Grid platform. + * + * @return the Selenium Grid platform + */ + public String getGridPlatform() { + return gridPlatform; + } + + /** + * Returns the Selenium Grid properties. + * + * @return the Selenium Grid properties + */ + public String getGridProperties() { + return gridProperties; + } + + /** + * Returns the Saucelabs URL. + * + * @return the Saucelabs URL + */ + public String getGridUrl() { + return gridUrl; + } + + /** + * Returns the HTTPS proxy. + * + * @return the HTTPS proxy + */ + public String getProxyHttps() { + return proxyHttps; + } + + /** + * Returns the initial horizontal offset of the browser window. + * + * @return the initial horizontal offset of the browser window + */ + public int getBrowserInitPositionX() { + return browserInitPositionX; + } + + /** + * Returns the initial vertical offset of the browser window. + * + * @return the initial vertical offset of the browser window + */ + public int getBrowserInitPositionY() { + return browserInitPositionY; + } + + /** + * Returns the URL represented by this {@code ClientProperties}. + * + * @return the URL represented by this {@code ClientProperties} + */ + public URL getClient() { + return client; + } +} diff --git a/DefaultSessionFactory.java b/DefaultSessionFactory.java new file mode 100644 index 0000000..89b0ba0 --- /dev/null +++ b/DefaultSessionFactory.java @@ -0,0 +1,700 @@ +/* + * (C) Copyright 2013 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.ewd.impl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.logging.ConsoleHandler; +import java.util.logging.Handler; +import java.util.logging.Level; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.finra.jtaf.ewd.ExtWebDriver; +import org.finra.jtaf.ewd.session.SessionFactory; +import org.openqa.selenium.Dimension; +import org.openqa.selenium.Point; +import org.openqa.selenium.Proxy; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.edge.EdgeDriver; +import org.openqa.selenium.firefox.FirefoxBinary; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.openqa.selenium.htmlunit.HtmlUnitDriver; +import org.openqa.selenium.ie.InternetExplorerDriver; +import org.openqa.selenium.remote.CapabilityType; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.remote.LocalFileDetector; +import org.openqa.selenium.remote.RemoteWebDriver; +import org.openqa.selenium.safari.SafariDriver; + +/** + * SessionPool functionality used by SessionManager instances. + * + * + */ + +public class DefaultSessionFactory implements SessionFactory { + private static final long MILLISECONDS_IN_DAY = 86400000; + private static final Object lock = new Object(); + private static final Log log = LogFactory.getLog(DefaultSessionFactory.class); + private static boolean executedTaskKill = false; + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public void cleanup(Map options) throws Exception { + + ClientProperties properties = new ClientProperties(options.get("client")); + + if (!executedTaskKill) { + synchronized (lock) { + if (properties.isKillTasksAtStartup()) { + if (properties.getBrowser().equalsIgnoreCase("ie") + || properties.getBrowser().equalsIgnoreCase("iexplore") + || properties.getBrowser().equalsIgnoreCase("*iexplore")) { + try { + Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe /T"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue IEDriverServer.exe tasks"); + } + try { + Runtime.getRuntime().exec("taskkill /F /IM iexplore.exe /T"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue Internet Explorer browsers"); + } + } else if (properties.getBrowser().equalsIgnoreCase("chrome")) { + if (properties.getOS() == null + || properties.getOS().equalsIgnoreCase("windows")) { + try { + Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T"); + + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); + } + try { + Runtime.getRuntime().exec("taskkill /F /IM chrome.exe /T"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chrome browsers"); + + } + } else if (properties.getOS().equalsIgnoreCase("linux")) { + try { + Runtime.getRuntime().exec("killall -9 chromedriver"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); + } + try { + Runtime.getRuntime().exec("killall -9 chrome"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chrome browsers"); + } + } else if (properties.getOS().equalsIgnoreCase("mac")) { + try { + Runtime.getRuntime().exec("killall -KILL chromedriver"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chromedriver tasks"); + } + try { + Runtime.getRuntime().exec("killall -KILL chrome"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chrome browsers"); + } + } else { + log.warn("Taskkill failed to kill any rogue chromedriver or chrome tasks because the OS" + + "provided is either incorrect or not supported"); + } + } else if (properties.getBrowser().equalsIgnoreCase("firefox") + || properties.getBrowser().equalsIgnoreCase("*firefox")) { + if (properties.getOS() == null + || properties.getOS().equalsIgnoreCase("windows")) { + // there is no taskkill for FirefoxDriver because + // there is no "server" used for Firefox + try { + Runtime.getRuntime().exec("taskkill /F /IM firefox.exe /T"); + + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue firefox browsers"); + } + } else if (properties.getOS().equalsIgnoreCase("linux")) { + try { + Runtime.getRuntime().exec("killall -9 firefox"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue firefox browsers"); + } + } else if (properties.getOS().equalsIgnoreCase("mac")) { + try { + Runtime.getRuntime().exec("killall -KILL firefox"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue firefox browsers"); + } + } else { + log.warn("Taskkill failed to kill any rogue firefox tasks because the OS" + + "provided is either incorrect or not supported"); + } + } + } + executedTaskKill = true; + } + } + + removeWebDriverTempOldFolders(properties); + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public DesiredCapabilities createCapabilities(Map options) throws Exception { + + ClientProperties properties = new ClientProperties(options.get("client")); + + final String browser = properties.getBrowser(); + + if (properties.isUseGrid()) { + DesiredCapabilities capabilities = null; + + if (properties.getGridUrl().length() == 0) { + throw new Exception( + "You must provide 'grid.url' to use Selenium Grid in client property file"); + } + if (browser.length() == 0) { + throw new Exception( + "You must provide 'browser' to use Selenium Grid in client property file"); + } + if (properties.getGridPlatform().length() == 0) { + throw new Exception( + "You must provide 'grid.platform' to use Selenium Grid in client property file"); + } + + if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") + || browser.equalsIgnoreCase("*iexplore")) { + capabilities = DesiredCapabilities.internetExplorer(); + } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { + capabilities = DesiredCapabilities.firefox(); + } else if (browser.equalsIgnoreCase("chrome")) { + capabilities = DesiredCapabilities.chrome(); + } else if (browser.equalsIgnoreCase("safari")) { + capabilities = DesiredCapabilities.safari(); + } else if (browser.equalsIgnoreCase("opera")) { + capabilities = DesiredCapabilities.opera(); + } else if (browser.equalsIgnoreCase("android")) { + capabilities = DesiredCapabilities.android(); + } else if (browser.equalsIgnoreCase("ipad")) { + capabilities = DesiredCapabilities.ipad(); + } else if (browser.equalsIgnoreCase("iphone")) { + capabilities = DesiredCapabilities.iphone(); + } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge")) { + capabilities = DesiredCapabilities.edge(); + } else { + throw new Exception("Unsupported browser: " + browser + + " Please refer to documentation for supported browsers."); + } + + capabilities.setVersion(properties.getBrowserVersion()); + + String platform = properties.getGridPlatform(); + if (platform != null && platform.length() > 0) { + capabilities.setCapability("platform", platform); + } else { + // Default to Windows 7 + capabilities.setCapability("platform", "Windows 7"); + } + + String sauceFile = properties.getGridSaucefile() ; + if (sauceFile != null && sauceFile.length() > 0) { + Map sOptions = new HashMap(); + sOptions.put("executable", "sauce-storage:" + sauceFile ); + sOptions.put("args", "[ '--silent', '-a', '-q' ]"); + sOptions.put("background", "true"); + + capabilities.setCapability("prerun",sOptions); + + } + + + + + // Set Proxy + String proxyStr = properties.getProxy(); + String proxyHttps = properties.getProxyHttps(); + Proxy proxy = null; + if (proxyStr != null && !proxyStr.equals("")) { + proxy = new Proxy(); + proxy.setHttpProxy(proxyStr); + + } + if (proxyHttps != null && !proxyHttps.equals("")) { + if (proxy == null) { + proxy = new Proxy(); + } + proxy.setSslProxy(proxyHttps); + } + + if (proxy != null) { + capabilities.setCapability(CapabilityType.PROXY, proxy); + } + + // preparing data for session name + String computerName = null; + try { + computerName = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + } + + capabilities.setCapability("name", "JTAF EWD client=" + properties.getClient() + + "; started from " + computerName); + + String gridProperties = properties.getGridProperties(); + if (gridProperties != null && gridProperties.length() > 0) { + String[] gridPropertiesSlpitted = gridProperties.split(" "); + for (String gridPropertiesSlpittedCurrent : gridPropertiesSlpitted) { + if (gridPropertiesSlpittedCurrent != null + && gridPropertiesSlpittedCurrent.length() > 0) { + String[] propertyNameAndValue = gridPropertiesSlpittedCurrent.split("="); + if (propertyNameAndValue.length == 2) { + capabilities.setCapability(propertyNameAndValue[0], + propertyNameAndValue[1]); + } + } + } + } + + return capabilities; + } else { + log.debug("browser [" + browser + "]"); + + // Turning off all console logs using java.util.logging + Handler[] h = java.util.logging.LogManager.getLogManager().getLogger("").getHandlers(); + for (int i = 0; i < h.length; i++) { + if (h[i] instanceof ConsoleHandler) { + h[i].setLevel(Level.OFF); + } + } + + String proxyProperty = properties.getProxy(); + DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); + if (proxyProperty != null) { + Proxy proxy = new Proxy(); + proxy.setHttpProxy(proxyProperty).setFtpProxy(proxyProperty).setSslProxy( + proxyProperty); + desiredCapabilities = new DesiredCapabilities(); + if (browser != null && browser.equalsIgnoreCase("chrome")) { + // chrome way of proxy initialization + desiredCapabilities.setCapability("chrome.switches", Arrays + .asList("--proxy-server=http://" + proxy)); + } else { + // ff and ie way of proxy initialization + desiredCapabilities.setCapability(CapabilityType.PROXY, proxy); + } + } + + if (properties.getDownloadFolder() != null + && properties.getDownloadFolder().length() > 0) { + // '0' means to download to the desktop, '1' means to download + // to the default "Downloads" directory, '2' means to use the + // directory you specify in "browser.download.dir" + desiredCapabilities.setCapability("browser.download.folderList", 2); + desiredCapabilities.setCapability("browser.download.dir", System + .getProperty("user.dir") + + System.getProperty("file.separator") + properties.getDownloadFolder()); + desiredCapabilities + .setCapability( + "browser.helperApps.neverAsk.saveToDisk", + "text/csv, application/octet-stream, application/pdf, application/vnd.fdf, application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff"); + desiredCapabilities.setCapability("browser.helperApps.alwaysAsk.force", false); + desiredCapabilities.setCapability("browser.download.manager.showWhenStarting", + false); + } + return desiredCapabilities; + } + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public WebDriver createInnerDriver(Map options, DesiredCapabilities capabilities) + throws Exception { + ClientProperties properties = new ClientProperties(options.get("client")); + + WebDriver wd = null; + DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities); + String browser = properties.getBrowser(); + + if (properties.isUseGrid()) { + RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(properties.getGridUrl()), + capabilities); + remoteWebDriver.setFileDetector(new LocalFileDetector()); + wd = remoteWebDriver; + }else { + if (browser == null || browser.equals("")) { + throw new RuntimeException( + "Browser cannot be null. Please set 'browser' in client properties. Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); + } else if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") + || browser.equalsIgnoreCase("*iexplore")) { + String webdriverIEDriver = properties.getWebDriverIEDriver(); + + if (webdriverIEDriver != null) { + System.setProperty("webdriver.ie.driver", webdriverIEDriver); + } + + String browserVersion = properties.getBrowserVersion(); + + if (browserVersion == null || browserVersion.equals("")) { + throw new RuntimeException( + "When using IE as the browser, please set 'browser.version' in client properties"); + } else { + if (browserVersion.startsWith("9")) { + desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); + desiredCapabilities + .setCapability( + InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, + true); + wd = new InternetExplorerDriver(desiredCapabilities); + } else { + wd = new InternetExplorerDriver(desiredCapabilities); + } + } + } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { + final String ffProfileFolder = properties.getFirefoxProfileFolder(); + final String ffProfileFile = properties.getFirefoxProfileFile(); + final String path = properties.getBinaryPath(); + final String webDriverGeckoDriver = properties.getWebDriverGeckoDriver(); + + + if(webDriverGeckoDriver != null){ + + System.setProperty("webdriver.gecko.driver", webDriverGeckoDriver); + + } + + if (path != null) { + FirefoxBinary fireFox = getFFBinary(path); + FirefoxProfile ffp = null; + + if (ffProfileFolder != null) { + ffp = new FirefoxProfile(new File(ffProfileFolder)); + } else { + ffp = new FirefoxProfile(); + } + + if (ffProfileFile != null) { + addPreferences(ffp, ffProfileFile); + } + + addPreferences(ffp); + + List ffExtensions = properties.getFirefoxExtensions(); + if (ffExtensions != null && ffExtensions.size() > 0) { + addExtensionsToFirefoxProfile(ffp, ffExtensions); + } + + wd = new FirefoxDriver(fireFox, ffp, desiredCapabilities); + } else { + wd = new FirefoxDriver(desiredCapabilities); + } + } else if (browser.equalsIgnoreCase("chrome")) { + + String webdriverChromeDriver = properties.getWebDriverChromeDriver(); + + if (webdriverChromeDriver != null) { + System.setProperty("webdriver.chrome.driver", webdriverChromeDriver); + } + + // for downloading with Chrome + if(properties.getDownloadFolder() != null) { + HashMap chromePrefs = new HashMap(); + chromePrefs.put("profile.default_content_settings.popups", 0); + chromePrefs.put("download.default_directory", properties.getDownloadFolder()); + ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.setExperimentalOption("prefs", chromePrefs); + desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); + } + + wd = new ChromeDriver(desiredCapabilities); + } else if (browser.equalsIgnoreCase("safari")) { + wd = new SafariDriver(desiredCapabilities); + } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge") + || browser.equalsIgnoreCase("edge")) { + wd = new EdgeDriver(desiredCapabilities); + } else if (browser.equalsIgnoreCase("htmlunit")) { + wd = new HtmlUnitDriver(desiredCapabilities); + ((HtmlUnitDriver) wd).setJavascriptEnabled(true); + } else { + throw new Exception("Unsupported browser type: " + browser + + ". Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); + } + + // move browser windows to specific position. It's useful for + // debugging... + final int browserInitPositionX = properties.getBrowserInitPositionX(); + final int browserInitPositionY = properties.getBrowserInitPositionY(); + if (browserInitPositionX != 0 || browserInitPositionY != 0) { + wd.manage().window().setSize(new Dimension(1280, 1024)); + wd.manage().window().setPosition(new Point(browserInitPositionX, browserInitPositionY)); + } + } + + return wd; + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public ExtWebDriver createNewSession(Map options, WebDriver wd) { + DefaultExtWebDriver selenium = new DefaultExtWebDriver(); + selenium.setWrappedDriver(wd); + + // Get client properties file + ClientProperties properties = new ClientProperties(options.get("client")); + + // Set client properties (specific to our factory/implementation) + selenium.setClientProperties(properties); + + // Set timeout value + selenium.setMaxRequestTimeout(properties.getMaxRequestTimeoutString()); + + // Highlighting + selenium.setHighlightColors(properties.getHighlightColorMap()); + selenium.setIsHighlight(properties.isHighlight()); + + return selenium; + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public Map createDefaultOptions() { + HashMap ret = new HashMap(); + // Add any default options needed here (like path to default properties) + + ret.put("client", "client.properties"); + + return ret; + } + + /** + * + * @param ffp + * for use in setting the firefox profile for the tests to use + * when running firefox + */ + private static void addPreferences(FirefoxProfile ffp) { + ffp.setPreference("capability.policy.default.HTMLDocument.readyState", "allAccess"); + ffp.setPreference("capability.policy.default.HTMLDocument.compatMode", "allAccess"); + ffp.setPreference("capability.policy.default.Document.compatMode", "allAccess"); + ffp.setPreference("capability.policy.default.Location.href", "allAccess"); + ffp.setPreference("capability.policy.default.Window.pageXOffset", "allAccess"); + ffp.setPreference("capability.policy.default.Window.pageYOffset", "allAccess"); + ffp.setPreference("capability.policy.default.Window.frameElement", "allAccess"); + ffp.setPreference("capability.policy.default.Window.frameElement.get", "allAccess"); + ffp.setPreference("capability.policy.default.Window.QueryInterface", "allAccess"); + ffp.setPreference("capability.policy.default.Window.mozInnerScreenY", "allAccess"); + ffp.setPreference("capability.policy.default.Window.mozInnerScreenX", "allAccess"); + } + + /** + * + * @param ffp + * the firefox profile you are using + * @param propertiesFile + * the properties you want to add to the profile + */ + private static void addPreferences(FirefoxProfile ffp, String propertiesFile) { + Properties firefoxProfile = new Properties(); + + try(FileInputStream fis = new FileInputStream(propertiesFile)) { + firefoxProfile.load(fis); + } catch (Throwable th) { + throw new RuntimeException("Could not load firefox profile", th); + } + + for (Object o : firefoxProfile.keySet()) { + String key = (String) o; + String getVal = null; + if (key.endsWith(".type")) { + getVal = key.substring(0, key.lastIndexOf(".")); + } + + if (getVal != null) { + String type = firefoxProfile.getProperty(key); + String value = firefoxProfile.getProperty(getVal + ".value"); + + if (value.contains("${PROJECT_PATH}")) { + String projectPath = (new File("")).getAbsolutePath(); + value = projectPath + value.replaceAll("\\$\\{PROJECT_PATH\\}", ""); + } + + if (type.equalsIgnoreCase("BOOLEAN")) { + ffp.setPreference(getVal, Boolean.parseBoolean(value)); + } else if (type.equalsIgnoreCase("STRING")) { + ffp.setPreference(getVal, value); + } else if (type.equalsIgnoreCase("INTEGER") || type.equalsIgnoreCase("INT")) { + ffp.setPreference(getVal, Integer.parseInt(value)); + } + } + } + } + + /** + * + * @param ffp + * the firefox profile specified + * @param extensions + * extensions desired to be added + * @throws IOException + */ + private static void addExtensionsToFirefoxProfile(FirefoxProfile ffp, List extensions) + throws IOException { + for (String s : extensions) { + ffp.addExtension(new File(s)); + } + } + + /** + * + * @param filePath + * the binary path location of the firefox app (where it's + * installed) + * @return + */ + private static FirefoxBinary getFFBinary(String filePath) { + File[] possibleLocations = { new File(filePath != null ? filePath : ""), + new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe"), + new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"), }; + + File ffbinary = null; + + for (File curr : possibleLocations) { + if (curr.exists()) { + ffbinary = curr; + break; + } + } + + if (ffbinary == null) { + throw new RuntimeException( + "Unable to find firefox binary, please ensure that firefox is installed " + + "on your system. If it is then please determine the path to your firefox.exe and set it as " + + "binaryPath="); + } else { + return new FirefoxBinary(ffbinary); + } + } + + /** + * This method cleans out folders where the WebDriver temp information is + * stored. + * + * @param properties + * client properties specified + */ + private static void removeWebDriverTempOldFolders(ClientProperties properties) { + String tempFolder = System.getProperty("java.io.tmpdir"); + + int numberOfDaysToKeepTempFolders = properties.getNumberOfDaysToKeepTempFolders(); + if (numberOfDaysToKeepTempFolders < 0) { + numberOfDaysToKeepTempFolders = 7; + } + + List tempFolderNameContainsList = new ArrayList(); + tempFolderNameContainsList.add("anonymous"); + tempFolderNameContainsList.add("scoped_dir"); + tempFolderNameContainsList.add("webdriver-ie"); + + // add parameters from config file + String tempFolderNameContainsListFromProp = properties.getTempFolderNameContainsList(); + if (tempFolderNameContainsListFromProp != null) { + String[] tempFolderNameContainsListFromPropSpit = tempFolderNameContainsListFromProp + .split(","); + for (String name : tempFolderNameContainsListFromPropSpit) { + tempFolderNameContainsList.add(name); + } + } + + removeFolders(tempFolder, tempFolderNameContainsList, numberOfDaysToKeepTempFolders); + } + + /** + * This method can be called to remove specific folders or set how long you + * want to keep the temp information. + * + * @param folder + * which temp folder you want to remove + * @param folderTemplates + * the templates of these temp folders + * @param numberOfDaysToKeepTempFolders + * how long you want to keep the temp information + */ + private final static void removeFolders(String folder, List folderTemplates, + int numberOfDaysToKeepTempFolders) { + long dateToRemoveFiledAfter = (new Date()).getTime() + - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); + + File tempFolder = new File(folder); + File[] folderChildren = tempFolder.listFiles(); + if(null == folderChildren) { + log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); + return; + } + + for (File currentFile : folderChildren) { + if (currentFile.isDirectory()) { + for (String folderTemplate : folderTemplates) { + if (currentFile.getName().contains(folderTemplate) + && (currentFile.lastModified() < dateToRemoveFiledAfter)) { + try { + currentFile.delete(); + FileUtils.deleteDirectory(currentFile); + log.debug("Folder '" + currentFile.getName() + "' deleted..."); + } catch (Exception e) { + log.fatal("Error deleting folder '" + currentFile.getName() + "'"); + } + } + } + } + } + } +} diff --git a/pom.xml b/pom.xml index 2ef506b..ccab69e 100644 --- a/pom.xml +++ b/pom.xml @@ -141,7 +141,7 @@ 0.6.3.201306030806 - + pre-integration-test pre-integration-test @@ -151,7 +151,7 @@ ${project.build.directory}/coverage-reports/jacoco-it.exec - + failsafeArgLine failsafeArgLine @@ -286,16 +286,24 @@ org.seleniumhq.selenium - selenium-server - 2.53.0 - pom + selenium-support + 3.3.1 org.seleniumhq.selenium - selenium-htmlunit-driver - 2.52.0 + htmlunit-driver + 2.26 - + + org.seleniumhq.selenium + selenium-java + 3.3.1 + + + org.seleniumhq.selenium + selenium-leg-rc + 3.3.1 + org.ccil.cowan.tagsoup @@ -362,4 +370,4 @@ https://oss.sonatype.org/content/repositories/snapshots - + \ No newline at end of file From 813d2415869205688ef91f4f308a097378bcd611 Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Wed, 5 Apr 2017 13:19:29 -0400 Subject: [PATCH 02/10] Delete ClientProperties.java --- ClientProperties.java | 695 ------------------------------------------ 1 file changed, 695 deletions(-) delete mode 100644 ClientProperties.java diff --git a/ClientProperties.java b/ClientProperties.java deleted file mode 100644 index c8d8963..0000000 --- a/ClientProperties.java +++ /dev/null @@ -1,695 +0,0 @@ -/* - * (C) Copyright 2013 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.ewd.impl; - -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; -import org.apache.commons.configuration.PropertiesConfigurationLayout; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Enables storage of and access to driver and browser configuration. - * - */ -public class ClientProperties { - private final Logger logger = LoggerFactory.getLogger(ClientProperties.class.getPackage().getName()); - - private URL client; - - private final PropertiesConfiguration config; - private final PropertiesConfigurationLayout propertiesConfigurationLayout; - - private final String browser; - private final String browserVersion; - private final String proxy; - private final String proxyHttps; - - private int browserInitPositionX = 0; - private int browserInitPositionY = 0; - - private final String os; - private final String osVersion; - - private final String maxRequestTimeoutString; // For backwards-compatibility - private int maxRequestTimeout = 18000; - private String maxPageWaitString; - private int maxPageWait = 18000; - private final String appearWaitTimeString; - private int appearWaitTime; - private final int maxDownloadWaitTime; - private final String downloadFolder; - private final String uploadFolder; - - private final String maxAllowedSessions; - private final String binaryPath; - private final String webDriverIEDriver; - private final String webDriverChromeDriver; - private final String webDriverGeckoDriver; - private boolean isHighlight; - private final Map highlightColorMap; - - private final String firefoxProfileFolder; - private final String firefoxPropertiesFile; - private final List firefoxExtensions = new ArrayList(); - - private final String tempFolderNameContainsList; - private int numberOfDaysToKeepTempFolders = 7; - - private final boolean debugMode; - private final boolean doTaskKill; - private final boolean selectLastFrame; - - // Selenium Grid or Sauce labs - private final boolean useGrid; - private final String gridUrl; - private final String gridPlatform; - private final String gridProperties; - private final String gridSauceFile; - - /** - * Constructs a {@code ClientProperties} from the given file. - * - * @param filePath - * the file to be loaded - */ - public ClientProperties(String filePath) { - URL clientPath = this.getClass().getClassLoader().getResource(filePath); - this.config = new PropertiesConfiguration(); - this.config.setDelimiterParsingDisabled(true); - try { - client = clientPath; - // Disable delimiting values (default is comma delimited) - this.config.load(client); - } catch (ConfigurationException e) { - String message = "Client configuration could not be loaded from file: \"" - + filePath + "\""; - this.logger.error(message, e); - throw new RuntimeException(message, e); - } - propertiesConfigurationLayout = config.getLayout(); - - browser = load("browser", "htmlunit", "Browser name. See browsers supported by WebDriver."); - browserVersion = load("browser.version", null, "Version of the browser (if applicable)."); - proxy = load("proxy", null, null); - proxyHttps = load("proxy.https", null, null); - - String browserInitPositionXStr = load("browser.init.position.x", "0", - "Horizontal position for moving browser to. Useful for debugging tests."); - try { - browserInitPositionX = Integer.parseInt(browserInitPositionXStr); - } catch (NumberFormatException e) { - logger.error("Error parsing '" - + browserInitPositionXStr - + "' (value of 'browser.init.position.x' property from client properties file) as integer. Please fix your test configuration.",e); - } - - String browserInitPositionYStr = load("browser.init.position.y", "0", - "Vertical position for moving browser to. Useful for debugging tests."); - try { - browserInitPositionY = Integer.parseInt(browserInitPositionYStr); - } catch (NumberFormatException e) { - logger.error("Error parsing '" - + browserInitPositionYStr - + "' (value of 'browser.init.position.y' property from client properties file) as integer. Please fix your test configuration.",e); - } - - os = load("os", null, null); - osVersion = load("os.version", null, null); - maxPageWaitString = load("maxPageWait", "30000", - "Standard maximum page wait timeout throughout your automation project (in milliseconds)"); - try { - maxPageWait = Integer.parseInt(maxPageWaitString); - } catch (NumberFormatException e) { - logger.error("Error parsing '" - + maxPageWaitString - + "'",e); - } - - appearWaitTimeString = load("appearWaitTime", "5000", - "Maximum time for waiting of element appear (in milliseconds)"); - try { - appearWaitTime = Integer.parseInt(appearWaitTimeString); - } catch (NumberFormatException e) { - logger.error("Error parsing '" - + appearWaitTimeString - + "'",e); - } - - maxRequestTimeoutString = load("maxRequestTimeout", "30000", - "Standard maximum request wait timeout throughout your automation project (in milliseconds)"); - try { - maxRequestTimeout = Integer.parseInt(maxRequestTimeoutString); - } catch (NumberFormatException e) { - logger.error("Error parsing '" - + maxRequestTimeoutString - + "'",e); - } - - maxDownloadWaitTime = Integer.parseInt(load("download.time", "30000", - "Maximum download wait timeout")); - downloadFolder = load("download.folder", null, "Default download folder"); - binaryPath = load( - "binaryPath", - null, - "Path to Firefox executable (if you want to use specific version installed on your machine instead of default FF installation)"); - webDriverIEDriver = load("webdriver.ie.driver", null, "Path to IEDriverServer.exe"); - webDriverChromeDriver = load("webdriver.chrome.driver", null, - "Path to chromedriver executable"); - webDriverGeckoDriver = load("webdriver.gecko.driver", null, - "Path to GeckoDriver executable"); - - String uploadFolderStr = load("upload.folder", null, - "Default folder to grab files from to perform upload"); - if (uploadFolderStr != null && !uploadFolderStr.equals("")) { - File temp = new File(uploadFolderStr); - uploadFolder = temp.getAbsolutePath(); - } else { - uploadFolder = "."; - } - firefoxProfileFolder = load("firefoxProfile.folder", null, - "Path to custom Firefox profile (setup Firefox profile)"); - firefoxPropertiesFile = load( - "firefoxProfile.file", - null, - "Properties file containing configuration you want to load to current Firefox profile (setup Firefox properties file)"); - - // Check before 'webdriver.doTaskKill' - String useGridStr = load("useGrid", "false", - "Setting for running tests against Selenium Grid or Sauce Labs"); - useGrid = useGridStr != null && useGridStr.equalsIgnoreCase("true"); - - // Check after 'useGrid' - String taskCheck = load("webdriver.doTaskKill", "true", - "Gracefully kill all the driver server processes at the beginning of execution"); - if (taskCheck != null) { - if (taskCheck.equalsIgnoreCase("false") || taskCheck.equalsIgnoreCase("0") - || taskCheck.equalsIgnoreCase("no") || useGrid) { - doTaskKill = false; - } else if (taskCheck.equalsIgnoreCase("true") || taskCheck.equalsIgnoreCase("1") || taskCheck - .equalsIgnoreCase("yes")) { - doTaskKill = true; - } else { - logger.error("Property 'doTaskKill' is not within range of accepted values. (Range of accepted values are '1'/'0', 'Yes'/'No' and 'True'/'False')"); - doTaskKill = true; - } - } else { - // Default value - doTaskKill = true; - } - - String numberOfDaysToKeepTempFoldersStr = load( - "numberOfDaysToKeepTempFolders", - "7", - "Specify the period of which you want to keep temporary WebDriver folders created in temp directory"); - try { - numberOfDaysToKeepTempFolders = Integer.parseInt(numberOfDaysToKeepTempFoldersStr); - } catch (NumberFormatException e) { - logger.error("Error parsing '" - + numberOfDaysToKeepTempFoldersStr - + "'",e); - } - - tempFolderNameContainsList = load("tempFolderNameContainsList", null, - "Comma separated list of folders to clean with webDriver temp files"); - - for (int i = 1; config.containsKey("firefoxProfile.extension." + Integer.toString(i)); i++) { - String ext = config.getString("firefoxProfile.extension." + Integer.toString(i)); - firefoxExtensions.add(ext); - } - - String highlight = load("highlight", "false", "Highlighting web elements during execution"); - if (highlight.equalsIgnoreCase("true") || highlight.equalsIgnoreCase("yes") - || highlight.equalsIgnoreCase("1")) { - isHighlight = true; - } else if (highlight.equalsIgnoreCase("false") || highlight.equalsIgnoreCase("no") - || highlight.equalsIgnoreCase("0")) { - isHighlight = false; - } else { - logger.error("Error parsing client property 'highlight' ('" + highlight - + "'). It can be one of 'true / false', 'yes / no', '1 / 0'."); - } - - highlightColorMap = new HashMap(); - loadColorMapRgb(); - maxAllowedSessions = load("maxAllowedSessions", null, null); - - String debug = load("debugMode", "false", - "Test debug mode. If it is on, highlight will be turned on by default"); - - // If debug is on, then turn highlight on - if (debug != null && debug.equalsIgnoreCase("true")) { - debugMode = true; - isHighlight = true; - } else { - debugMode = false; - } - - String selectLastFrameStr = load("selectLastFrame", "true", - "Feature to select last frame automatically"); - if (selectLastFrameStr != null && selectLastFrameStr.equalsIgnoreCase("false")) { - selectLastFrame = false; - } else { - selectLastFrame = true; - } - - gridSauceFile = load("grid.saucefile", null, "grid sauce file goes here") ; - - gridUrl = load("grid.url", - "http://username-string:access-key-string@ondemand.saucelabs.com:80/wd/hub", - "Sauce labs URL (e.g. 'http://username-string:access-key-string@ondemand.saucelabs.com:80/wd/hub')"); - gridPlatform = load("grid.platform", "Windows 7", - "Selenium Grid OS Platform name (e.g. 'Windows 7')"); - gridProperties = load("grid.properties", "record-screenshots=true", - "Space separated Selenium Grid properties (e.g. 'record-screenshots=true')"); - } - - /** - * Loads the given key/value pair into the configuration. - *

- * If the configuration already contains the given key, no change is made to - * the configuration. - * - * @param key - * the key to be put into the configuration - * @param defaultValue - * the value to be put into the configuration; if {@code null}, - * then no change is made to the configuration - * @param comment - * a comment to be set for the key/value pair; {@code null} - * values permitted - * @return the newly set value, or the current value if the configuration - * already contains the given key - */ - private final String load(String key, String defaultValue, String comment) { - if (config.getProperty(key) != null) { - return config.getString(key); - } else { - if (defaultValue != null) { - try { - config.addProperty(key, defaultValue); - if (comment != null) { - propertiesConfigurationLayout.setComment(key, comment); - } else { - propertiesConfigurationLayout - .setComment( - key, - "Automatically added default value. Please see Client Properties documentation on ExtWebDriver homepage."); - } - config.save(config.getPath()); - } catch (ConfigurationException e) { - logger.error("Error saving updated property file ('" + config.getPath() + "')" - + e); - } - } - return defaultValue; - } - } - - /** - * load the color mode and rgb values from the client properties file as - * key/value pairs in the highlighColorMap - * - */ - private final void loadColorMapRgb() { - Iterator colorKeys = config.getKeys("highlight"); - if(colorKeys!=null){ - while(colorKeys.hasNext()){ - String current = colorKeys.next(); - String[] splits = current.split("\\."); - if(splits.length > 1){ - String val = config.getString(current); - if(val.startsWith("rgb")) - highlightColorMap.put(splits[1].toUpperCase(), val); - else - logger.warn("Please check property " +current+ ". The highlight color has to specify RGB values in this format: eg. highlight.find=rgb(255,255,0)"); - } - else if(splits[0].equals("highlight")){ - - continue; - } - } - } - - - //default load - logger.warn("No RGB property for highlight was provided. Colors set to default."); - if(!highlightColorMap.containsKey("find")) - highlightColorMap.put("find".toUpperCase(), load("highlight.find", "rgb(255, 255, 0)", "color for highlight element during finding")); - if(!highlightColorMap.containsKey("get")) - highlightColorMap.put("get".toUpperCase(), load("highlight.get", "rgb(135, 206, 250)", "color for highlight element during finding")); - if(!highlightColorMap.containsKey("put")) - highlightColorMap.put("put".toUpperCase(), load("highlight.put", "rgb(152, 251, 152)", "color for highlight element during finding")); - - - - } - - public String getHighlightColor(String colorMode){ - return highlightColorMap.get( colorMode.toUpperCase()); - } - - public Map getHighlightColorMap(){ - return this.highlightColorMap; - } - - /** - * Returns the name of the browser. - * - * @return the name of the browser - */ - public final String getBrowser() { - return browser; - } - - /** - * Returns the version of the browser. - * - * @return the version of the browser - */ - public final String getBrowserVersion() { - return browserVersion; - } - - /** - * Returns the proxy. - * - * @return the proxy - */ - public final String getProxy() { - return proxy; - } - - /** - * Returns the name of the operating system. - * - * @return the name of the operating system - */ - public final String getOS() { - return os; - } - - /** - * Returns the version of the operating system. - * - * @return the version of the operating system - */ - public final String getOSVersion() { - return osVersion; - } - - /** - * Returns the maximum wait time for downloads. - * - * @return the maximum wait time for downloads - */ - public final int getMaxDownloadWaitTime() { - return maxDownloadWaitTime; - } - - /** - * Returns the directory for downloads. - * - * @return the directory for downloads - */ - public final String getDownloadFolder() { - return downloadFolder; - } - - /** - * Returns the directory for uploads. - * - * @return the directory for uploads - */ - public final String getUploadFolder() { - return uploadFolder; - } - - /** - * Returns the maximum timeout for requests as a {@code String}. - * - * @return the maximum timeout for requests as a {@code String} - */ - public final String getMaxRequestTimeoutString() { - return maxRequestTimeoutString; - } - - /** - * Returns the maximum time out for requests as an {@code int}. - * - * @return the maximum time out for requests as an {@code int} - */ - public final int getMaxRequestTimeout() { - return maxRequestTimeout; - } - - /** - * Returns the maximum wait time for pages. - * - * @return the maximum wait time for pages - */ - public int getMaxPageWait() { - return maxPageWait; - } - - /** - * Returns the maximum wait time for elements to appear. - * - * @return the maximum wait time for elements to appear - */ - public int getAppearWaitTime() { - return appearWaitTime; - } - - /** - * Returns the maximum allowed number of sessions. - * - * @return the maximum allowed number of sessions - */ - public String getMaxAllowedSessions() { - return maxAllowedSessions; - } - - /** - * Returns the path to the Firefox executable binary. - * - * @return the path to the Firefox executable binary - */ - public String getBinaryPath() { - return binaryPath; - } - - /** - * Returns the path to IEDriverServer.exe. - * - * @return the path to IEDriverServer.exe - */ - public String getWebDriverIEDriver() { - return webDriverIEDriver; - } - - /** - * Returns the path to chromedriver.exe. - * - * @return the path to chromedriver.exe - */ - public String getWebDriverChromeDriver() { - return webDriverChromeDriver; - } - - - public String getWebDriverGeckoDriver() { - return webDriverGeckoDriver; - } - - - /** - * Returns the name of the browser. - * - * @return the name of the browser - */ - public String getFirefoxProfileFolder() { - return firefoxProfileFolder; - } - - /** - * Returns the path to the Firefox profile. - * - * @return the path to the Firefox profile - */ - public String getFirefoxProfileFile() { - return firefoxPropertiesFile; - } - - /** - * Returns whether elements will be highlighted during execution. - * - * @return {@code true} if and only if elements will be highlighted during - * execution - */ - public boolean isHighlight() { - return isHighlight; - } - - - /** - * Returns a {@code List} of Firefox extensions. - * - * @return a {@code List} of Firefox extensions - */ - public List getFirefoxExtensions() { - return firefoxExtensions; - } - - /** - * Returns the number of days temporary folders are kept. - * - * @return the number of days temporary folders are kept - */ - public int getNumberOfDaysToKeepTempFolders() { - return numberOfDaysToKeepTempFolders; - } - - /** - * Returns the list of folder names to be cleaned with the temp folders. - * - * @return the list of folder names to be cleaned with the temp folders - */ - public String getTempFolderNameContainsList() { - return tempFolderNameContainsList; - } - - /** - * Returns whether debug mode is enabled. - * - * @return {@code true} if and only if debug mode is enabled - */ - public boolean getDebugMode() { - return debugMode; - } - - /** - * Returns whether running driver services are killed at the beginning of - * execution. - * - * @return {@code true} if and only if running driver services are killed at - * the beginning of execution - */ - public boolean isKillTasksAtStartup() { - return doTaskKill; - } - - /** - * Returns whther the last frame will be automatically selected. - * - * @return {@code true} if and only if the last frame will be automatically - * selected - */ - public boolean shouldSelectLastFrame() { - return selectLastFrame; - } - - /** - * Returns whether Selenium Grid or Saucelabs will be used. - * - * @return {@code true} if and only if Selenium Grid or Saucelabs will be - * used - */ - public boolean isUseGrid() { - return useGrid; - } - - /** - * Returns the Selenium Grid Sauce File. - * - * @return the Selenium Grid Sauce File - */ - public String getGridSaucefile() { - return gridSauceFile; - } - - /** - * Returns the Selenium Grid platform. - * - * @return the Selenium Grid platform - */ - public String getGridPlatform() { - return gridPlatform; - } - - /** - * Returns the Selenium Grid properties. - * - * @return the Selenium Grid properties - */ - public String getGridProperties() { - return gridProperties; - } - - /** - * Returns the Saucelabs URL. - * - * @return the Saucelabs URL - */ - public String getGridUrl() { - return gridUrl; - } - - /** - * Returns the HTTPS proxy. - * - * @return the HTTPS proxy - */ - public String getProxyHttps() { - return proxyHttps; - } - - /** - * Returns the initial horizontal offset of the browser window. - * - * @return the initial horizontal offset of the browser window - */ - public int getBrowserInitPositionX() { - return browserInitPositionX; - } - - /** - * Returns the initial vertical offset of the browser window. - * - * @return the initial vertical offset of the browser window - */ - public int getBrowserInitPositionY() { - return browserInitPositionY; - } - - /** - * Returns the URL represented by this {@code ClientProperties}. - * - * @return the URL represented by this {@code ClientProperties} - */ - public URL getClient() { - return client; - } -} From d6801e8bb29deef7ed8d2304cc5406e666aca643 Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Wed, 5 Apr 2017 13:19:46 -0400 Subject: [PATCH 03/10] Delete DefaultSessionFactory.java --- DefaultSessionFactory.java | 700 ------------------------------------- 1 file changed, 700 deletions(-) delete mode 100644 DefaultSessionFactory.java diff --git a/DefaultSessionFactory.java b/DefaultSessionFactory.java deleted file mode 100644 index 89b0ba0..0000000 --- a/DefaultSessionFactory.java +++ /dev/null @@ -1,700 +0,0 @@ -/* - * (C) Copyright 2013 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.ewd.impl; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.InetAddress; -import java.net.URL; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.ConsoleHandler; -import java.util.logging.Handler; -import java.util.logging.Level; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.finra.jtaf.ewd.ExtWebDriver; -import org.finra.jtaf.ewd.session.SessionFactory; -import org.openqa.selenium.Dimension; -import org.openqa.selenium.Point; -import org.openqa.selenium.Proxy; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.chrome.ChromeDriver; -import org.openqa.selenium.chrome.ChromeOptions; -import org.openqa.selenium.edge.EdgeDriver; -import org.openqa.selenium.firefox.FirefoxBinary; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.openqa.selenium.firefox.FirefoxProfile; -import org.openqa.selenium.htmlunit.HtmlUnitDriver; -import org.openqa.selenium.ie.InternetExplorerDriver; -import org.openqa.selenium.remote.CapabilityType; -import org.openqa.selenium.remote.DesiredCapabilities; -import org.openqa.selenium.remote.LocalFileDetector; -import org.openqa.selenium.remote.RemoteWebDriver; -import org.openqa.selenium.safari.SafariDriver; - -/** - * SessionPool functionality used by SessionManager instances. - * - * - */ - -public class DefaultSessionFactory implements SessionFactory { - private static final long MILLISECONDS_IN_DAY = 86400000; - private static final Object lock = new Object(); - private static final Log log = LogFactory.getLog(DefaultSessionFactory.class); - private static boolean executedTaskKill = false; - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public void cleanup(Map options) throws Exception { - - ClientProperties properties = new ClientProperties(options.get("client")); - - if (!executedTaskKill) { - synchronized (lock) { - if (properties.isKillTasksAtStartup()) { - if (properties.getBrowser().equalsIgnoreCase("ie") - || properties.getBrowser().equalsIgnoreCase("iexplore") - || properties.getBrowser().equalsIgnoreCase("*iexplore")) { - try { - Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe /T"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue IEDriverServer.exe tasks"); - } - try { - Runtime.getRuntime().exec("taskkill /F /IM iexplore.exe /T"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue Internet Explorer browsers"); - } - } else if (properties.getBrowser().equalsIgnoreCase("chrome")) { - if (properties.getOS() == null - || properties.getOS().equalsIgnoreCase("windows")) { - try { - Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T"); - - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); - } - try { - Runtime.getRuntime().exec("taskkill /F /IM chrome.exe /T"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chrome browsers"); - - } - } else if (properties.getOS().equalsIgnoreCase("linux")) { - try { - Runtime.getRuntime().exec("killall -9 chromedriver"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); - } - try { - Runtime.getRuntime().exec("killall -9 chrome"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chrome browsers"); - } - } else if (properties.getOS().equalsIgnoreCase("mac")) { - try { - Runtime.getRuntime().exec("killall -KILL chromedriver"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chromedriver tasks"); - } - try { - Runtime.getRuntime().exec("killall -KILL chrome"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chrome browsers"); - } - } else { - log.warn("Taskkill failed to kill any rogue chromedriver or chrome tasks because the OS" - + "provided is either incorrect or not supported"); - } - } else if (properties.getBrowser().equalsIgnoreCase("firefox") - || properties.getBrowser().equalsIgnoreCase("*firefox")) { - if (properties.getOS() == null - || properties.getOS().equalsIgnoreCase("windows")) { - // there is no taskkill for FirefoxDriver because - // there is no "server" used for Firefox - try { - Runtime.getRuntime().exec("taskkill /F /IM firefox.exe /T"); - - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue firefox browsers"); - } - } else if (properties.getOS().equalsIgnoreCase("linux")) { - try { - Runtime.getRuntime().exec("killall -9 firefox"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue firefox browsers"); - } - } else if (properties.getOS().equalsIgnoreCase("mac")) { - try { - Runtime.getRuntime().exec("killall -KILL firefox"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue firefox browsers"); - } - } else { - log.warn("Taskkill failed to kill any rogue firefox tasks because the OS" - + "provided is either incorrect or not supported"); - } - } - } - executedTaskKill = true; - } - } - - removeWebDriverTempOldFolders(properties); - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public DesiredCapabilities createCapabilities(Map options) throws Exception { - - ClientProperties properties = new ClientProperties(options.get("client")); - - final String browser = properties.getBrowser(); - - if (properties.isUseGrid()) { - DesiredCapabilities capabilities = null; - - if (properties.getGridUrl().length() == 0) { - throw new Exception( - "You must provide 'grid.url' to use Selenium Grid in client property file"); - } - if (browser.length() == 0) { - throw new Exception( - "You must provide 'browser' to use Selenium Grid in client property file"); - } - if (properties.getGridPlatform().length() == 0) { - throw new Exception( - "You must provide 'grid.platform' to use Selenium Grid in client property file"); - } - - if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") - || browser.equalsIgnoreCase("*iexplore")) { - capabilities = DesiredCapabilities.internetExplorer(); - } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { - capabilities = DesiredCapabilities.firefox(); - } else if (browser.equalsIgnoreCase("chrome")) { - capabilities = DesiredCapabilities.chrome(); - } else if (browser.equalsIgnoreCase("safari")) { - capabilities = DesiredCapabilities.safari(); - } else if (browser.equalsIgnoreCase("opera")) { - capabilities = DesiredCapabilities.opera(); - } else if (browser.equalsIgnoreCase("android")) { - capabilities = DesiredCapabilities.android(); - } else if (browser.equalsIgnoreCase("ipad")) { - capabilities = DesiredCapabilities.ipad(); - } else if (browser.equalsIgnoreCase("iphone")) { - capabilities = DesiredCapabilities.iphone(); - } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge")) { - capabilities = DesiredCapabilities.edge(); - } else { - throw new Exception("Unsupported browser: " + browser - + " Please refer to documentation for supported browsers."); - } - - capabilities.setVersion(properties.getBrowserVersion()); - - String platform = properties.getGridPlatform(); - if (platform != null && platform.length() > 0) { - capabilities.setCapability("platform", platform); - } else { - // Default to Windows 7 - capabilities.setCapability("platform", "Windows 7"); - } - - String sauceFile = properties.getGridSaucefile() ; - if (sauceFile != null && sauceFile.length() > 0) { - Map sOptions = new HashMap(); - sOptions.put("executable", "sauce-storage:" + sauceFile ); - sOptions.put("args", "[ '--silent', '-a', '-q' ]"); - sOptions.put("background", "true"); - - capabilities.setCapability("prerun",sOptions); - - } - - - - - // Set Proxy - String proxyStr = properties.getProxy(); - String proxyHttps = properties.getProxyHttps(); - Proxy proxy = null; - if (proxyStr != null && !proxyStr.equals("")) { - proxy = new Proxy(); - proxy.setHttpProxy(proxyStr); - - } - if (proxyHttps != null && !proxyHttps.equals("")) { - if (proxy == null) { - proxy = new Proxy(); - } - proxy.setSslProxy(proxyHttps); - } - - if (proxy != null) { - capabilities.setCapability(CapabilityType.PROXY, proxy); - } - - // preparing data for session name - String computerName = null; - try { - computerName = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - } - - capabilities.setCapability("name", "JTAF EWD client=" + properties.getClient() - + "; started from " + computerName); - - String gridProperties = properties.getGridProperties(); - if (gridProperties != null && gridProperties.length() > 0) { - String[] gridPropertiesSlpitted = gridProperties.split(" "); - for (String gridPropertiesSlpittedCurrent : gridPropertiesSlpitted) { - if (gridPropertiesSlpittedCurrent != null - && gridPropertiesSlpittedCurrent.length() > 0) { - String[] propertyNameAndValue = gridPropertiesSlpittedCurrent.split("="); - if (propertyNameAndValue.length == 2) { - capabilities.setCapability(propertyNameAndValue[0], - propertyNameAndValue[1]); - } - } - } - } - - return capabilities; - } else { - log.debug("browser [" + browser + "]"); - - // Turning off all console logs using java.util.logging - Handler[] h = java.util.logging.LogManager.getLogManager().getLogger("").getHandlers(); - for (int i = 0; i < h.length; i++) { - if (h[i] instanceof ConsoleHandler) { - h[i].setLevel(Level.OFF); - } - } - - String proxyProperty = properties.getProxy(); - DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); - if (proxyProperty != null) { - Proxy proxy = new Proxy(); - proxy.setHttpProxy(proxyProperty).setFtpProxy(proxyProperty).setSslProxy( - proxyProperty); - desiredCapabilities = new DesiredCapabilities(); - if (browser != null && browser.equalsIgnoreCase("chrome")) { - // chrome way of proxy initialization - desiredCapabilities.setCapability("chrome.switches", Arrays - .asList("--proxy-server=http://" + proxy)); - } else { - // ff and ie way of proxy initialization - desiredCapabilities.setCapability(CapabilityType.PROXY, proxy); - } - } - - if (properties.getDownloadFolder() != null - && properties.getDownloadFolder().length() > 0) { - // '0' means to download to the desktop, '1' means to download - // to the default "Downloads" directory, '2' means to use the - // directory you specify in "browser.download.dir" - desiredCapabilities.setCapability("browser.download.folderList", 2); - desiredCapabilities.setCapability("browser.download.dir", System - .getProperty("user.dir") - + System.getProperty("file.separator") + properties.getDownloadFolder()); - desiredCapabilities - .setCapability( - "browser.helperApps.neverAsk.saveToDisk", - "text/csv, application/octet-stream, application/pdf, application/vnd.fdf, application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff"); - desiredCapabilities.setCapability("browser.helperApps.alwaysAsk.force", false); - desiredCapabilities.setCapability("browser.download.manager.showWhenStarting", - false); - } - return desiredCapabilities; - } - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public WebDriver createInnerDriver(Map options, DesiredCapabilities capabilities) - throws Exception { - ClientProperties properties = new ClientProperties(options.get("client")); - - WebDriver wd = null; - DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities); - String browser = properties.getBrowser(); - - if (properties.isUseGrid()) { - RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(properties.getGridUrl()), - capabilities); - remoteWebDriver.setFileDetector(new LocalFileDetector()); - wd = remoteWebDriver; - }else { - if (browser == null || browser.equals("")) { - throw new RuntimeException( - "Browser cannot be null. Please set 'browser' in client properties. Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); - } else if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") - || browser.equalsIgnoreCase("*iexplore")) { - String webdriverIEDriver = properties.getWebDriverIEDriver(); - - if (webdriverIEDriver != null) { - System.setProperty("webdriver.ie.driver", webdriverIEDriver); - } - - String browserVersion = properties.getBrowserVersion(); - - if (browserVersion == null || browserVersion.equals("")) { - throw new RuntimeException( - "When using IE as the browser, please set 'browser.version' in client properties"); - } else { - if (browserVersion.startsWith("9")) { - desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); - desiredCapabilities - .setCapability( - InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, - true); - wd = new InternetExplorerDriver(desiredCapabilities); - } else { - wd = new InternetExplorerDriver(desiredCapabilities); - } - } - } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { - final String ffProfileFolder = properties.getFirefoxProfileFolder(); - final String ffProfileFile = properties.getFirefoxProfileFile(); - final String path = properties.getBinaryPath(); - final String webDriverGeckoDriver = properties.getWebDriverGeckoDriver(); - - - if(webDriverGeckoDriver != null){ - - System.setProperty("webdriver.gecko.driver", webDriverGeckoDriver); - - } - - if (path != null) { - FirefoxBinary fireFox = getFFBinary(path); - FirefoxProfile ffp = null; - - if (ffProfileFolder != null) { - ffp = new FirefoxProfile(new File(ffProfileFolder)); - } else { - ffp = new FirefoxProfile(); - } - - if (ffProfileFile != null) { - addPreferences(ffp, ffProfileFile); - } - - addPreferences(ffp); - - List ffExtensions = properties.getFirefoxExtensions(); - if (ffExtensions != null && ffExtensions.size() > 0) { - addExtensionsToFirefoxProfile(ffp, ffExtensions); - } - - wd = new FirefoxDriver(fireFox, ffp, desiredCapabilities); - } else { - wd = new FirefoxDriver(desiredCapabilities); - } - } else if (browser.equalsIgnoreCase("chrome")) { - - String webdriverChromeDriver = properties.getWebDriverChromeDriver(); - - if (webdriverChromeDriver != null) { - System.setProperty("webdriver.chrome.driver", webdriverChromeDriver); - } - - // for downloading with Chrome - if(properties.getDownloadFolder() != null) { - HashMap chromePrefs = new HashMap(); - chromePrefs.put("profile.default_content_settings.popups", 0); - chromePrefs.put("download.default_directory", properties.getDownloadFolder()); - ChromeOptions chromeOptions = new ChromeOptions(); - chromeOptions.setExperimentalOption("prefs", chromePrefs); - desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); - } - - wd = new ChromeDriver(desiredCapabilities); - } else if (browser.equalsIgnoreCase("safari")) { - wd = new SafariDriver(desiredCapabilities); - } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge") - || browser.equalsIgnoreCase("edge")) { - wd = new EdgeDriver(desiredCapabilities); - } else if (browser.equalsIgnoreCase("htmlunit")) { - wd = new HtmlUnitDriver(desiredCapabilities); - ((HtmlUnitDriver) wd).setJavascriptEnabled(true); - } else { - throw new Exception("Unsupported browser type: " + browser - + ". Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); - } - - // move browser windows to specific position. It's useful for - // debugging... - final int browserInitPositionX = properties.getBrowserInitPositionX(); - final int browserInitPositionY = properties.getBrowserInitPositionY(); - if (browserInitPositionX != 0 || browserInitPositionY != 0) { - wd.manage().window().setSize(new Dimension(1280, 1024)); - wd.manage().window().setPosition(new Point(browserInitPositionX, browserInitPositionY)); - } - } - - return wd; - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public ExtWebDriver createNewSession(Map options, WebDriver wd) { - DefaultExtWebDriver selenium = new DefaultExtWebDriver(); - selenium.setWrappedDriver(wd); - - // Get client properties file - ClientProperties properties = new ClientProperties(options.get("client")); - - // Set client properties (specific to our factory/implementation) - selenium.setClientProperties(properties); - - // Set timeout value - selenium.setMaxRequestTimeout(properties.getMaxRequestTimeoutString()); - - // Highlighting - selenium.setHighlightColors(properties.getHighlightColorMap()); - selenium.setIsHighlight(properties.isHighlight()); - - return selenium; - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public Map createDefaultOptions() { - HashMap ret = new HashMap(); - // Add any default options needed here (like path to default properties) - - ret.put("client", "client.properties"); - - return ret; - } - - /** - * - * @param ffp - * for use in setting the firefox profile for the tests to use - * when running firefox - */ - private static void addPreferences(FirefoxProfile ffp) { - ffp.setPreference("capability.policy.default.HTMLDocument.readyState", "allAccess"); - ffp.setPreference("capability.policy.default.HTMLDocument.compatMode", "allAccess"); - ffp.setPreference("capability.policy.default.Document.compatMode", "allAccess"); - ffp.setPreference("capability.policy.default.Location.href", "allAccess"); - ffp.setPreference("capability.policy.default.Window.pageXOffset", "allAccess"); - ffp.setPreference("capability.policy.default.Window.pageYOffset", "allAccess"); - ffp.setPreference("capability.policy.default.Window.frameElement", "allAccess"); - ffp.setPreference("capability.policy.default.Window.frameElement.get", "allAccess"); - ffp.setPreference("capability.policy.default.Window.QueryInterface", "allAccess"); - ffp.setPreference("capability.policy.default.Window.mozInnerScreenY", "allAccess"); - ffp.setPreference("capability.policy.default.Window.mozInnerScreenX", "allAccess"); - } - - /** - * - * @param ffp - * the firefox profile you are using - * @param propertiesFile - * the properties you want to add to the profile - */ - private static void addPreferences(FirefoxProfile ffp, String propertiesFile) { - Properties firefoxProfile = new Properties(); - - try(FileInputStream fis = new FileInputStream(propertiesFile)) { - firefoxProfile.load(fis); - } catch (Throwable th) { - throw new RuntimeException("Could not load firefox profile", th); - } - - for (Object o : firefoxProfile.keySet()) { - String key = (String) o; - String getVal = null; - if (key.endsWith(".type")) { - getVal = key.substring(0, key.lastIndexOf(".")); - } - - if (getVal != null) { - String type = firefoxProfile.getProperty(key); - String value = firefoxProfile.getProperty(getVal + ".value"); - - if (value.contains("${PROJECT_PATH}")) { - String projectPath = (new File("")).getAbsolutePath(); - value = projectPath + value.replaceAll("\\$\\{PROJECT_PATH\\}", ""); - } - - if (type.equalsIgnoreCase("BOOLEAN")) { - ffp.setPreference(getVal, Boolean.parseBoolean(value)); - } else if (type.equalsIgnoreCase("STRING")) { - ffp.setPreference(getVal, value); - } else if (type.equalsIgnoreCase("INTEGER") || type.equalsIgnoreCase("INT")) { - ffp.setPreference(getVal, Integer.parseInt(value)); - } - } - } - } - - /** - * - * @param ffp - * the firefox profile specified - * @param extensions - * extensions desired to be added - * @throws IOException - */ - private static void addExtensionsToFirefoxProfile(FirefoxProfile ffp, List extensions) - throws IOException { - for (String s : extensions) { - ffp.addExtension(new File(s)); - } - } - - /** - * - * @param filePath - * the binary path location of the firefox app (where it's - * installed) - * @return - */ - private static FirefoxBinary getFFBinary(String filePath) { - File[] possibleLocations = { new File(filePath != null ? filePath : ""), - new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe"), - new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"), }; - - File ffbinary = null; - - for (File curr : possibleLocations) { - if (curr.exists()) { - ffbinary = curr; - break; - } - } - - if (ffbinary == null) { - throw new RuntimeException( - "Unable to find firefox binary, please ensure that firefox is installed " - + "on your system. If it is then please determine the path to your firefox.exe and set it as " - + "binaryPath="); - } else { - return new FirefoxBinary(ffbinary); - } - } - - /** - * This method cleans out folders where the WebDriver temp information is - * stored. - * - * @param properties - * client properties specified - */ - private static void removeWebDriverTempOldFolders(ClientProperties properties) { - String tempFolder = System.getProperty("java.io.tmpdir"); - - int numberOfDaysToKeepTempFolders = properties.getNumberOfDaysToKeepTempFolders(); - if (numberOfDaysToKeepTempFolders < 0) { - numberOfDaysToKeepTempFolders = 7; - } - - List tempFolderNameContainsList = new ArrayList(); - tempFolderNameContainsList.add("anonymous"); - tempFolderNameContainsList.add("scoped_dir"); - tempFolderNameContainsList.add("webdriver-ie"); - - // add parameters from config file - String tempFolderNameContainsListFromProp = properties.getTempFolderNameContainsList(); - if (tempFolderNameContainsListFromProp != null) { - String[] tempFolderNameContainsListFromPropSpit = tempFolderNameContainsListFromProp - .split(","); - for (String name : tempFolderNameContainsListFromPropSpit) { - tempFolderNameContainsList.add(name); - } - } - - removeFolders(tempFolder, tempFolderNameContainsList, numberOfDaysToKeepTempFolders); - } - - /** - * This method can be called to remove specific folders or set how long you - * want to keep the temp information. - * - * @param folder - * which temp folder you want to remove - * @param folderTemplates - * the templates of these temp folders - * @param numberOfDaysToKeepTempFolders - * how long you want to keep the temp information - */ - private final static void removeFolders(String folder, List folderTemplates, - int numberOfDaysToKeepTempFolders) { - long dateToRemoveFiledAfter = (new Date()).getTime() - - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); - - File tempFolder = new File(folder); - File[] folderChildren = tempFolder.listFiles(); - if(null == folderChildren) { - log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); - return; - } - - for (File currentFile : folderChildren) { - if (currentFile.isDirectory()) { - for (String folderTemplate : folderTemplates) { - if (currentFile.getName().contains(folderTemplate) - && (currentFile.lastModified() < dateToRemoveFiledAfter)) { - try { - currentFile.delete(); - FileUtils.deleteDirectory(currentFile); - log.debug("Folder '" + currentFile.getName() + "' deleted..."); - } catch (Exception e) { - log.fatal("Error deleting folder '" + currentFile.getName() + "'"); - } - } - } - } - } - } -} From 239983041a5a3e0250e540d4840ff5246c6496f0 Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Wed, 5 Apr 2017 13:20:24 -0400 Subject: [PATCH 04/10] Add files via upload --- .../finra/jtaf/ewd/impl/ClientProperties.java | 29 +++++++------------ .../jtaf/ewd/impl/DefaultSessionFactory.java | 18 ++++++++---- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/finra/jtaf/ewd/impl/ClientProperties.java b/src/main/java/org/finra/jtaf/ewd/impl/ClientProperties.java index 2942b6a..c8d8963 100644 --- a/src/main/java/org/finra/jtaf/ewd/impl/ClientProperties.java +++ b/src/main/java/org/finra/jtaf/ewd/impl/ClientProperties.java @@ -19,7 +19,6 @@ import java.io.File; import java.net.URL; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -31,20 +30,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.ImmutableMap; - /** * Enables storage of and access to driver and browser configuration. * */ public class ClientProperties { - private static final String CLIENT_KEY = "client"; - private final Logger logger = LoggerFactory.getLogger(ClientProperties.class.getPackage().getName()); private URL client; - - private final Map options; + private final PropertiesConfiguration config; private final PropertiesConfigurationLayout propertiesConfigurationLayout; @@ -73,7 +67,7 @@ public class ClientProperties { private final String binaryPath; private final String webDriverIEDriver; private final String webDriverChromeDriver; - + private final String webDriverGeckoDriver; private boolean isHighlight; private final Map highlightColorMap; @@ -102,13 +96,6 @@ public class ClientProperties { * the file to be loaded */ public ClientProperties(String filePath) { - this(Collections.singletonMap(CLIENT_KEY, filePath)); - } - - public ClientProperties(Map options) { - this.options = ImmutableMap.copyOf(options); - String filePath = options.get(CLIENT_KEY); - URL clientPath = this.getClass().getClassLoader().getResource(filePath); this.config = new PropertiesConfiguration(); this.config.setDelimiterParsingDisabled(true); @@ -191,6 +178,8 @@ public ClientProperties(Map options) { webDriverIEDriver = load("webdriver.ie.driver", null, "Path to IEDriverServer.exe"); webDriverChromeDriver = load("webdriver.chrome.driver", null, "Path to chromedriver executable"); + webDriverGeckoDriver = load("webdriver.gecko.driver", null, + "Path to GeckoDriver executable"); String uploadFolderStr = load("upload.folder", null, "Default folder to grab files from to perform upload"); @@ -315,9 +304,7 @@ public ClientProperties(Map options) { * already contains the given key */ private final String load(String key, String defaultValue, String comment) { - if(options.containsKey(key)) { - return options.get(key); - } else if (config.getProperty(key) != null) { + if (config.getProperty(key) != null) { return config.getString(key); } else { if (defaultValue != null) { @@ -531,6 +518,12 @@ public String getWebDriverIEDriver() { public String getWebDriverChromeDriver() { return webDriverChromeDriver; } + + + public String getWebDriverGeckoDriver() { + return webDriverGeckoDriver; + } + /** * Returns the name of the browser. diff --git a/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java b/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java index 61364b9..89b0ba0 100644 --- a/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java +++ b/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java @@ -76,7 +76,7 @@ public class DefaultSessionFactory implements SessionFactory { @Override public void cleanup(Map options) throws Exception { - ClientProperties properties = new ClientProperties(options); + ClientProperties properties = new ClientProperties(options.get("client")); if (!executedTaskKill) { synchronized (lock) { @@ -180,7 +180,7 @@ public void cleanup(Map options) throws Exception { @Override public DesiredCapabilities createCapabilities(Map options) throws Exception { - ClientProperties properties = new ClientProperties(options); + ClientProperties properties = new ClientProperties(options.get("client")); final String browser = properties.getBrowser(); @@ -351,7 +351,7 @@ public DesiredCapabilities createCapabilities(Map options) throw @Override public WebDriver createInnerDriver(Map options, DesiredCapabilities capabilities) throws Exception { - ClientProperties properties = new ClientProperties(options); + ClientProperties properties = new ClientProperties(options.get("client")); WebDriver wd = null; DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities); @@ -395,7 +395,15 @@ public WebDriver createInnerDriver(Map options, DesiredCapabilit final String ffProfileFolder = properties.getFirefoxProfileFolder(); final String ffProfileFile = properties.getFirefoxProfileFile(); final String path = properties.getBinaryPath(); - + final String webDriverGeckoDriver = properties.getWebDriverGeckoDriver(); + + + if(webDriverGeckoDriver != null){ + + System.setProperty("webdriver.gecko.driver", webDriverGeckoDriver); + + } + if (path != null) { FirefoxBinary fireFox = getFFBinary(path); FirefoxProfile ffp = null; @@ -477,7 +485,7 @@ public ExtWebDriver createNewSession(Map options, WebDriver wd) selenium.setWrappedDriver(wd); // Get client properties file - ClientProperties properties = new ClientProperties(options); + ClientProperties properties = new ClientProperties(options.get("client")); // Set client properties (specific to our factory/implementation) selenium.setClientProperties(properties); From 04269ceb8a5d2074253650f425905bdcb8e42178 Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Wed, 5 Apr 2017 14:41:32 -0400 Subject: [PATCH 05/10] Add files via upload --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ccab69e..15b07f8 100644 --- a/pom.xml +++ b/pom.xml @@ -151,7 +151,7 @@ ${project.build.directory}/coverage-reports/jacoco-it.exec - failsafeArgLine + failsafeArgLine @@ -370,4 +370,4 @@ https://oss.sonatype.org/content/repositories/snapshots - \ No newline at end of file + From 5d2090a16fa46c29aef72187efa3b24b982d864f Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Wed, 5 Apr 2017 16:00:07 -0400 Subject: [PATCH 06/10] Add files via upload --- pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pom.xml b/pom.xml index 15b07f8..1ef1637 100644 --- a/pom.xml +++ b/pom.xml @@ -126,6 +126,9 @@ + + false + org.apache.maven.plugins From fd4cd2412482c63f7c0e0e13d0aef94681e06ed2 Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Wed, 5 Apr 2017 16:17:31 -0400 Subject: [PATCH 07/10] Add files via upload --- pom.xml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index 1ef1637..869ac4d 100644 --- a/pom.xml +++ b/pom.xml @@ -68,6 +68,7 @@ UTF-8 1.7.8 + true @@ -83,7 +84,6 @@ - false true 0 @@ -126,9 +126,6 @@ - - false - org.apache.maven.plugins From be3a678967bc194701f017d62e39e5d4cc4f317c Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Thu, 6 Apr 2017 11:29:42 -0400 Subject: [PATCH 08/10] Add files via upload --- pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 869ac4d..0cf7d5b 100644 --- a/pom.xml +++ b/pom.xml @@ -203,9 +203,9 @@ - org.mortbay.jetty - jetty-maven-plugin - 8.1.14.v20131031 + org.eclipse.jetty + jetty-maven-plugin + 9.3.0.M2 start-jetty From ab9a135aeb18fe9e3d93b953174fd590b5649f19 Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Thu, 25 May 2017 15:56:49 -0400 Subject: [PATCH 09/10] Add files via upload --- pom.xml | 749 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 377 insertions(+), 372 deletions(-) diff --git a/pom.xml b/pom.xml index dbc396c..8a3702b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,372 +1,377 @@ - - 4.0.0 - org.finra.jtaf - jtaf-extwebdriver - 1.5.3-SNAPSHOT - jar - Extensions for WebDriver - ExtWebDriver is an enhancement to the WebDriver API, with features such as widget library, session management and extended functions - http://finraos.github.io/JTAF-ExtWebDriver/ - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - scm:git:https://github.com/FINRAOS/JTAF-ExtWebDriver.git - scm:git:https://github.com/FINRAOS/JTAF-ExtWebDriver.git - https://github.com/FINRAOS/JTAF-ExtWebDriver.git - HEAD - - - - kood1 - Daniel Koo - danieljamin.koo@gmail.com - http://github.com/kood1 - - - bryantrobbins - Bryan Robbins - bryantrobbins@gmail.com - https://github.com/bryantrobbins - - - mike-glorioso - Mike Glorioso - mike.glorioso@gmail.com - http://github.com/mike-glorioso - - - lathanagaraj - Latha Nagaraj - latha.nagaraj@gmail.com - https://github.com/lathanagaraj - - - SMxJrz - Stephen Mele - smelecs@gmail.com - http://github.com/SMxJrz - - - mchao47 - Michael Chao - mchao47@gmail.com - http://github.com/mchao47 - - - - - org.sonatype.oss - oss-parent - 7 - - - - UTF-8 - 1.7.8 - - - - - org.apache.maven.plugins - maven-pmd-plugin - - - verify - - check - - - - - true - 0 - - rulesets/java/basic.xml - rulesets/java/strictexception.xml - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.16 - - true - - - - org.jacoco - jacoco-maven-plugin - 0.6.3.201306030806 - - - - - pre-integration-test - pre-integration-test - - prepare-agent - - - - ${project.build.directory}/coverage-reports/jacoco-it.exec - - failsafeArgLine - - - - - post-integration-test - post-integration-test - - report - - - - ${project.build.directory}/coverage-reports/jacoco-it.exec - - ${project.reporting.outputDirectory}/jacoco-it - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.16 - - - integration-test - - integration-test - - - - verify - - verify - - - - - false - - **/*Test* - - - **/*BrowserOnlyTest* - - methods - 4 - ${failsafeArgLine} - - - - org.eclipse.jetty - jetty-maven-plugin - 9.3.0.M2 - - - start-jetty - pre-integration-test - - run - - - 0 - true - - - - stop-jetty - post-integration-test - - stop - - - - - - - 29090 - - - 10 - 28005 - STOP - src/test/resources/webapp - - /simpleapp - - - - - org.apache.maven.plugins - maven-release-plugin - 2.4.1 - - forked-path - false - ${arguments} -Psonatype-oss-release - - - - - - - release-sign-artifacts - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.4 - - - sign-artifacts - verify - - sign - - - - - - - - - - - - org.seleniumhq.selenium - selenium-support - 3.3.1 - - - org.seleniumhq.selenium - htmlunit-driver - 2.26 - - - org.seleniumhq.selenium - selenium-java - 3.3.1 - - - org.seleniumhq.selenium - selenium-leg-rc - 3.3.1 - - - - org.ccil.cowan.tagsoup - tagsoup - 1.2.1 - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - compile - - - org.slf4j - slf4j-log4j12 - ${org.slf4j.version} - test - - - log4j - log4j - 1.2.14 - test - - - - - commons-configuration - commons-configuration - 1.9 - - - junit - junit - 4.11 - - - xml-apis - xml-apis - 1.4.01 - - - commons-lang - commons-lang - 2.6 - - - com.google.guava - guava - 15.0 - - - - - sonatype-nexus-staging - Sonatype Nexus release repository - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - - sonatype-nexus-snapshots - Sonatype Snapshot Repository - https://oss.sonatype.org/content/repositories/snapshots - - - + + 4.0.0 + org.finra.jtaf + jtaf-extwebdriver + 1.5.5-SNAPSHOT + jar + Extensions for WebDriver + ExtWebDriver is an enhancement to the WebDriver API, with features such as widget library, session management and extended functions + http://finraos.github.io/JTAF-ExtWebDriver/ + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + scm:git:https://github.com/FINRAOS/JTAF-ExtWebDriver.git + scm:git:https://github.com/FINRAOS/JTAF-ExtWebDriver.git + https://github.com/FINRAOS/JTAF-ExtWebDriver.git + HEAD + + + + kood1 + Daniel Koo + danieljamin.koo@gmail.com + http://github.com/kood1 + + + bryantrobbins + Bryan Robbins + bryantrobbins@gmail.com + https://github.com/bryantrobbins + + + mike-glorioso + Mike Glorioso + mike.glorioso@gmail.com + http://github.com/mike-glorioso + + + lathanagaraj + Latha Nagaraj + latha.nagaraj@gmail.com + https://github.com/lathanagaraj + + + SMxJrz + Stephen Mele + smelecs@gmail.com + http://github.com/SMxJrz + + + mchao47 + Michael Chao + mchao47@gmail.com + http://github.com/mchao47 + + + + + org.sonatype.oss + oss-parent + 7 + + + + UTF-8 + 1.7.8 + + + + + org.apache.maven.plugins + maven-pmd-plugin + + + verify + + check + + + + + false + true + 0 + + rulesets/java/basic.xml + rulesets/java/strictexception.xml + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.16 + + true + + + + org.jacoco + jacoco-maven-plugin + 0.7.9 + + + + + pre-integration-test + pre-integration-test + + prepare-agent + + + + ${project.build.directory}/coverage-reports/jacoco-it.exec + + failsafeArgLine + + + + + post-integration-test + post-integration-test + + report + + + + ${project.build.directory}/coverage-reports/jacoco-it.exec + + ${project.reporting.outputDirectory}/jacoco-it + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 2.16 + + + integration-test + + integration-test + + + + verify + + verify + + + + + false + + **/*Test* + + + **/*BrowserOnlyTest* + + methods + 4 + ${failsafeArgLine} + + + + org.eclipse.jetty + jetty-maven-plugin + 9.2.19.v20160908 + + + start-jetty + pre-integration-test + + start + + + true + + + + stop-jetty + post-integration-test + + stop + + + + + 28005 + STOP + src/test/resources/webapp + + /simpleapp + + + + jetty.port + 29090 + + + + org.eclipse.jetty.annotations.maxWait + 120 + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.4.1 + + forked-path + false + ${arguments} -Psonatype-oss-release + + + + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.4 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + org.seleniumhq.selenium + selenium-support + 3.3.1 + + + org.seleniumhq.selenium + htmlunit-driver + 2.26 + + + org.seleniumhq.selenium + selenium-java + 3.3.1 + + + org.seleniumhq.selenium + selenium-leg-rc + 3.3.1 + + + + org.ccil.cowan.tagsoup + tagsoup + 1.2.1 + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + compile + + + org.slf4j + slf4j-log4j12 + ${org.slf4j.version} + test + + + log4j + log4j + 1.2.14 + test + + + + + commons-configuration + commons-configuration + 1.9 + + + junit + junit + 4.11 + + + xml-apis + xml-apis + 1.4.01 + + + commons-lang + commons-lang + 2.6 + + + com.google.guava + guava + 15.0 + + + + + sonatype-nexus-staging + Sonatype Nexus release repository + https://oss.sonatype.org/service/local/staging/deploy/maven2 + + + + sonatype-nexus-snapshots + Sonatype Snapshot Repository + https://oss.sonatype.org/content/repositories/snapshots + + + From 58dd60b1937d43c3e16754d9a6e47c967b3a759f Mon Sep 17 00:00:00 2001 From: Anirudh Anil Arora Date: Thu, 25 May 2017 16:10:25 -0400 Subject: [PATCH 10/10] Add files via upload --- .../jtaf/ewd/impl/DefaultSessionFactory.java | 1400 ++++++++--------- 1 file changed, 700 insertions(+), 700 deletions(-) diff --git a/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java b/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java index 89b0ba0..317f807 100644 --- a/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java +++ b/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java @@ -1,700 +1,700 @@ -/* - * (C) Copyright 2013 Java Test Automation Framework Contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.finra.jtaf.ewd.impl; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.InetAddress; -import java.net.URL; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.logging.ConsoleHandler; -import java.util.logging.Handler; -import java.util.logging.Level; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.finra.jtaf.ewd.ExtWebDriver; -import org.finra.jtaf.ewd.session.SessionFactory; -import org.openqa.selenium.Dimension; -import org.openqa.selenium.Point; -import org.openqa.selenium.Proxy; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.chrome.ChromeDriver; -import org.openqa.selenium.chrome.ChromeOptions; -import org.openqa.selenium.edge.EdgeDriver; -import org.openqa.selenium.firefox.FirefoxBinary; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.openqa.selenium.firefox.FirefoxProfile; -import org.openqa.selenium.htmlunit.HtmlUnitDriver; -import org.openqa.selenium.ie.InternetExplorerDriver; -import org.openqa.selenium.remote.CapabilityType; -import org.openqa.selenium.remote.DesiredCapabilities; -import org.openqa.selenium.remote.LocalFileDetector; -import org.openqa.selenium.remote.RemoteWebDriver; -import org.openqa.selenium.safari.SafariDriver; - -/** - * SessionPool functionality used by SessionManager instances. - * - * - */ - -public class DefaultSessionFactory implements SessionFactory { - private static final long MILLISECONDS_IN_DAY = 86400000; - private static final Object lock = new Object(); - private static final Log log = LogFactory.getLog(DefaultSessionFactory.class); - private static boolean executedTaskKill = false; - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public void cleanup(Map options) throws Exception { - - ClientProperties properties = new ClientProperties(options.get("client")); - - if (!executedTaskKill) { - synchronized (lock) { - if (properties.isKillTasksAtStartup()) { - if (properties.getBrowser().equalsIgnoreCase("ie") - || properties.getBrowser().equalsIgnoreCase("iexplore") - || properties.getBrowser().equalsIgnoreCase("*iexplore")) { - try { - Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe /T"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue IEDriverServer.exe tasks"); - } - try { - Runtime.getRuntime().exec("taskkill /F /IM iexplore.exe /T"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue Internet Explorer browsers"); - } - } else if (properties.getBrowser().equalsIgnoreCase("chrome")) { - if (properties.getOS() == null - || properties.getOS().equalsIgnoreCase("windows")) { - try { - Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T"); - - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); - } - try { - Runtime.getRuntime().exec("taskkill /F /IM chrome.exe /T"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chrome browsers"); - - } - } else if (properties.getOS().equalsIgnoreCase("linux")) { - try { - Runtime.getRuntime().exec("killall -9 chromedriver"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); - } - try { - Runtime.getRuntime().exec("killall -9 chrome"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chrome browsers"); - } - } else if (properties.getOS().equalsIgnoreCase("mac")) { - try { - Runtime.getRuntime().exec("killall -KILL chromedriver"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chromedriver tasks"); - } - try { - Runtime.getRuntime().exec("killall -KILL chrome"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue chrome browsers"); - } - } else { - log.warn("Taskkill failed to kill any rogue chromedriver or chrome tasks because the OS" - + "provided is either incorrect or not supported"); - } - } else if (properties.getBrowser().equalsIgnoreCase("firefox") - || properties.getBrowser().equalsIgnoreCase("*firefox")) { - if (properties.getOS() == null - || properties.getOS().equalsIgnoreCase("windows")) { - // there is no taskkill for FirefoxDriver because - // there is no "server" used for Firefox - try { - Runtime.getRuntime().exec("taskkill /F /IM firefox.exe /T"); - - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue firefox browsers"); - } - } else if (properties.getOS().equalsIgnoreCase("linux")) { - try { - Runtime.getRuntime().exec("killall -9 firefox"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue firefox browsers"); - } - } else if (properties.getOS().equalsIgnoreCase("mac")) { - try { - Runtime.getRuntime().exec("killall -KILL firefox"); - } catch (IOException e) { - log.warn("Taskkill failed to kill any rogue firefox browsers"); - } - } else { - log.warn("Taskkill failed to kill any rogue firefox tasks because the OS" - + "provided is either incorrect or not supported"); - } - } - } - executedTaskKill = true; - } - } - - removeWebDriverTempOldFolders(properties); - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public DesiredCapabilities createCapabilities(Map options) throws Exception { - - ClientProperties properties = new ClientProperties(options.get("client")); - - final String browser = properties.getBrowser(); - - if (properties.isUseGrid()) { - DesiredCapabilities capabilities = null; - - if (properties.getGridUrl().length() == 0) { - throw new Exception( - "You must provide 'grid.url' to use Selenium Grid in client property file"); - } - if (browser.length() == 0) { - throw new Exception( - "You must provide 'browser' to use Selenium Grid in client property file"); - } - if (properties.getGridPlatform().length() == 0) { - throw new Exception( - "You must provide 'grid.platform' to use Selenium Grid in client property file"); - } - - if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") - || browser.equalsIgnoreCase("*iexplore")) { - capabilities = DesiredCapabilities.internetExplorer(); - } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { - capabilities = DesiredCapabilities.firefox(); - } else if (browser.equalsIgnoreCase("chrome")) { - capabilities = DesiredCapabilities.chrome(); - } else if (browser.equalsIgnoreCase("safari")) { - capabilities = DesiredCapabilities.safari(); - } else if (browser.equalsIgnoreCase("opera")) { - capabilities = DesiredCapabilities.opera(); - } else if (browser.equalsIgnoreCase("android")) { - capabilities = DesiredCapabilities.android(); - } else if (browser.equalsIgnoreCase("ipad")) { - capabilities = DesiredCapabilities.ipad(); - } else if (browser.equalsIgnoreCase("iphone")) { - capabilities = DesiredCapabilities.iphone(); - } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge")) { - capabilities = DesiredCapabilities.edge(); - } else { - throw new Exception("Unsupported browser: " + browser - + " Please refer to documentation for supported browsers."); - } - - capabilities.setVersion(properties.getBrowserVersion()); - - String platform = properties.getGridPlatform(); - if (platform != null && platform.length() > 0) { - capabilities.setCapability("platform", platform); - } else { - // Default to Windows 7 - capabilities.setCapability("platform", "Windows 7"); - } - - String sauceFile = properties.getGridSaucefile() ; - if (sauceFile != null && sauceFile.length() > 0) { - Map sOptions = new HashMap(); - sOptions.put("executable", "sauce-storage:" + sauceFile ); - sOptions.put("args", "[ '--silent', '-a', '-q' ]"); - sOptions.put("background", "true"); - - capabilities.setCapability("prerun",sOptions); - - } - - - - - // Set Proxy - String proxyStr = properties.getProxy(); - String proxyHttps = properties.getProxyHttps(); - Proxy proxy = null; - if (proxyStr != null && !proxyStr.equals("")) { - proxy = new Proxy(); - proxy.setHttpProxy(proxyStr); - - } - if (proxyHttps != null && !proxyHttps.equals("")) { - if (proxy == null) { - proxy = new Proxy(); - } - proxy.setSslProxy(proxyHttps); - } - - if (proxy != null) { - capabilities.setCapability(CapabilityType.PROXY, proxy); - } - - // preparing data for session name - String computerName = null; - try { - computerName = InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - } - - capabilities.setCapability("name", "JTAF EWD client=" + properties.getClient() - + "; started from " + computerName); - - String gridProperties = properties.getGridProperties(); - if (gridProperties != null && gridProperties.length() > 0) { - String[] gridPropertiesSlpitted = gridProperties.split(" "); - for (String gridPropertiesSlpittedCurrent : gridPropertiesSlpitted) { - if (gridPropertiesSlpittedCurrent != null - && gridPropertiesSlpittedCurrent.length() > 0) { - String[] propertyNameAndValue = gridPropertiesSlpittedCurrent.split("="); - if (propertyNameAndValue.length == 2) { - capabilities.setCapability(propertyNameAndValue[0], - propertyNameAndValue[1]); - } - } - } - } - - return capabilities; - } else { - log.debug("browser [" + browser + "]"); - - // Turning off all console logs using java.util.logging - Handler[] h = java.util.logging.LogManager.getLogManager().getLogger("").getHandlers(); - for (int i = 0; i < h.length; i++) { - if (h[i] instanceof ConsoleHandler) { - h[i].setLevel(Level.OFF); - } - } - - String proxyProperty = properties.getProxy(); - DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); - if (proxyProperty != null) { - Proxy proxy = new Proxy(); - proxy.setHttpProxy(proxyProperty).setFtpProxy(proxyProperty).setSslProxy( - proxyProperty); - desiredCapabilities = new DesiredCapabilities(); - if (browser != null && browser.equalsIgnoreCase("chrome")) { - // chrome way of proxy initialization - desiredCapabilities.setCapability("chrome.switches", Arrays - .asList("--proxy-server=http://" + proxy)); - } else { - // ff and ie way of proxy initialization - desiredCapabilities.setCapability(CapabilityType.PROXY, proxy); - } - } - - if (properties.getDownloadFolder() != null - && properties.getDownloadFolder().length() > 0) { - // '0' means to download to the desktop, '1' means to download - // to the default "Downloads" directory, '2' means to use the - // directory you specify in "browser.download.dir" - desiredCapabilities.setCapability("browser.download.folderList", 2); - desiredCapabilities.setCapability("browser.download.dir", System - .getProperty("user.dir") - + System.getProperty("file.separator") + properties.getDownloadFolder()); - desiredCapabilities - .setCapability( - "browser.helperApps.neverAsk.saveToDisk", - "text/csv, application/octet-stream, application/pdf, application/vnd.fdf, application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff"); - desiredCapabilities.setCapability("browser.helperApps.alwaysAsk.force", false); - desiredCapabilities.setCapability("browser.download.manager.showWhenStarting", - false); - } - return desiredCapabilities; - } - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public WebDriver createInnerDriver(Map options, DesiredCapabilities capabilities) - throws Exception { - ClientProperties properties = new ClientProperties(options.get("client")); - - WebDriver wd = null; - DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities); - String browser = properties.getBrowser(); - - if (properties.isUseGrid()) { - RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(properties.getGridUrl()), - capabilities); - remoteWebDriver.setFileDetector(new LocalFileDetector()); - wd = remoteWebDriver; - }else { - if (browser == null || browser.equals("")) { - throw new RuntimeException( - "Browser cannot be null. Please set 'browser' in client properties. Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); - } else if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") - || browser.equalsIgnoreCase("*iexplore")) { - String webdriverIEDriver = properties.getWebDriverIEDriver(); - - if (webdriverIEDriver != null) { - System.setProperty("webdriver.ie.driver", webdriverIEDriver); - } - - String browserVersion = properties.getBrowserVersion(); - - if (browserVersion == null || browserVersion.equals("")) { - throw new RuntimeException( - "When using IE as the browser, please set 'browser.version' in client properties"); - } else { - if (browserVersion.startsWith("9")) { - desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); - desiredCapabilities - .setCapability( - InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, - true); - wd = new InternetExplorerDriver(desiredCapabilities); - } else { - wd = new InternetExplorerDriver(desiredCapabilities); - } - } - } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { - final String ffProfileFolder = properties.getFirefoxProfileFolder(); - final String ffProfileFile = properties.getFirefoxProfileFile(); - final String path = properties.getBinaryPath(); - final String webDriverGeckoDriver = properties.getWebDriverGeckoDriver(); - - - if(webDriverGeckoDriver != null){ - - System.setProperty("webdriver.gecko.driver", webDriverGeckoDriver); - - } - - if (path != null) { - FirefoxBinary fireFox = getFFBinary(path); - FirefoxProfile ffp = null; - - if (ffProfileFolder != null) { - ffp = new FirefoxProfile(new File(ffProfileFolder)); - } else { - ffp = new FirefoxProfile(); - } - - if (ffProfileFile != null) { - addPreferences(ffp, ffProfileFile); - } - - addPreferences(ffp); - - List ffExtensions = properties.getFirefoxExtensions(); - if (ffExtensions != null && ffExtensions.size() > 0) { - addExtensionsToFirefoxProfile(ffp, ffExtensions); - } - - wd = new FirefoxDriver(fireFox, ffp, desiredCapabilities); - } else { - wd = new FirefoxDriver(desiredCapabilities); - } - } else if (browser.equalsIgnoreCase("chrome")) { - - String webdriverChromeDriver = properties.getWebDriverChromeDriver(); - - if (webdriverChromeDriver != null) { - System.setProperty("webdriver.chrome.driver", webdriverChromeDriver); - } - - // for downloading with Chrome - if(properties.getDownloadFolder() != null) { - HashMap chromePrefs = new HashMap(); - chromePrefs.put("profile.default_content_settings.popups", 0); - chromePrefs.put("download.default_directory", properties.getDownloadFolder()); - ChromeOptions chromeOptions = new ChromeOptions(); - chromeOptions.setExperimentalOption("prefs", chromePrefs); - desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); - } - - wd = new ChromeDriver(desiredCapabilities); - } else if (browser.equalsIgnoreCase("safari")) { - wd = new SafariDriver(desiredCapabilities); - } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge") - || browser.equalsIgnoreCase("edge")) { - wd = new EdgeDriver(desiredCapabilities); - } else if (browser.equalsIgnoreCase("htmlunit")) { - wd = new HtmlUnitDriver(desiredCapabilities); - ((HtmlUnitDriver) wd).setJavascriptEnabled(true); - } else { - throw new Exception("Unsupported browser type: " + browser - + ". Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); - } - - // move browser windows to specific position. It's useful for - // debugging... - final int browserInitPositionX = properties.getBrowserInitPositionX(); - final int browserInitPositionY = properties.getBrowserInitPositionY(); - if (browserInitPositionX != 0 || browserInitPositionY != 0) { - wd.manage().window().setSize(new Dimension(1280, 1024)); - wd.manage().window().setPosition(new Point(browserInitPositionX, browserInitPositionY)); - } - } - - return wd; - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public ExtWebDriver createNewSession(Map options, WebDriver wd) { - DefaultExtWebDriver selenium = new DefaultExtWebDriver(); - selenium.setWrappedDriver(wd); - - // Get client properties file - ClientProperties properties = new ClientProperties(options.get("client")); - - // Set client properties (specific to our factory/implementation) - selenium.setClientProperties(properties); - - // Set timeout value - selenium.setMaxRequestTimeout(properties.getMaxRequestTimeoutString()); - - // Highlighting - selenium.setHighlightColors(properties.getHighlightColorMap()); - selenium.setIsHighlight(properties.isHighlight()); - - return selenium; - } - - /* - * (non-Javadoc) - * - * @see org.finra.jtaf.ewd.session.SessionFactory - */ - @Override - public Map createDefaultOptions() { - HashMap ret = new HashMap(); - // Add any default options needed here (like path to default properties) - - ret.put("client", "client.properties"); - - return ret; - } - - /** - * - * @param ffp - * for use in setting the firefox profile for the tests to use - * when running firefox - */ - private static void addPreferences(FirefoxProfile ffp) { - ffp.setPreference("capability.policy.default.HTMLDocument.readyState", "allAccess"); - ffp.setPreference("capability.policy.default.HTMLDocument.compatMode", "allAccess"); - ffp.setPreference("capability.policy.default.Document.compatMode", "allAccess"); - ffp.setPreference("capability.policy.default.Location.href", "allAccess"); - ffp.setPreference("capability.policy.default.Window.pageXOffset", "allAccess"); - ffp.setPreference("capability.policy.default.Window.pageYOffset", "allAccess"); - ffp.setPreference("capability.policy.default.Window.frameElement", "allAccess"); - ffp.setPreference("capability.policy.default.Window.frameElement.get", "allAccess"); - ffp.setPreference("capability.policy.default.Window.QueryInterface", "allAccess"); - ffp.setPreference("capability.policy.default.Window.mozInnerScreenY", "allAccess"); - ffp.setPreference("capability.policy.default.Window.mozInnerScreenX", "allAccess"); - } - - /** - * - * @param ffp - * the firefox profile you are using - * @param propertiesFile - * the properties you want to add to the profile - */ - private static void addPreferences(FirefoxProfile ffp, String propertiesFile) { - Properties firefoxProfile = new Properties(); - - try(FileInputStream fis = new FileInputStream(propertiesFile)) { - firefoxProfile.load(fis); - } catch (Throwable th) { - throw new RuntimeException("Could not load firefox profile", th); - } - - for (Object o : firefoxProfile.keySet()) { - String key = (String) o; - String getVal = null; - if (key.endsWith(".type")) { - getVal = key.substring(0, key.lastIndexOf(".")); - } - - if (getVal != null) { - String type = firefoxProfile.getProperty(key); - String value = firefoxProfile.getProperty(getVal + ".value"); - - if (value.contains("${PROJECT_PATH}")) { - String projectPath = (new File("")).getAbsolutePath(); - value = projectPath + value.replaceAll("\\$\\{PROJECT_PATH\\}", ""); - } - - if (type.equalsIgnoreCase("BOOLEAN")) { - ffp.setPreference(getVal, Boolean.parseBoolean(value)); - } else if (type.equalsIgnoreCase("STRING")) { - ffp.setPreference(getVal, value); - } else if (type.equalsIgnoreCase("INTEGER") || type.equalsIgnoreCase("INT")) { - ffp.setPreference(getVal, Integer.parseInt(value)); - } - } - } - } - - /** - * - * @param ffp - * the firefox profile specified - * @param extensions - * extensions desired to be added - * @throws IOException - */ - private static void addExtensionsToFirefoxProfile(FirefoxProfile ffp, List extensions) - throws IOException { - for (String s : extensions) { - ffp.addExtension(new File(s)); - } - } - - /** - * - * @param filePath - * the binary path location of the firefox app (where it's - * installed) - * @return - */ - private static FirefoxBinary getFFBinary(String filePath) { - File[] possibleLocations = { new File(filePath != null ? filePath : ""), - new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe"), - new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"), }; - - File ffbinary = null; - - for (File curr : possibleLocations) { - if (curr.exists()) { - ffbinary = curr; - break; - } - } - - if (ffbinary == null) { - throw new RuntimeException( - "Unable to find firefox binary, please ensure that firefox is installed " - + "on your system. If it is then please determine the path to your firefox.exe and set it as " - + "binaryPath="); - } else { - return new FirefoxBinary(ffbinary); - } - } - - /** - * This method cleans out folders where the WebDriver temp information is - * stored. - * - * @param properties - * client properties specified - */ - private static void removeWebDriverTempOldFolders(ClientProperties properties) { - String tempFolder = System.getProperty("java.io.tmpdir"); - - int numberOfDaysToKeepTempFolders = properties.getNumberOfDaysToKeepTempFolders(); - if (numberOfDaysToKeepTempFolders < 0) { - numberOfDaysToKeepTempFolders = 7; - } - - List tempFolderNameContainsList = new ArrayList(); - tempFolderNameContainsList.add("anonymous"); - tempFolderNameContainsList.add("scoped_dir"); - tempFolderNameContainsList.add("webdriver-ie"); - - // add parameters from config file - String tempFolderNameContainsListFromProp = properties.getTempFolderNameContainsList(); - if (tempFolderNameContainsListFromProp != null) { - String[] tempFolderNameContainsListFromPropSpit = tempFolderNameContainsListFromProp - .split(","); - for (String name : tempFolderNameContainsListFromPropSpit) { - tempFolderNameContainsList.add(name); - } - } - - removeFolders(tempFolder, tempFolderNameContainsList, numberOfDaysToKeepTempFolders); - } - - /** - * This method can be called to remove specific folders or set how long you - * want to keep the temp information. - * - * @param folder - * which temp folder you want to remove - * @param folderTemplates - * the templates of these temp folders - * @param numberOfDaysToKeepTempFolders - * how long you want to keep the temp information - */ - private final static void removeFolders(String folder, List folderTemplates, - int numberOfDaysToKeepTempFolders) { - long dateToRemoveFiledAfter = (new Date()).getTime() - - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); - - File tempFolder = new File(folder); - File[] folderChildren = tempFolder.listFiles(); - if(null == folderChildren) { - log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); - return; - } - - for (File currentFile : folderChildren) { - if (currentFile.isDirectory()) { - for (String folderTemplate : folderTemplates) { - if (currentFile.getName().contains(folderTemplate) - && (currentFile.lastModified() < dateToRemoveFiledAfter)) { - try { - currentFile.delete(); - FileUtils.deleteDirectory(currentFile); - log.debug("Folder '" + currentFile.getName() + "' deleted..."); - } catch (Exception e) { - log.fatal("Error deleting folder '" + currentFile.getName() + "'"); - } - } - } - } - } - } -} +/* + * (C) Copyright 2013 Java Test Automation Framework Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.finra.jtaf.ewd.impl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.logging.ConsoleHandler; +import java.util.logging.Handler; +import java.util.logging.Level; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.finra.jtaf.ewd.ExtWebDriver; +import org.finra.jtaf.ewd.session.SessionFactory; +import org.openqa.selenium.Dimension; +import org.openqa.selenium.Point; +import org.openqa.selenium.Proxy; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.edge.EdgeDriver; +import org.openqa.selenium.firefox.FirefoxBinary; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.openqa.selenium.htmlunit.HtmlUnitDriver; +import org.openqa.selenium.ie.InternetExplorerDriver; +import org.openqa.selenium.remote.CapabilityType; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.remote.LocalFileDetector; +import org.openqa.selenium.remote.RemoteWebDriver; +import org.openqa.selenium.safari.SafariDriver; + +/** + * SessionPool functionality used by SessionManager instances. + * + * + */ + +public class DefaultSessionFactory implements SessionFactory { + private static final long MILLISECONDS_IN_DAY = 86400000; + private static final Object lock = new Object(); + private static final Log log = LogFactory.getLog(DefaultSessionFactory.class); + private static boolean executedTaskKill = false; + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public void cleanup(Map options) throws Exception { + + ClientProperties properties = new ClientProperties(options.get("client")); + + if (!executedTaskKill) { + synchronized (lock) { + if (properties.isKillTasksAtStartup()) { + if (properties.getBrowser().equalsIgnoreCase("ie") + || properties.getBrowser().equalsIgnoreCase("iexplore") + || properties.getBrowser().equalsIgnoreCase("*iexplore")) { + try { + Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe /T"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue IEDriverServer.exe tasks"); + } + try { + Runtime.getRuntime().exec("taskkill /F /IM iexplore.exe /T"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue Internet Explorer browsers"); + } + } else if (properties.getBrowser().equalsIgnoreCase("chrome")) { + if (properties.getOS() == null + || properties.getOS().equalsIgnoreCase("windows")) { + try { + Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe /T"); + + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); + } + try { + Runtime.getRuntime().exec("taskkill /F /IM chrome.exe /T"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chrome browsers"); + + } + } else if (properties.getOS().equalsIgnoreCase("linux")) { + try { + Runtime.getRuntime().exec("killall -9 chromedriver"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chromedriver.exe processes"); + } + try { + Runtime.getRuntime().exec("killall -9 chrome"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chrome browsers"); + } + } else if (properties.getOS().equalsIgnoreCase("mac")) { + try { + Runtime.getRuntime().exec("killall -KILL chromedriver"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chromedriver tasks"); + } + try { + Runtime.getRuntime().exec("killall -KILL chrome"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue chrome browsers"); + } + } else { + log.warn("Taskkill failed to kill any rogue chromedriver or chrome tasks because the OS" + + "provided is either incorrect or not supported"); + } + } else if (properties.getBrowser().equalsIgnoreCase("firefox") + || properties.getBrowser().equalsIgnoreCase("*firefox")) { + if (properties.getOS() == null + || properties.getOS().equalsIgnoreCase("windows")) { + // there is no taskkill for FirefoxDriver because + // there is no "server" used for Firefox + try { + Runtime.getRuntime().exec("taskkill /F /IM firefox.exe /T"); + + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue firefox browsers"); + } + } else if (properties.getOS().equalsIgnoreCase("linux")) { + try { + Runtime.getRuntime().exec("killall -9 firefox"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue firefox browsers"); + } + } else if (properties.getOS().equalsIgnoreCase("mac")) { + try { + Runtime.getRuntime().exec("killall -KILL firefox"); + } catch (IOException e) { + log.warn("Taskkill failed to kill any rogue firefox browsers"); + } + } else { + log.warn("Taskkill failed to kill any rogue firefox tasks because the OS" + + "provided is either incorrect or not supported"); + } + } + } + executedTaskKill = true; + } + } + + removeWebDriverTempOldFolders(properties); + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public DesiredCapabilities createCapabilities(Map options) throws Exception { + + ClientProperties properties = new ClientProperties(options.get("client")); + + final String browser = properties.getBrowser(); + + if (properties.isUseGrid()) { + DesiredCapabilities capabilities = null; + + if (properties.getGridUrl().length() == 0) { + throw new Exception( + "You must provide 'grid.url' to use Selenium Grid in client property file"); + } + if (browser.length() == 0) { + throw new Exception( + "You must provide 'browser' to use Selenium Grid in client property file"); + } + if (properties.getGridPlatform().length() == 0) { + throw new Exception( + "You must provide 'grid.platform' to use Selenium Grid in client property file"); + } + + if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") + || browser.equalsIgnoreCase("*iexplore")) { + capabilities = DesiredCapabilities.internetExplorer(); + } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { + capabilities = DesiredCapabilities.firefox(); + } else if (browser.equalsIgnoreCase("chrome")) { + capabilities = DesiredCapabilities.chrome(); + } else if (browser.equalsIgnoreCase("safari")) { + capabilities = DesiredCapabilities.safari(); + } else if (browser.equalsIgnoreCase("opera")) { + capabilities = DesiredCapabilities.opera(); + } else if (browser.equalsIgnoreCase("android")) { + capabilities = DesiredCapabilities.android(); + } else if (browser.equalsIgnoreCase("ipad")) { + capabilities = DesiredCapabilities.ipad(); + } else if (browser.equalsIgnoreCase("iphone")) { + capabilities = DesiredCapabilities.iphone(); + } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge")) { + capabilities = DesiredCapabilities.edge(); + } else { + throw new Exception("Unsupported browser: " + browser + + " Please refer to documentation for supported browsers."); + } + + capabilities.setVersion(properties.getBrowserVersion()); + + String platform = properties.getGridPlatform(); + if (platform != null && platform.length() > 0) { + capabilities.setCapability("platform", platform); + } else { + // Default to Windows 7 + capabilities.setCapability("platform", "Windows 7"); + } + + String sauceFile = properties.getGridSaucefile() ; + if (sauceFile != null && sauceFile.length() > 0) { + Map sOptions = new HashMap(); + sOptions.put("executable", "sauce-storage:" + sauceFile ); + sOptions.put("args", "[ '--silent', '-a', '-q' ]"); + sOptions.put("background", "true"); + + capabilities.setCapability("prerun",sOptions); + + } + + + + + // Set Proxy + String proxyStr = properties.getProxy(); + String proxyHttps = properties.getProxyHttps(); + Proxy proxy = null; + if (proxyStr != null && !proxyStr.equals("")) { + proxy = new Proxy(); + proxy.setHttpProxy(proxyStr); + + } + if (proxyHttps != null && !proxyHttps.equals("")) { + if (proxy == null) { + proxy = new Proxy(); + } + proxy.setSslProxy(proxyHttps); + } + + if (proxy != null) { + capabilities.setCapability(CapabilityType.PROXY, proxy); + } + + // preparing data for session name + String computerName = null; + try { + computerName = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + } + + capabilities.setCapability("name", "JTAF EWD client=" + properties.getClient() + + "; started from " + computerName); + + String gridProperties = properties.getGridProperties(); + if (gridProperties != null && gridProperties.length() > 0) { + String[] gridPropertiesSlpitted = gridProperties.split(" "); + for (String gridPropertiesSlpittedCurrent : gridPropertiesSlpitted) { + if (gridPropertiesSlpittedCurrent != null + && gridPropertiesSlpittedCurrent.length() > 0) { + String[] propertyNameAndValue = gridPropertiesSlpittedCurrent.split("="); + if (propertyNameAndValue.length == 2) { + capabilities.setCapability(propertyNameAndValue[0], + propertyNameAndValue[1]); + } + } + } + } + + return capabilities; + } else { + log.debug("browser [" + browser + "]"); + + // Turning off all console logs using java.util.logging + Handler[] h = java.util.logging.LogManager.getLogManager().getLogger("").getHandlers(); + for (int i = 0; i < h.length; i++) { + if (h[i] instanceof ConsoleHandler) { + h[i].setLevel(Level.OFF); + } + } + + String proxyProperty = properties.getProxy(); + DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); + if (proxyProperty != null) { + Proxy proxy = new Proxy(); + proxy.setHttpProxy(proxyProperty).setFtpProxy(proxyProperty).setSslProxy( + proxyProperty); + desiredCapabilities = new DesiredCapabilities(); + if (browser != null && browser.equalsIgnoreCase("chrome")) { + // chrome way of proxy initialization + desiredCapabilities.setCapability("chrome.switches", Arrays + .asList("--proxy-server=http://" + proxy)); + } else { + // ff and ie way of proxy initialization + desiredCapabilities.setCapability(CapabilityType.PROXY, proxy); + } + } + + if (properties.getDownloadFolder() != null + && properties.getDownloadFolder().length() > 0) { + // '0' means to download to the desktop, '1' means to download + // to the default "Downloads" directory, '2' means to use the + // directory you specify in "browser.download.dir" + desiredCapabilities.setCapability("browser.download.folderList", 2); + desiredCapabilities.setCapability("browser.download.dir", System + .getProperty("user.dir") + + System.getProperty("file.separator") + properties.getDownloadFolder()); + desiredCapabilities + .setCapability( + "browser.helperApps.neverAsk.saveToDisk", + "text/csv, application/octet-stream, application/pdf, application/vnd.fdf, application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff"); + desiredCapabilities.setCapability("browser.helperApps.alwaysAsk.force", false); + desiredCapabilities.setCapability("browser.download.manager.showWhenStarting", + false); + } + return desiredCapabilities; + } + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public WebDriver createInnerDriver(Map options, DesiredCapabilities capabilities) + throws Exception { + ClientProperties properties = new ClientProperties(options.get("client")); + + WebDriver wd = null; + DesiredCapabilities desiredCapabilities = new DesiredCapabilities(capabilities); + String browser = properties.getBrowser(); + + if (properties.isUseGrid()) { + RemoteWebDriver remoteWebDriver = new RemoteWebDriver(new URL(properties.getGridUrl()), + capabilities); + remoteWebDriver.setFileDetector(new LocalFileDetector()); + wd = remoteWebDriver; + }else { + if (browser == null || browser.equals("")) { + throw new RuntimeException( + "Browser cannot be null. Please set 'browser' in client properties. Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); + } else if (browser.equalsIgnoreCase("ie") || browser.equalsIgnoreCase("iexplore") + || browser.equalsIgnoreCase("*iexplore")) { + String webdriverIEDriver = properties.getWebDriverIEDriver(); + + if (webdriverIEDriver != null) { + System.setProperty("webdriver.ie.driver", webdriverIEDriver); + } + + String browserVersion = properties.getBrowserVersion(); + + if (browserVersion == null || browserVersion.equals("")) { + throw new RuntimeException( + "When using IE as the browser, please set 'browser.version' in client properties"); + } else { + if (browserVersion.startsWith("9")) { + desiredCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); + desiredCapabilities + .setCapability( + InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, + true); + wd = new InternetExplorerDriver(desiredCapabilities); + } else { + wd = new InternetExplorerDriver(desiredCapabilities); + } + } + } else if ((browser.equalsIgnoreCase("firefox") || browser.equalsIgnoreCase("*firefox"))) { + final String ffProfileFolder = properties.getFirefoxProfileFolder(); + final String ffProfileFile = properties.getFirefoxProfileFile(); + final String path = properties.getBinaryPath(); + final String webDriverGeckoDriver = properties.getWebDriverGeckoDriver(); + + + if(webDriverGeckoDriver != null){ + + System.setProperty("webdriver.gecko.driver", webDriverGeckoDriver); + + } + + if (path != null) { + FirefoxBinary fireFox = getFFBinary(path); + FirefoxProfile ffp = null; + + if (ffProfileFolder != null) { + ffp = new FirefoxProfile(new File(ffProfileFolder)); + } else { + ffp = new FirefoxProfile(); + } + + if (ffProfileFile != null) { + addPreferences(ffp, ffProfileFile); + } + + addPreferences(ffp); + + List ffExtensions = properties.getFirefoxExtensions(); + if (ffExtensions != null && ffExtensions.size() > 0) { + addExtensionsToFirefoxProfile(ffp, ffExtensions); + } + + wd = new FirefoxDriver(fireFox, ffp, desiredCapabilities); + } else { + wd = new FirefoxDriver(desiredCapabilities); + } + } else if (browser.equalsIgnoreCase("chrome")) { + + String webdriverChromeDriver = properties.getWebDriverChromeDriver(); + + if (webdriverChromeDriver != null) { + System.setProperty("webdriver.chrome.driver", webdriverChromeDriver); + } + + // for downloading with Chrome + if(properties.getDownloadFolder() != null) { + HashMap chromePrefs = new HashMap(); + chromePrefs.put("profile.default_content_settings.popups", 0); + chromePrefs.put("download.default_directory", properties.getDownloadFolder()); + ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.setExperimentalOption("prefs", chromePrefs); + desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); + } + + wd = new ChromeDriver(desiredCapabilities); + } else if (browser.equalsIgnoreCase("safari")) { + wd = new SafariDriver(desiredCapabilities); + } else if (browser.equalsIgnoreCase("MS Edge") || browser.equalsIgnoreCase("MicrosoftEdge") + || browser.equalsIgnoreCase("edge")) { + wd = new EdgeDriver(desiredCapabilities); + } else if (browser.equalsIgnoreCase("htmlunit")) { + wd = new HtmlUnitDriver(desiredCapabilities); + ((HtmlUnitDriver) wd).setJavascriptEnabled(true); + } else { + throw new Exception("Unsupported browser type: " + browser + + ". Supported browser types: IE, Firefox, Chrome, Safari, HtmlUnit."); + } + + // move browser windows to specific position. It's useful for + // debugging... + final int browserInitPositionX = properties.getBrowserInitPositionX(); + final int browserInitPositionY = properties.getBrowserInitPositionY(); + if (browserInitPositionX != 0 || browserInitPositionY != 0) { + wd.manage().window().setSize(new Dimension(1280, 1024)); + wd.manage().window().setPosition(new Point(browserInitPositionX, browserInitPositionY)); + } + } + + return wd; + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public ExtWebDriver createNewSession(Map options, WebDriver wd) { + DefaultExtWebDriver selenium = new DefaultExtWebDriver(); + selenium.setWrappedDriver(wd); + + // Get client properties file + ClientProperties properties = new ClientProperties(options.get("client")); + + // Set client properties (specific to our factory/implementation) + selenium.setClientProperties(properties); + + // Set timeout value + selenium.setMaxRequestTimeout(properties.getMaxRequestTimeoutString()); + + // Highlighting + selenium.setHighlightColors(properties.getHighlightColorMap()); + selenium.setIsHighlight(properties.isHighlight()); + + return selenium; + } + + /* + * (non-Javadoc) + * + * @see org.finra.jtaf.ewd.session.SessionFactory + */ + @Override + public Map createDefaultOptions() { + HashMap ret = new HashMap(); + // Add any default options needed here (like path to default properties) + + ret.put("client", "client.properties"); + + return ret; + } + + /** + * + * @param ffp + * for use in setting the firefox profile for the tests to use + * when running firefox + */ + private static void addPreferences(FirefoxProfile ffp) { + ffp.setPreference("capability.policy.default.HTMLDocument.readyState", "allAccess"); + ffp.setPreference("capability.policy.default.HTMLDocument.compatMode", "allAccess"); + ffp.setPreference("capability.policy.default.Document.compatMode", "allAccess"); + ffp.setPreference("capability.policy.default.Location.href", "allAccess"); + ffp.setPreference("capability.policy.default.Window.pageXOffset", "allAccess"); + ffp.setPreference("capability.policy.default.Window.pageYOffset", "allAccess"); + ffp.setPreference("capability.policy.default.Window.frameElement", "allAccess"); + ffp.setPreference("capability.policy.default.Window.frameElement.get", "allAccess"); + ffp.setPreference("capability.policy.default.Window.QueryInterface", "allAccess"); + ffp.setPreference("capability.policy.default.Window.mozInnerScreenY", "allAccess"); + ffp.setPreference("capability.policy.default.Window.mozInnerScreenX", "allAccess"); + } + + /** + * + * @param ffp + * the firefox profile you are using + * @param propertiesFile + * the properties you want to add to the profile + */ + private static void addPreferences(FirefoxProfile ffp, String propertiesFile) { + Properties firefoxProfile = new Properties(); + + try(FileInputStream fis = new FileInputStream(propertiesFile)) { + firefoxProfile.load(fis); + } catch (Throwable th) { + throw new RuntimeException("Could not load firefox profile", th); + } + + for (Object o : firefoxProfile.keySet()) { + String key = (String) o; + String getVal = null; + if (key.endsWith(".type")) { + getVal = key.substring(0, key.lastIndexOf(".")); + } + + if (getVal != null) { + String type = firefoxProfile.getProperty(key); + String value = firefoxProfile.getProperty(getVal + ".value"); + + if (value.contains("${PROJECT_PATH}")) { + String projectPath = (new File("")).getAbsolutePath(); + value = projectPath + value.replaceAll("\\$\\{PROJECT_PATH\\}", ""); + } + + if (type.equalsIgnoreCase("BOOLEAN")) { + ffp.setPreference(getVal, Boolean.parseBoolean(value)); + } else if (type.equalsIgnoreCase("STRING")) { + ffp.setPreference(getVal, value); + } else if (type.equalsIgnoreCase("INTEGER") || type.equalsIgnoreCase("INT")) { + ffp.setPreference(getVal, Integer.parseInt(value)); + } + } + } + } + + /** + * + * @param ffp + * the firefox profile specified + * @param extensions + * extensions desired to be added + * @throws IOException + */ + private static void addExtensionsToFirefoxProfile(FirefoxProfile ffp, List extensions) + throws IOException { + for (String s : extensions) { + ffp.addExtension(new File(s)); + } + } + + /** + * + * @param filePath + * the binary path location of the firefox app (where it's + * installed) + * @return + */ + private static FirefoxBinary getFFBinary(String filePath) { + File[] possibleLocations = { new File(filePath != null ? filePath : ""), + new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe"), + new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"), }; + + File ffbinary = null; + + for (File curr : possibleLocations) { + if (curr.exists()) { + ffbinary = curr; + break; + } + } + + if (ffbinary == null) { + throw new RuntimeException( + "Unable to find firefox binary, please ensure that firefox is installed " + + "on your system. If it is then please determine the path to your firefox.exe and set it as " + + "binaryPath="); + } else { + return new FirefoxBinary(ffbinary); + } + } + + /** + * This method cleans out folders where the WebDriver temp information is + * stored. + * + * @param properties + * client properties specified + */ + private static void removeWebDriverTempOldFolders(ClientProperties properties) { + String tempFolder = System.getProperty("java.io.tmpdir"); + + int numberOfDaysToKeepTempFolders = properties.getNumberOfDaysToKeepTempFolders(); + if (numberOfDaysToKeepTempFolders < 0) { + numberOfDaysToKeepTempFolders = 7; + } + + List tempFolderNameContainsList = new ArrayList(); + tempFolderNameContainsList.add("anonymous"); + tempFolderNameContainsList.add("scoped_dir"); + tempFolderNameContainsList.add("webdriver-ie"); + + // add parameters from config file + String tempFolderNameContainsListFromProp = properties.getTempFolderNameContainsList(); + if (tempFolderNameContainsListFromProp != null) { + String[] tempFolderNameContainsListFromPropSpit = tempFolderNameContainsListFromProp + .split(","); + for (String name : tempFolderNameContainsListFromPropSpit) { + tempFolderNameContainsList.add(name); + } + } + + removeFolders(tempFolder, tempFolderNameContainsList, numberOfDaysToKeepTempFolders); + } + + /** + * This method can be called to remove specific folders or set how long you + * want to keep the temp information. + * + * @param folder + * which temp folder you want to remove + * @param folderTemplates + * the templates of these temp folders + * @param numberOfDaysToKeepTempFolders + * how long you want to keep the temp information + */ + private final static void removeFolders(String folder, List folderTemplates, + int numberOfDaysToKeepTempFolders) { + long dateToRemoveFiledAfter = (new Date()).getTime() + - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); + + File tempFolder = new File(folder); + File[] folderChildren = tempFolder.listFiles(); + if(null == folderChildren) { + log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); + return; + } + + for (File currentFile : folderChildren) { + if (currentFile.isDirectory()) { + for (String folderTemplate : folderTemplates) { + if (currentFile.getName().contains(folderTemplate) + && (currentFile.lastModified() < dateToRemoveFiledAfter)) { + try { + currentFile.delete(); + FileUtils.deleteDirectory(currentFile); + log.debug("Folder '" + currentFile.getName() + "' deleted..."); + } catch (Exception e) { + log.fatal("Error deleting folder '" + currentFile.getName() + "'"); + } + } + } + } + } + } +}