
com.automationrockstars.design.gir.webdriver.DriverFactory Maven / Gradle / Ivy
The newest version!
/*******************************************************************************
* Copyright (c) 2015, 2016 Automation RockStars Ltd.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Contributors:
* Automation RockStars - initial API and implementation
*******************************************************************************/
package com.automationrockstars.design.gir.webdriver;
import com.automationrockstars.base.ConfigLoader;
import com.automationrockstars.bmo.AllureStoryReporter;
import com.automationrockstars.bmo.GenericAllureStoryReporter;
import com.automationrockstars.design.gir.webdriver.plugin.UiDriverPluginService;
import com.automationrockstars.design.gir.webdriver.plugin.UiObjectActionPluginService;
import com.automationrockstars.design.gir.webdriver.plugin.UiObjectFindPluginService;
import com.automationrockstars.design.gir.webdriver.plugin.UiObjectInfoPluginService;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.*;
import org.apache.commons.collections.list.UnmodifiableList;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.openqa.selenium.*;
import org.openqa.selenium.Platform;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.WrapsDriver;
import org.openqa.selenium.remote.BrowserType;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import static com.automationrockstars.base.ConfigLoader.config;
import static com.automationrockstars.design.gir.webdriver.plugin.UiObjectFindPluginService.findPlugins;
public class DriverFactory {
public static final String WEBDRIVER_SESSION = "webdriver.session";
public static final String DEFAULT_AUTO_DOWNLOAD = "application/octet-stream,application/x-gzip,application/gzip,application/zip,application/pdf,application/vnd.cups-pdf";
public static final ConcurrentMap wdsInstances = Maps.newConcurrentMap();
private static final ThreadLocal instances = new InheritableThreadLocal<>();
private static final List activeDrivers = Lists.newCopyOnWriteArrayList();
;
private static final Logger log = LoggerFactory.getLogger(DriverFactory.class);
private static final ThreadLocal url = new ThreadLocal<>();
private static final String GRID_URL = ConfigLoader.config().getString("grid.url", null);
private static final String MATRIX_PROP = "webdriver.matrix.browsers";
private static final String BROWSER_PROP = "webdriver.browser";
private static final String DEF_BROWSER_PROP = "webdriver.browser.default";
private static final String DEF_BROWSER = "phantomjs";
private static Capabilities capabilities;
private static WebDriver DISPLAY_BROWSER = null;
private static PeekingIterator matrix = null;
private static boolean pluginInitialized = false;
private static ThreadLocal providers = new ThreadLocal<>();
private static final ThreadLocal browser = new InheritableThreadLocal() {
protected String initialValue() {
String browser = DEF_BROWSER;
if (!isWds()) {
if (browserQueue().hasNext()) {
browser = browserQueue().next();
} else {
if (ConfigLoader.config().containsKey("webdriver.browser")) {
browser = ConfigLoader.config().getString("webdriver.browser");
}
}
}
return browser;
}
};
private static final WebDriver instance() {
return instances.get();
}
public static void url(String url) {
DriverFactory.url.set(url);
}
public static String url() {
return url.get();
}
public static final WebDriver getUnwrappedDriver() {
WebDriver toUnwrap = null;
if (isWds()) {
toUnwrap = wdsInstance();
} else {
if (instance() == null) {
getDriver();
}
toUnwrap = instance();
}
return unwrap(toUnwrap);
}
public static WebDriver unwrap(WebDriver wrapped) {
if (WrapsDriver.class.isAssignableFrom(wrapped.getClass())) {
return unwrap(((WrapsDriver) wrapped).getWrappedDriver());
} else return wrapped;
}
public static boolean canScreenshot() {
return instance() != null || providers.get() != null;
}
public static byte[] getScreenshot() {
return ((RemoteWebDriver) getUnwrappedDriver()).getScreenshotAs(OutputType.BYTES);
}
public static String getScreenshotAsBase64() {
return ((RemoteWebDriver) getUnwrappedDriver()).getScreenshotAs(OutputType.BASE64);
}
public static void displayScreenshotFile() {
try {
File screenshot = getScreenshotFile();
if (FileUtils.waitFor(screenshot, 1)) {
log.info("Screenshot file available {}", screenshot.getAbsolutePath());
Desktop.getDesktop().open(screenshot);
} else {
log.warn("File {} not created", screenshot);
}
} catch (IOException e) {
log.error("Cannot display screenshot due to", e);
}
}
public static void displayScreenshotBrowser() {
if (DISPLAY_BROWSER == null) {
DISPLAY_BROWSER = new ChromeDriver();
}
if (DISPLAY_BROWSER != null) {
DISPLAY_BROWSER.get("data:image/gif;base64," + getScreenshotAsBase64());
}
}
public static File getScreenshotFile() {
if (TakesScreenshot.class.isAssignableFrom(getUnwrappedDriver().getClass())) {
return ((TakesScreenshot) getUnwrappedDriver()).getScreenshotAs(OutputType.FILE);
} else return new File(UUID.randomUUID().toString());
}
public static void setCapabilities(Capabilities capabilities) {
DriverFactory.capabilities = capabilities;
}
public static Actions actions() {
return new Actions(getUnwrappedDriver());
}
private static final boolean isGridAvailable(String gridUrl) {
boolean result = true;
CloseableHttpResponse gridResponse;
try {
CloseableHttpClient cl = HttpClients.createDefault();
gridResponse = cl.execute(new HttpGet(new URI(gridUrl)));
if (gridResponse.getStatusLine().getStatusCode() == 404) {
log.warn("Response from contacting grid {}", IOUtils.toString(gridResponse.getEntity().getContent()));
result = false;
}
gridResponse.close();
cl.close();
} catch (Throwable e) {
result = false;
log.error("Selenium grid not available due to {}", e.getMessage());
}
return result;
}
private static boolean checkGridExtras(String gridUrl, RemoteWebDriver driver) {
String gridExtras = GridUtils.getNodeExtras(gridUrl, driver);
if (gridExtras == null) {
log.info("No grid extras foud");
return false;
} else {
log.info("Grid extras available at {}", gridExtras);
return true;
}
}
private static synchronized Iterator browserQueue() {
while (matrix == null || !matrix.hasNext() || matrix.peek() == null) {
matrix = browserMatrix();
}
if (!pluginInitialized) {
UiObjectFindPluginService.findPlugins();
UiObjectActionPluginService.actionPlugins();
UiObjectInfoPluginService.infoPlugins();
UiDriverPluginService.driverPlugins();
pluginInitialized = true;
}
return matrix;
}
public static synchronized PeekingIterator browserMatrix() {
PeekingIterator result;
if (ConfigLoader.config().containsKey(MATRIX_PROP)) {
result = Iterators.peekingIterator(Iterators.forArray(ConfigLoader.config().getStringArray(MATRIX_PROP)));
} else {
String bName = ConfigLoader.config().getString(BROWSER_PROP, ConfigLoader.config().getString(DEF_BROWSER_PROP, DEF_BROWSER));
if (bName.equalsIgnoreCase("ie")) {
bName = BrowserType.IE;
log.info("Using {} for browser", bName);
}
result = Iterators.peekingIterator(Iterators.cycle(bName));
}
return result;
}
public static void setBrowser(String browser) {
DriverFactory.browser.set(browser);
}
private static String storyName() {
String story = null;
try {
if (!Strings.isNullOrEmpty(GenericAllureStoryReporter.storyName())) {
story = GenericAllureStoryReporter.storyName();
} else if (!Strings.isNullOrEmpty(AllureStoryReporter.storyName())) {
story = AllureStoryReporter.storyName();
}
} catch (Throwable t) {
}
return story;
}
private static String scenarioName() {
String scenario = null;
try {
if (!Strings.isNullOrEmpty(GenericAllureStoryReporter.storyName())) {
scenario = GenericAllureStoryReporter.scenarioName();
} else if (!Strings.isNullOrEmpty(AllureStoryReporter.storyName())) {
scenario = AllureStoryReporter.scenarioName();
}
} catch (Throwable t) {
}
return scenario;
}
private static synchronized void enableGridExtras(RemoteWebDriver driver) {
if (checkGridExtras(GRID_URL, driver)) {
String videoLink = String.format("%s/download_video/%s.mp4", GridUtils.getNodeExtras(GRID_URL, driver), driver.getSessionId().toString()).replace("//download","/download");
ConfigLoader.config().addProperty("webdriver.video", videoLink);
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy