
com.github.becausetesting.cucumber.selenium.RemoteWebDriverEx Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons Show documentation
Show all versions of commons Show documentation
A common libraries used for testing framework.
package com.github.becausetesting.cucumber.selenium;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Beta;
import org.openqa.selenium.By;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.Platform;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Keyboard;
import org.openqa.selenium.interactions.Mouse;
import org.openqa.selenium.logging.LocalLogs;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingHandler;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.logging.Logs;
import org.openqa.selenium.logging.NeedsLocalLogs;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.DriverCommand;
import org.openqa.selenium.remote.ErrorHandler;
import org.openqa.selenium.remote.ExecuteMethod;
import org.openqa.selenium.remote.FileDetector;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.JsonToBeanConverter;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteExecuteMethod;
import org.openqa.selenium.remote.RemoteKeyboard;
import org.openqa.selenium.remote.RemoteLogs;
import org.openqa.selenium.remote.RemoteMouse;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.SessionNotFoundException;
import org.openqa.selenium.remote.UnreachableBrowserException;
import org.openqa.selenium.remote.UselessFileDetector;
import org.openqa.selenium.remote.internal.JsonToWebElementConverter;
import org.openqa.selenium.remote.internal.WebElementToJsonConverter;
import org.openqa.selenium.security.Credentials;
import org.openqa.selenium.security.UserAndPassword;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@SuppressWarnings("deprecation")
public class RemoteWebDriverEx extends RemoteWebDriver {
// TODO(dawagner): This static logger should be unified with the
// per-instance localLogs
/*
*
* 2016/03/07 Alter: Add the use exising session for testing
*/
private static final Logger logger = Logger.getLogger(RemoteWebDriverEx.class.getName());
private Level level = Level.FINE;
private ErrorHandler errorHandler = new ErrorHandler();
private CommandExecutor executor;
private Capabilities capabilities;
private SessionId sessionId;
private FileDetector fileDetector = new UselessFileDetector();
private ExecuteMethod executeMethod;
private JsonToWebElementConverter converter;
private RemoteKeyboard keyboard;
private RemoteMouse mouse;
private Logs remoteLogs;
private LocalLogs localLogs;
private int w3cComplianceLevel = 0;
private boolean useSession=false;
public void useSeleniumSession(boolean useSession){
this.useSession=useSession;
}
// For default testing to switch to firefox
protected RemoteWebDriverEx() {
this((URL) null, DesiredCapabilities.firefox());
}
protected RemoteWebDriverEx(boolean useSessionId) {
this((URL) null, DesiredCapabilities.firefox(), useSessionId);
}
public RemoteWebDriverEx(CommandExecutor executor, Capabilities desiredCapabilities,
Capabilities requiredCapabilities, boolean useSessionId) {
this.executor = executor;
//recover scenario script
Thread.currentThread();
Thread.setDefaultUncaughtExceptionHandler(new RecoveryScenario());
init(desiredCapabilities, requiredCapabilities);
if (executor instanceof NeedsLocalLogs) {
((NeedsLocalLogs) executor).setLocalLogs(localLogs);
}
if (useSessionId) {
getExistingSessionId();
}
if (this.sessionId == null) {
try {
startClient();
} catch (RuntimeException e) {
try {
stopClient();
} catch (Exception ignored) {
// Ignore the clean-up exception. We'll propagate the
// original failure.
}
throw e;
}
try {
startSession(desiredCapabilities, requiredCapabilities);
} catch (RuntimeException e) {
try {
quit();
} catch (Exception ignored) {
// Ignore the clean-up exception. We'll propagate the
// original
// failure.
}
throw e;
}
}
}
public RemoteWebDriverEx(CommandExecutor executor, Capabilities desiredCapabilities) {
this(executor, desiredCapabilities, null, false);
}
public RemoteWebDriverEx(Capabilities desiredCapabilities) {
this((URL) null, desiredCapabilities);
}
public RemoteWebDriverEx(Capabilities desiredCapabilities, boolean useSessionId) {
this((URL) null, desiredCapabilities, useSessionId);
}
public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, requiredCapabilities, false);
}
public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities, Capabilities requiredCapabilities,
boolean useSessionId) {
this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, requiredCapabilities, useSessionId);
}
public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities) {
this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, null, true);
}
public RemoteWebDriverEx(URL remoteAddress, Capabilities desiredCapabilities, boolean useSessionId) {
this(new HttpCommandExecutor(remoteAddress), desiredCapabilities, null, useSessionId);
}
public int getW3CStandardComplianceLevel() {
return w3cComplianceLevel;
}
private void init(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
logger.addHandler(LoggingHandler.getInstance());
converter = new JsonToWebElementConverter(this);
executeMethod = new RemoteExecuteMethod(this);
keyboard = new RemoteKeyboard(executeMethod);
mouse = new RemoteMouse(executeMethod);
ImmutableSet.Builder builder = new ImmutableSet.Builder();
boolean isProfilingEnabled = desiredCapabilities != null
&& desiredCapabilities.is(CapabilityType.ENABLE_PROFILING_CAPABILITY);
if (requiredCapabilities != null
&& requiredCapabilities.getCapability(CapabilityType.ENABLE_PROFILING_CAPABILITY) != null) {
isProfilingEnabled = requiredCapabilities.is(CapabilityType.ENABLE_PROFILING_CAPABILITY);
}
if (isProfilingEnabled) {
builder.add(LogType.PROFILER);
}
LoggingPreferences mergedLoggingPrefs = new LoggingPreferences();
if (desiredCapabilities != null) {
mergedLoggingPrefs.addPreferences(
(LoggingPreferences) desiredCapabilities.getCapability(CapabilityType.LOGGING_PREFS));
}
if (requiredCapabilities != null) {
mergedLoggingPrefs.addPreferences(
(LoggingPreferences) requiredCapabilities.getCapability(CapabilityType.LOGGING_PREFS));
}
if ((mergedLoggingPrefs.getEnabledLogTypes().contains(LogType.CLIENT)
&& mergedLoggingPrefs.getLevel(LogType.CLIENT) != Level.OFF)
|| !mergedLoggingPrefs.getEnabledLogTypes().contains(LogType.CLIENT)) {
builder.add(LogType.CLIENT);
}
Set logTypesToInclude = builder.build();
LocalLogs performanceLogger = LocalLogs.getStoringLoggerInstance(logTypesToInclude);
LocalLogs clientLogs = LocalLogs.getHandlerBasedLoggerInstance(LoggingHandler.getInstance(), logTypesToInclude);
localLogs = LocalLogs.getCombinedLogsHolder(clientLogs, performanceLogger);
remoteLogs = new RemoteLogs(executeMethod, localLogs);
}
/**
* Set the file detector to be used when sending keyboard input. By default,
* this is set to a file detector that does nothing.
*
* @param detector
* The detector to use. Must not be null.
* @see FileDetector
* @see LocalFileDetector
* @see UselessFileDetector
*/
public void setFileDetector(FileDetector detector) {
if (detector == null) {
throw new WebDriverException("You may not set a file detector that is null");
}
fileDetector = detector;
}
public SessionId getSessionId() {
return sessionId;
}
public Capabilities getCapabilities() {
return capabilities;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void getExistingSessionId() {
Response response = execute(DriverCommand.GET_ALL_SESSIONS);
ArrayList sessionsList = (ArrayList) response.getValue();
int size = sessionsList.size();
if (size > 0) {
// Here it will get the first sesion container ,if you have multiply
// sesssion ,it always get the top sessions in the session
// containers
Map rawCapabilities = (Map) sessionsList.get(sessionsList.size() - 1);
DesiredCapabilities returnedCapabilities = new DesiredCapabilities();
for (Map.Entry entry : rawCapabilities.entrySet()) {
// Handle the platform later
if (CapabilityType.PLATFORM.equals(entry.getKey())) {
continue;
}
returnedCapabilities.setCapability(entry.getKey(), entry.getValue());
}
String platformString = (String) rawCapabilities.get(CapabilityType.PLATFORM);
Platform platform;
try {
if (platformString == null || "".equals(platformString)) {
platform = Platform.ANY;
} else {
platform = Platform.valueOf(platformString);
}
} catch (IllegalArgumentException e) {
// The server probably responded with a name matching the
// os.name
// system property. Try to recover and parse this.
platform = Platform.extractFromSysProperty(platformString);
}
returnedCapabilities.setPlatform(platform);
capabilities = returnedCapabilities;
String oldsessionid = (String) rawCapabilities.get("id");
sessionId = new SessionId(oldsessionid);
logger.info("Found Existing sessionId: " + oldsessionid
+ " from session container,and emulate all the operations in this session.");
if (response.getStatus() == null) {
w3cComplianceLevel = 1;
}
}
}
protected void setSessionId(String opaqueKey) {
sessionId = new SessionId(opaqueKey);
}
protected void startSession(Capabilities desiredCapabilities) {
startSession(desiredCapabilities, null);
}
@SuppressWarnings({ "unchecked" })
protected void startSession(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {
ImmutableMap.Builder paramBuilder = new ImmutableMap.Builder();
paramBuilder.put("desiredCapabilities", desiredCapabilities);
if (requiredCapabilities != null) {
paramBuilder.put("requiredCapabilities", requiredCapabilities);
}
Map parameters = paramBuilder.build();
Response response = execute(DriverCommand.NEW_SESSION, parameters);
Map rawCapabilities = (Map) response.getValue();
DesiredCapabilities returnedCapabilities = new DesiredCapabilities();
for (Map.Entry entry : rawCapabilities.entrySet()) {
// Handle the platform later
if (CapabilityType.PLATFORM.equals(entry.getKey())) {
continue;
}
returnedCapabilities.setCapability(entry.getKey(), entry.getValue());
}
String platformString = (String) rawCapabilities.get(CapabilityType.PLATFORM);
Platform platform;
try {
if (platformString == null || "".equals(platformString)) {
platform = Platform.ANY;
} else {
platform = Platform.valueOf(platformString);
}
} catch (IllegalArgumentException e) {
// The server probably responded with a name matching the os.name
// system property. Try to recover and parse this.
platform = Platform.extractFromSysProperty(platformString);
}
returnedCapabilities.setPlatform(platform);
capabilities = returnedCapabilities;
sessionId = new SessionId(response.getSessionId());
if (response.getStatus() == null) {
w3cComplianceLevel = 1;
}
}
public Object executeScript(String script, Object... args) {
if (!capabilities.isJavascriptEnabled()) {
throw new UnsupportedOperationException(
"You must be using an underlying instance of WebDriver that supports executing javascript");
}
// Escape the quote marks
script = script.replaceAll("\"", "\\\"");
Iterable
© 2015 - 2025 Weber Informatics LLC | Privacy Policy