How to use Interface WebDriverListener class of org.openqa.selenium.support.events package

Best Selenium code snippet using org.openqa.selenium.support.events.Interface WebDriverListener

Source:ActionsLibrary.java Github

copy

Full Screen

1package com.web.automation.accelerators;2import java.awt.AWTException;3import java.awt.Robot;4import java.awt.Toolkit;5import java.awt.datatransfer.Clipboard;6import java.awt.datatransfer.DataFlavor;7import java.awt.datatransfer.StringSelection;8import java.awt.datatransfer.UnsupportedFlavorException;9import java.awt.event.KeyEvent;10import java.io.BufferedReader;11import java.io.File;12import java.io.FileInputStream;13import java.io.FileNotFoundException;14import java.io.FileOutputStream;15import java.io.FileReader;16import java.io.FileWriter;17import java.io.IOException;18import java.io.InputStream;19import java.io.InputStreamReader;20import java.io.OutputStream;21import java.io.PrintWriter;22import java.io.StringWriter;23import java.net.HttpURLConnection;24import java.net.InetAddress;25import java.net.MalformedURLException;26import java.net.NetworkInterface;27import java.net.URL;28import java.text.DateFormat;29import java.text.ParseException;30import java.text.SimpleDateFormat;31import java.util.ArrayList;32import java.util.Calendar;33import java.util.Date;34import java.util.Enumeration;35import java.util.GregorianCalendar;36import java.util.HashMap;37import java.util.Iterator;38import java.util.List;39import java.util.Map;40import java.util.Set;41import java.util.TimeZone;42import java.util.concurrent.TimeUnit;43import java.util.logging.Level;44import java.util.regex.Matcher;45import java.util.regex.Pattern;46import org.apache.commons.io.FileUtils;47import org.apache.commons.io.IOUtils;48import org.apache.http.HttpHost;49import org.apache.http.HttpResponse;50import org.apache.http.client.ClientProtocolException;51import org.apache.http.client.CookieStore;52import org.apache.http.client.HttpClient;53import org.apache.http.client.methods.HttpGet;54import org.apache.http.client.params.ClientPNames;55import org.apache.http.client.params.CookiePolicy;56import org.apache.http.client.protocol.ClientContext;57import org.apache.http.cookie.ClientCookie;58import org.apache.http.impl.client.BasicCookieStore;59import org.apache.http.impl.client.DefaultHttpClient;60import org.apache.http.impl.cookie.BasicClientCookie2;61import org.apache.http.message.BasicHttpEntityEnclosingRequest;62import org.apache.http.protocol.BasicHttpContext;63import org.apache.http.protocol.HttpContext;64import org.joda.time.LocalDate;65import org.joda.time.Years;66import org.json.JSONException;67import org.json.JSONObject;68import org.openqa.selenium.Alert;69import org.openqa.selenium.By;70import org.openqa.selenium.Cookie;71import org.openqa.selenium.Dimension;72import org.openqa.selenium.ElementNotVisibleException;73import org.openqa.selenium.JavascriptExecutor;74import org.openqa.selenium.Keys;75import org.openqa.selenium.NoAlertPresentException;76import org.openqa.selenium.NoSuchElementException;77import org.openqa.selenium.OutputType;78import org.openqa.selenium.Platform;79import org.openqa.selenium.Point;80import org.openqa.selenium.Proxy;81import org.openqa.selenium.StaleElementReferenceException;82import org.openqa.selenium.TakesScreenshot;83import org.openqa.selenium.TimeoutException;84import org.openqa.selenium.UnhandledAlertException;85import org.openqa.selenium.WebDriver;86import org.openqa.selenium.WebDriverException;87import org.openqa.selenium.WebElement;88import org.openqa.selenium.chrome.ChromeDriver;89import org.openqa.selenium.chrome.ChromeOptions;90import org.openqa.selenium.edge.EdgeDriver;91import org.openqa.selenium.firefox.FirefoxDriver;92import org.openqa.selenium.firefox.FirefoxProfile;93import org.openqa.selenium.firefox.internal.ProfilesIni;94import org.openqa.selenium.html5.Location;95import org.openqa.selenium.ie.InternetExplorerDriver;96import org.openqa.selenium.interactions.Action;97import org.openqa.selenium.interactions.Actions;98import org.openqa.selenium.logging.LogEntries;99import org.openqa.selenium.logging.LogEntry;100import org.openqa.selenium.logging.LogType;101import org.openqa.selenium.logging.LoggingPreferences;102import org.openqa.selenium.opera.OperaOptions;103import org.openqa.selenium.phantomjs.PhantomJSDriver;104import org.openqa.selenium.phantomjs.PhantomJSDriverService;105import org.openqa.selenium.remote.Augmenter;106import org.openqa.selenium.remote.CapabilityType;107import org.openqa.selenium.remote.DesiredCapabilities;108import org.openqa.selenium.remote.HttpCommandExecutor;109import org.openqa.selenium.remote.RemoteWebDriver;110import org.openqa.selenium.remote.RemoteWebElement;111import org.openqa.selenium.remote.SessionNotFoundException;112import org.openqa.selenium.safari.SafariDriver;113import org.openqa.selenium.safari.SafariOptions;114import org.openqa.selenium.support.events.EventFiringWebDriver;115import org.openqa.selenium.support.ui.ExpectedConditions;116import org.openqa.selenium.support.ui.FluentWait;117import org.openqa.selenium.support.ui.Select;118import org.openqa.selenium.support.ui.WebDriverWait;119import org.testng.Assert;120import org.testng.SkipException;121import com.google.common.base.Optional;122import com.web.automation.bmp.BMP_Proxy_Controller;123import com.web.automation.listeners.MyListener;124import com.web.automation.listeners.WebDriverListener;125import com.web.automation.logs.CustomLogName;126import com.web.automation.logs.CustomLogs;127import com.web.automation.logs.ExtentLogs;128import com.web.automation.utilities.CaptureScreenShot;129import com.web.automation.utilities.CommonVariables;130import com.web.automation.utilities.ConfigManager;131import io.appium.java_client.AppiumDriver;132import io.appium.java_client.ios.IOSDriver;133import io.appium.java_client.remote.MobileCapabilityType;134import net.lightbody.bmp.proxy.jetty.html.Page;135public class ActionsLibrary extends MyListener {136 public static WebDriver wd;137 public static EventFiringWebDriver driver;138 private WebDriverListener eventListener;139 public static RemoteWebDriver rdriver;140 private AppiumDriver appiumDriver;141 private WebDriverWait wait;142 public static int driverStartfailureCount = 1;143 private DesiredCapabilities objCapabilities;144 private ChromeOptions chromeoptions;145 private OperaOptions operaOptions;146 private Set<String> arrKnownBrowserHwnd; // Stores windows handle when147 // launching a new browser148 public String hwndFirstWindow; // This will store handle of original window149 public String hwndMostRecentWindow; // This will store handle of most150 // recently known window151 public Boolean locationServiceEnabled;152 private Boolean doFullReset;153 private String chromeProfile;154 private String firefoxProfilePath;155 156 private String safariProfilePath;157 private LoggingPreferences prefs;158 private ExtentLogs extentLogs = new ExtentLogs();159 private FileWriter fw;160 private PrintWriter pw;161 private int CurrentMonthDays;162 private static String downloadedfilepath;163 private FirefoxProfile firefoxProfile;164 public static String gStrErrMsg = " ";165 166 @SuppressWarnings("static-access")167 public ActionsLibrary(WebDriver driver) {168 this.driver = (EventFiringWebDriver) driver;169 initPropertiesFile();170 this.locationServiceEnabled = Boolean171 .parseBoolean(ConfigManager.getProperties().getProperty("locationServiceEnabled").trim().toLowerCase());172 doFullReset = true;173 if (this.locationServiceEnabled) {174 this.chromeProfile = "browser-profile-location-boston";175 this.firefoxProfilePath = "Firefox_profile_For_Location_Simulate";176 this.safariProfilePath = "Safari_Shared_Location_Profile";177 }178 }179 /**180 * @author Cigniti181 * @description: setter for EventFiringWebDriver182 * @param driver183 */184 public void setDriver(EventFiringWebDriver driver) {185 this.driver = driver;186 }187 /**188 * @author Cigniti189 */190 public ActionsLibrary() {191 initPropertiesFile();192 }193 /**194 * @author Cigniti195 * @description: Intialize config properties196 */197 private void initPropertiesFile() {198 try {199 if (!ConfigManager.ArePropertiesSet.get()) {200 ConfigManager.getProperties();201 ConfigManager.UpdateProperties();202 }203 } catch (Exception e) {204 e.getLocalizedMessage();205 }206 }207 /**208 * @author Cigniti209 * @description : Webdriver Wait For Page with time210 * @param time211 */212 @SuppressWarnings("static-access")213 public void WebdriverWaitForPage() {214 this.driver.manage().timeouts().implicitlyWait(215 Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut")), TimeUnit.SECONDS);216 }217 /**218 * @author Cigniti219 * @description : start webdriver with an instance of browser type.220 * @param browserType221 * @return222 */223 @SuppressWarnings("static-access")224 public WebDriver instantiateDriver(String browserType) {225 String chromeprofilepath = null;226 Process process = null;227 try {228 String osname = System.getProperty("os.name");229 String DriverPath = "";230 tearDown();231 System.out.println("************ Starting the driver: " + browserType + " ***************");232 downloadedfilepath = System.getProperty("user.dir").replace("\\", "/") + "/Tool/downloadedFiles";233 switch (browserType.trim().toLowerCase()) {234 case "linux-chrome":235 if (ConfigManager.getProperties().getProperty("KillDriverBinaries").toLowerCase().trim()236 .contains("yes")) {237 KillWindowProcess("chromedriver.exe");238 }239 chromeoptions = new ChromeOptions();240 chromeoptions.addArguments("test-type");241 chromeoptions.addArguments("disable-session-crashed-bubble");242 chromeoptions.addArguments("disable-popup-blocking");243 chromeoptions.addArguments("--lang=" + ConfigManager.getProperties().getProperty("lacaleLang"));244 objCapabilities = new DesiredCapabilities();245 objCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeoptions);246 objCapabilities.setCapability("platform", Platform.LINUX);247 objCapabilities.setCapability("browserName", "chrome");248 objCapabilities.setCapability("takesScreenshot", true);249 objCapabilities.setCapability("handlesAlerts", true);250 objCapabilities.setCapability("browserTimeout", 9000000);251 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));252 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));253 this.setBrowserProxy();254 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {255 rdriver = null;256 rdriver = new RemoteWebDriver(new URL(257 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),258 objCapabilities);259 driver = new EventFiringWebDriver(rdriver);260 eventListener = null;261 eventListener = new WebDriverListener(driver);262 driver.register(eventListener);263 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()264 .contains("true")) {265 rdriver = null;266 rdriver = new RemoteWebDriver(new URL(267 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),268 objCapabilities);269 driver = new EventFiringWebDriver(rdriver);270 eventListener = null;271 eventListener = new WebDriverListener(driver);272 driver.register(eventListener);273 } else {274 DriverPath = System.getProperty("user.dir").replace("\\", "/")275 + "/Tool/chromedrivers/linux/chromedriver.exe";276 System.setProperty("webdriver.chrome.driver", DriverPath);277 this.wd = null;278 this.wd = new ChromeDriver(objCapabilities);279 this.driver = new EventFiringWebDriver(wd);280 eventListener = null;281 eventListener = new WebDriverListener(this.driver);282 this.driver.register(eventListener);283 }284 this.driver.manage().window().maximize();285 this.driver.getWrappedDriver().manage().deleteAllCookies();286 suppressCredential();287 break;288 case "mac-chrome":289 if (ConfigManager.getProperties().getProperty("KillDriverBinaries").toLowerCase().trim()290 .contains("yes")) {291 KillWindowProcess("chromedriver.exe");292 }293 LoggingPreferences prefs1 = new LoggingPreferences();294 prefs1.enable(LogType.BROWSER, Level.ALL);295 setDownloadPathForFile(downloadedfilepath);296 chromeoptions = new ChromeOptions();297 chromeoptions.addArguments("test-type");298 chromeoptions.addArguments("disable-session-crashed-bubble");299 chromeoptions.addArguments("disable-popup-blocking");300 chromeoptions.addArguments("--lang=" + ConfigManager.getProperties().getProperty("lacaleLang"));301 objCapabilities = new DesiredCapabilities();302 objCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeoptions);303 objCapabilities.setCapability(CapabilityType.LOGGING_PREFS, prefs1);304 objCapabilities.setCapability("platform", CommonVariables.PlatformName.get().toUpperCase());305 objCapabilities.setCapability("browserName", "chrome");306 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));307 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));308 this.setBrowserProxy();309 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {310 rdriver = null;311 rdriver = new RemoteWebDriver(new URL(312 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),313 objCapabilities);314 driver = new EventFiringWebDriver(rdriver);315 eventListener = null;316 eventListener = new WebDriverListener(driver);317 driver.register(eventListener);318 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()319 .contains("true")) {320 rdriver = null;321 rdriver = new RemoteWebDriver(new URL(322 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),323 objCapabilities);324 driver = new EventFiringWebDriver(rdriver);325 eventListener = null;326 eventListener = new WebDriverListener(driver);327 driver.register(eventListener);328 } else {329 DriverPath = System.getProperty("user.dir").replace("\\", "/")330 + "/Tool/chromedrivers/mac/chromedriver";331 System.setProperty("webdriver.chrome.driver", DriverPath);332 this.wd = null;333 this.wd = new ChromeDriver(objCapabilities);334 this.driver = new EventFiringWebDriver(wd);335 eventListener = null;336 eventListener = new WebDriverListener(this.driver);337 this.driver.register(eventListener);338 }339 this.driver.manage().window().maximize();340 driver.getWrappedDriver().manage().deleteAllCookies();341 suppressCredential();342 break;343 case "windows-chrome":344 if (ConfigManager.getProperties().getProperty("KillDriverBinaries").toLowerCase().trim()345 .contains("yes")) {346 KillWindowProcess("chromedriver.exe");347 }348 chromeoptions = new ChromeOptions();349 chromeoptions.addArguments("test-type");350 chromeoptions.addArguments("disable-session-crashed-bubble");351 chromeoptions.addArguments("disable-popup-blocking");352 chromeoptions.addArguments("--lang=" + ConfigManager.getProperties().getProperty("lacaleLang"));353 if (locationServiceEnabled != null) {354 if (!locationServiceEnabled) {355 Map<String, Object> prefs = new HashMap<String, Object>();356 prefs.put("profile.default_content_settings.geolocation", 2);357 chromeoptions.setExperimentalOption("prefs", prefs);358 } else if (locationServiceEnabled) {359 chromeprofilepath = System.getProperty("user.dir").replace("\\", "/")360 + "/Tool/BrowserProfiles/Chrome/" + chromeProfile;361 if (locationServiceEnabled && ConfigManager.getProperties().getProperty("seleniumGrid")362 .toLowerCase().trim().contains("true"))363 chromeprofilepath = System.getProperty("user.dir").replace("\\", "/")364 + "/Tool/BrowserProfiles/Chrome/" + chromeProfile;365 chromeoptions.addArguments("user-data-dir=" + chromeprofilepath);366 }367 }368 prefs = new LoggingPreferences();369 prefs.enable(LogType.BROWSER, Level.ALL);370 setDownloadPathForFile(downloadedfilepath);371 objCapabilities = new DesiredCapabilities();372 //objCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeoptions);373 //objCapabilities.setCapability(CapabilityType.LOGGING_PREFS, prefs);374 //objCapabilities.setCapability("platform", CommonVariables.PlatformName.get().toUpperCase().trim());375 objCapabilities.setCapability("browserName", "chrome");376 //objCapabilities.setCapability("version", CommonVariables.Version.get());377 //objCapabilities.setCapability("takesScreenshot", true);378 //objCapabilities.setCapability("handlesAlerts", true);379 //objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));380 //objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));381 this.setBrowserProxy();382 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {383 rdriver = null;384 rdriver = new RemoteWebDriver(new URL(385 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),386 objCapabilities);387 driver = new EventFiringWebDriver(rdriver);388 eventListener = null;389 eventListener = new WebDriverListener(driver);390 driver.register(eventListener);391 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()392 .contains("true")) {393 rdriver = null;394 rdriver = new RemoteWebDriver(new URL(395 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),396 objCapabilities);397 driver = new EventFiringWebDriver(rdriver);398 eventListener = null;399 eventListener = new WebDriverListener(driver);400 driver.register(eventListener);401 } else {402 DriverPath = System.getProperty("user.dir").replace("\\", "/")403 + "/Tool/chromedrivers/windows/chromedriver.exe";404 System.setProperty("webdriver.chrome.driver", DriverPath);405 this.wd = null;406 this.wd = new ChromeDriver(objCapabilities);407 this.driver = new EventFiringWebDriver(wd);408 eventListener = null;409 eventListener = new WebDriverListener(this.driver);410 this.driver.register(eventListener);411 412 /*rdriver = null;413 rdriver = new RemoteWebDriver(new URL(414 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),415 objCapabilities);416 driver = new EventFiringWebDriver(rdriver);417 eventListener = null;418 eventListener = new WebDriverListener(driver);419 driver.register(eventListener);*/420 421 }422 try423 {424 this.driver.manage().window().maximize();425 this.driver.getWrappedDriver().manage().deleteAllCookies();426 }427 catch(Exception e){e.printStackTrace();}428 if (locationServiceEnabled) {429 driver.navigate().to("chrome://settings/clearBrowserData");430 WebElement frame = driver431 .findElement(By.xpath("//iframe[@src='chrome://settings-frame/clearBrowserData']"));432 WebDriver frameDriver = driver.switchTo().frame(frame);433 Select dropDown = new Select(frameDriver.findElement(By.id("clear-browser-data-time-period")));434 dropDown.selectByIndex(4);435 WebElement elm = driver.findElement(By.id("delete-cookies-checkbox"));436 if (!elm.isSelected())437 elm.click();438 elm = driver.findElement(By.xpath("//button[@id='clear-browser-data-commit']"));439 elm.click();440 (new WebDriverWait(driver, 90)).until(ExpectedConditions441 .invisibilityOfElementLocated(By.xpath("//button[@id='clear-browser-data-commit']")));442 }443 /*444 * process = Runtime .getRuntime() .exec(445 * "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");446 * process.waitFor(); Thread.sleep(3000);447 */448 suppressCredential();449 break;450 case "mac-safari":451 SafariOptions safariOptions = new SafariOptions();452 objCapabilities = DesiredCapabilities.safari();453 objCapabilities.setCapability("takesScreenshot", true);454 objCapabilities.setCapability("handlesAlerts", true);455 objCapabilities.setCapability("cssSelectorsEnabled", true);456 objCapabilities.setCapability("databaseEnabled", true);457 objCapabilities.setCapability("platform", CommonVariables.PlatformName.get().toUpperCase());458 objCapabilities.setCapability("browserName", "safari");459 objCapabilities.setCapability("nativeEvents", true);460 objCapabilities.setCapability("acceptSslCerts", true);461 objCapabilities.setCapability("safariIgnoreFraudWarning", true);462 objCapabilities.setCapability("WarnAboutFraudulentWebsite", false);463 if (locationServiceEnabled != null) {464 objCapabilities.setCapability("locationContextEnabled", locationServiceEnabled);465 }466 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));467 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));468 if (locationServiceEnabled != null) {469 objCapabilities.setCapability("locationContextEnabled", locationServiceEnabled);470 }471 SafariOptions.fromCapabilities(objCapabilities);472 try {473 this.setBrowserProxy();474 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()475 .contains("true")) {476 rdriver = null;477 rdriver = new RemoteWebDriver(new URL(478 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),479 objCapabilities);480 driver = new EventFiringWebDriver(rdriver);481 eventListener = null;482 eventListener = new WebDriverListener(driver);483 driver.register(eventListener);484 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()485 .contains("true")) {486 rdriver = null;487 rdriver = new RemoteWebDriver(new URL(488 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),489 objCapabilities);490 driver = new EventFiringWebDriver(rdriver);491 eventListener = null;492 eventListener = new WebDriverListener(driver);493 driver.register(eventListener);494 } else {495 String SafariDriverPath = System.getProperty("user.dir").replace("\\", "/")496 + "/Tool/SafariDriver/SafariDriver.safariextz";497 System.setProperty("webdriver.safari.driver", SafariDriverPath);498 System.setProperty("webdriver.safari.noinstall", "true");499 this.wd = null;500 this.wd = new SafariDriver(safariOptions);501 this.driver = new EventFiringWebDriver(wd);502 eventListener = null;503 eventListener = new WebDriverListener(this.driver);504 this.driver.register(eventListener);505 }506 } catch (Exception e1) {507 if (e1.getClass().toString().contains("UnreachableBrowserException")508 || e1.getClass().toString().toLowerCase().contains("timeoutException")) {509 System.out.println("org.openqa.selenium.remote.UnreachableBrowserException occured");510 KillWindowProcess("Safari");511 try {512 Thread.sleep(22000);513 } catch (InterruptedException e2) {514 }515 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()516 .contains("true")) {517 rdriver = null;518 rdriver = new RemoteWebDriver(new URL("http://"519 + ConfigManager.getProperties().getProperty("SeleniumGridHubIP") + ":4444/wd/hub"),520 objCapabilities);521 this.driver = new EventFiringWebDriver(rdriver);522 eventListener = null;523 eventListener = new WebDriverListener(driver);524 this.driver.register(eventListener);525 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()526 .contains("true")) {527 rdriver = null;528 rdriver = new RemoteWebDriver(new URL("http://"529 + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),530 objCapabilities);531 this.driver = new EventFiringWebDriver(rdriver);532 eventListener = null;533 eventListener = new WebDriverListener(driver);534 this.driver.register(eventListener);535 } else {536 wd = null;537 wd = new SafariDriver(safariOptions);538 this.driver = new EventFiringWebDriver(wd);539 eventListener = null;540 eventListener = new WebDriverListener(driver);541 this.driver.register(eventListener);542 }543 } else {544 throw e1;545 }546 }547 try {548 Thread.sleep(5000);549 } catch (InterruptedException e2) {550 e2.printStackTrace();551 }552 this.driver.manage().window().maximize();553 suppressCredential();554 break;555 case "windows-internet_explorer":556 case "windows-internet explorer":557 case "windows-Internet Explorer":558 case "windows-ie":559 if (ConfigManager.getProperties().getProperty("KillDriverBinaries").toLowerCase().trim()560 .contains("yes")) {561 KillWindowProcess("IEDriverServer.exe");562 }563 objCapabilities = new DesiredCapabilities();564 objCapabilities = DesiredCapabilities.internetExplorer();565 objCapabilities.setCapability("platform", CommonVariables.PlatformName.get().toUpperCase());566 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));567 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));568 objCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,569 true);570 objCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);571 objCapabilities.setJavascriptEnabled(true);572 objCapabilities.setCapability("requireWindowFocus", true);573 objCapabilities.setCapability("enablePersistentHover", false);574 /*575 * objCapabilities.setCapability("ignoreZoomSetting", true);576 * objCapabilities.setCapability("nativeEvents",false);577 */578 objCapabilities.setCapability(InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR, true);579 objCapabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);580 this.setBrowserProxy();581 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {582 rdriver = null;583 rdriver = new RemoteWebDriver(new URL(584 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),585 objCapabilities);586 driver = new EventFiringWebDriver(rdriver);587 eventListener = null;588 eventListener = new WebDriverListener(driver);589 driver.register(eventListener);590 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()591 .contains("true")) {592 rdriver = null;593 rdriver = new RemoteWebDriver(new URL(594 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),595 objCapabilities);596 driver = new EventFiringWebDriver(rdriver);597 eventListener = null;598 eventListener = new WebDriverListener(driver);599 driver.register(eventListener);600 } else {601 File fileIE = new File("Tool/IEDrivers/IEDriverServer.exe");602 System.setProperty("webdriver.ie.driver", fileIE.getAbsolutePath());603 this.wd = null;604 this.wd = new InternetExplorerDriver(objCapabilities);605 this.driver = new EventFiringWebDriver(wd);606 eventListener = null;607 eventListener = new WebDriverListener(this.driver);608 this.driver.register(eventListener);609 }610 this.driver.manage().window().maximize();611 this.driver.manage().deleteAllCookies();612 /*613 * process = Runtime .getRuntime() .exec(614 * "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");615 * process.waitFor(); Thread.sleep(3000);616 */617 suppressCredential();618 // code to start windows batch file for windows focus during619 // execution620 try {621 if (System.getProperty("os.name").toLowerCase().contains("windows")) {622 String command = "cmd /c start " + " CALL " + "\"" + System.getProperty("user.dir")623 + "\\Drivers\\MakeDisplayActive.bat" + "\"";624 String command1 = "cmd /c start " + " CALL " + "\"" + System.getProperty("user.dir")625 + "\\Drivers\\EnableDisplayContentIESetting.bat" + "\"";626 String command2 = "cmd /c start " + " CALL " + "\"" + System.getProperty("user.dir")627 + "\\Drivers\\ReturnSessionToConsole.bat" + "\"";628 Runtime runtime = Runtime.getRuntime();629 @SuppressWarnings("unused")630 Process pr = runtime.exec(command);631 @SuppressWarnings("unused")632 Process pr1 = runtime.exec(command1);633 @SuppressWarnings("unused")634 Process pr2 = runtime.exec(command2);635 } else {636 System.out.println(637 "****** Batch file to make display active is not executed because this is not the windows platform. ******");638 }639 } catch (Exception e) {640 System.out.println("Unable to execute windows focus batch file due to exception :- "641 + e.getLocalizedMessage());642 }643 // code to handle security dialog in IE browser644 if (CommonVariables.CommonDriver.get().getPageSource().trim()645 .contains("There is a problem with this website")) {646 CommonVariables.CommonDriver.get().navigate()647 .to("javascript:document.getElementById('overridelink').click()");648 try {649 Thread.sleep(Long.parseLong("3000"));650 } catch (NumberFormatException e) {651 // TODO Auto-generated catch block652 e.printStackTrace();653 } catch (InterruptedException e) {654 // TODO Auto-generated catch block655 e.printStackTrace();656 }657 }658 break;659 case "windows-firefox":660 KillWindowProcess("geckodriver.exe");661 objCapabilities = new DesiredCapabilities();662 objCapabilities = DesiredCapabilities.firefox();663 objCapabilities.setCapability("marionette", false);664 objCapabilities.setCapability("platform", CommonVariables.PlatformName.get().toUpperCase());665 objCapabilities.setCapability("browserName", "firefox");666 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));667 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));668 if (this.locationServiceEnabled == true) {669 firefoxProfile = new FirefoxProfile(new File(System.getProperty("user.dir").replace("\\", "/")670 + "/Tool/BrowserProfiles/Firefox/" + firefoxProfilePath));671 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()672 .contains("true")) {673 firefoxProfile = new FirefoxProfile(new File(System.getProperty("user.dir").replace("\\", "/")674 + "/Tool/BrowserProfiles/Firefox/" + firefoxProfilePath));675 }676 firefoxProfile.setPreference("geo.enabled", true);677 firefoxProfile.setPreference("extensions.ui.locale.hidden", true);678 firefoxProfile.setPreference("intl.accept_languages",679 ConfigManager.getProperties().getProperty("lacaleLang"));680 firefoxProfile.setPreference("extensions.enabledAddons", "georelocate%40netzgewitter.com:0.2.3");681 firefoxProfile.setPreference("extensions.georelocate.latitude",682 ConfigManager.getProperties().getProperty("latitude"));683 firefoxProfile.setPreference("extensions.georelocate.longitude",684 ConfigManager.getProperties().getProperty("longitude"));685 firefoxProfile.setPreference("extensions.georelocate@netzgewitter.com.install-event-fired", true);686 firefoxProfile.setPreference("browser.cache.disk.enable", false);687 firefoxProfile.setPreference("browser.cache.memory.enable", false);688 firefoxProfile.setPreference("browser.cache.offline.enable", false);689 firefoxProfile.setPreference("network.http.use-cache", false);690 firefoxProfile.setPreference("browser.download.folderList", 2);691 firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);692 firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);693 firefoxProfile.setPreference("browser.download.dir", System.getProperty("user.dir") + "\\testdata");694 firefoxProfile.setPreference("browser.download.defaultFolder",695 System.getProperty("user.dir") + "\\testdata");696 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",697 "text/anytext ,text/plain,text/html,application/plain");698 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-excel");699 firefoxProfile.setPreference("pdfjs.disabled", true);700 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");701 firefoxProfile.setPreference("browser.download.manager.closeWhenDone", true);702 firefoxProfile.setPreference("browser.download.manager.useWindow", false);703 firefoxProfile.setPreference("browser.download.manager.alertOnExeOpen", false);704 ProfilesIni allProfiles = new ProfilesIni();705 allProfiles.getProfile("");706 } else {707 firefoxProfile = new FirefoxProfile();708 firefoxProfile.setPreference("geo.enabled", false);709 }710 firefoxProfile.setAcceptUntrustedCertificates(true);711 firefoxProfile.setEnableNativeEvents(true);712 firefoxProfile.setAssumeUntrustedCertificateIssuer(true);713 objCapabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);714 this.setBrowserProxy();715 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {716 rdriver = null;717 rdriver = new RemoteWebDriver(new URL(718 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),719 objCapabilities);720 driver = new EventFiringWebDriver(rdriver);721 eventListener = null;722 eventListener = new WebDriverListener(driver);723 driver.register(eventListener);724 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()725 .contains("true")) {726 rdriver = null;727 rdriver = new RemoteWebDriver(new URL(728 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),729 objCapabilities);730 driver = new EventFiringWebDriver(rdriver);731 eventListener = null;732 eventListener = new WebDriverListener(driver);733 driver.register(eventListener);734 } else {735 DriverPath = System.getProperty("user.dir").replace("\\", "/")736 + "/Tool/FirefoxDrivers/windows/geckodriver.exe";737 System.setProperty("webdriver.gecko.driver", DriverPath);738 this.wd = null;739 this.wd = new FirefoxDriver(objCapabilities);740 this.driver = new EventFiringWebDriver(wd);741 eventListener = null;742 eventListener = new WebDriverListener(this.driver);743 this.driver.register(eventListener);744 }745 this.driver.getWrappedDriver().manage().deleteAllCookies();746 /*747 * process = Runtime .getRuntime() .exec(748 * "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");749 * process.waitFor(); Thread.sleep(3000);750 */751 suppressCredential();752 break;753 case "mac-firefox":754 objCapabilities = new DesiredCapabilities();755 objCapabilities = DesiredCapabilities.firefox();756 objCapabilities.setCapability("marionette", false);757 objCapabilities.setCapability("platform", "MAC");758 objCapabilities.setCapability("browserName", "firefox");759 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));760 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));761 firefoxProfile = new FirefoxProfile();762 firefoxProfile.setPreference("geo.enabled", false);763 firefoxProfile.setPreference("extensions.ui.locale.hidden", true);764 firefoxProfile.setPreference("intl.accept_languages",765 ConfigManager.getProperties().getProperty("lacaleLang"));766 firefoxProfile.setAcceptUntrustedCertificates(true);767 firefoxProfile.setEnableNativeEvents(true);768 firefoxProfile.setPreference("browser.cache.disk.enable", false);769 firefoxProfile.setPreference("browser.cache.memory.enable", false);770 firefoxProfile.setPreference("browser.cache.offline.enable", false);771 firefoxProfile.setPreference("network.http.use-cache", false);772 firefoxProfile.setPreference("browser.download.folderList", 2);773 firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);774 firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);775 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",776 "text/anytext ,text/plain,text/html,application/plain");777 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-excel");778 firefoxProfile.setPreference("pdfjs.disabled", true);779 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");780 firefoxProfile.setPreference("browser.download.manager.closeWhenDone", true);781 firefoxProfile.setPreference("browser.download.manager.useWindow", false);782 firefoxProfile.setPreference("browser.download.manager.alertOnExeOpen", false);783 objCapabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);784 this.setBrowserProxy();785 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {786 rdriver = null;787 rdriver = new RemoteWebDriver(new URL(788 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),789 objCapabilities);790 driver = new EventFiringWebDriver(rdriver);791 eventListener = null;792 eventListener = new WebDriverListener(driver);793 driver.register(eventListener);794 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()795 .contains("true")) {796 rdriver = null;797 rdriver = new RemoteWebDriver(new URL(798 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),799 objCapabilities);800 driver = new EventFiringWebDriver(rdriver);801 eventListener = null;802 eventListener = new WebDriverListener(driver);803 driver.register(eventListener);804 } else {805 DriverPath = System.getProperty("user.dir").replace("\\", "/")806 + "/Tool/FirefoxDrivers/mac/geckodriver";807 System.setProperty("webdriver.gecko.driver", DriverPath);808 this.wd = null;809 this.wd = new FirefoxDriver(objCapabilities);810 this.driver = new EventFiringWebDriver(wd);811 eventListener = null;812 eventListener = new WebDriverListener(this.driver);813 this.driver.register(eventListener);814 }815 driver.getWrappedDriver().manage().deleteAllCookies();816 suppressCredential();817 break;818 case "linux-firefox":819 objCapabilities = new DesiredCapabilities();820 objCapabilities = DesiredCapabilities.firefox();821 objCapabilities.setCapability("marionette", false);822 objCapabilities.setCapability("platform", "LINUX");823 objCapabilities.setCapability("browserName", "firefox");824 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));825 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));826 firefoxProfile = new FirefoxProfile();827 firefoxProfile.setPreference("geo.enabled", false);828 firefoxProfile.setAcceptUntrustedCertificates(true);829 firefoxProfile.setEnableNativeEvents(true);830 firefoxProfile.setPreference("extensions.ui.locale.hidden", true);831 firefoxProfile.setPreference("intl.accept_languages",832 ConfigManager.getProperties().getProperty("lacaleLang"));833 firefoxProfile.setPreference("browser.cache.disk.enable", false);834 firefoxProfile.setPreference("browser.cache.memory.enable", false);835 firefoxProfile.setPreference("browser.cache.offline.enable", false);836 firefoxProfile.setPreference("network.http.use-cache", false);837 firefoxProfile.setPreference("browser.download.folderList", 2);838 firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);839 firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);840 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",841 "text/anytext ,text/plain,text/html,application/plain");842 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/vnd.ms-excel");843 firefoxProfile.setPreference("pdfjs.disabled", true);844 firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");845 firefoxProfile.setPreference("browser.download.manager.closeWhenDone", true);846 firefoxProfile.setPreference("browser.download.manager.useWindow", false);847 firefoxProfile.setPreference("browser.download.manager.alertOnExeOpen", false);848 objCapabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);849 objCapabilities.setCapability(FirefoxDriver.PROFILE, firefoxProfile);850 this.setBrowserProxy();851 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {852 rdriver = null;853 rdriver = new RemoteWebDriver(new URL(854 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),855 objCapabilities);856 driver = new EventFiringWebDriver(rdriver);857 eventListener = null;858 eventListener = new WebDriverListener(driver);859 driver.register(eventListener);860 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()861 .contains("true")) {862 rdriver = null;863 rdriver = new RemoteWebDriver(864 new URL("http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + "/wd /hub"),865 objCapabilities);866 driver = new EventFiringWebDriver(rdriver);867 eventListener = null;868 eventListener = new WebDriverListener(driver);869 driver.register(eventListener);870 } else {871 DriverPath = System.getProperty("user.dir").replace("\\", "/")872 + "/Tool/FirefoxDrivers/linux/geckodriver";873 System.setProperty("webdriver.gecko.driver", DriverPath);874 this.wd = null;875 this.wd = new FirefoxDriver(objCapabilities);876 this.driver = new EventFiringWebDriver(wd);877 eventListener = null;878 eventListener = new WebDriverListener(this.driver);879 this.driver.register(eventListener);880 }881 driver.getWrappedDriver().manage().deleteAllCookies();882 suppressCredential();883 break;884 case "mac-iphone-device":885 case "mac-iphone_device":886 objCapabilities = new DesiredCapabilities().iphone();887 objCapabilities.setCapability("deviceName", "iPhone");888 objCapabilities.setCapability("version", ConfigManager.getProperties().getProperty("Version"));889 objCapabilities.setCapability("launchTimeout", "300000");890 objCapabilities.setCapability("newCommandTimeout", "600");891 objCapabilities.setCapability("platformVersion",892 ConfigManager.getProperties().getProperty("macPlatformVersion"));893 objCapabilities.setCapability("udid", ConfigManager.getProperties().getProperty("iphoneUdId"));894 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));895 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));896 File file = new File(ConfigManager.getProperties().getProperty("safariLuancherPath"));897 objCapabilities.setCapability("app", file.getAbsolutePath());898 try {899 // this.setBrowserProxy();900 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()901 .contains("true")) {902 rdriver = null;903 rdriver = new RemoteWebDriver(new URL(904 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),905 objCapabilities);906 Thread.sleep(20000);907 for (String winHandle : this.driver.getWindowHandles()) {908 this.driver.switchTo().window(winHandle);909 }910 this.driver = new EventFiringWebDriver(rdriver);911 eventListener = null;912 eventListener = new WebDriverListener(driver);913 driver.register(eventListener);914 break;915 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()916 .contains("true")) {917 rdriver = null;918 rdriver = new RemoteWebDriver(new URL(919 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),920 objCapabilities);921 Thread.sleep(20000);922 for (String winHandle : this.driver.getWindowHandles()) {923 this.driver.switchTo().window(winHandle);924 }925 this.driver = new EventFiringWebDriver(rdriver);926 eventListener = null;927 eventListener = new WebDriverListener(driver);928 driver.register(eventListener);929 break;930 } else {931 rdriver = null;932 this.appiumDriver = new IOSDriver(933 new URL("http://" + ConfigManager.getProperties().getProperty("appiumServerIP") + ":"934 + ConfigManager.getProperties().getProperty("appiumPort") + "/wd/hub"),935 objCapabilities);936 this.rdriver = appiumDriver;937 Thread.sleep(20000);938 for (String winHandle : this.driver.getWindowHandles()) {939 this.driver.switchTo().window(winHandle);940 }941 this.driver = new EventFiringWebDriver(rdriver);942 eventListener = null;943 eventListener = new WebDriverListener(driver);944 driver.register(eventListener);945 }946 try {947 Thread.sleep(2500);948 } catch (InterruptedException e) {949 e.printStackTrace();950 }951 suppressCredential();952 break;953 } catch (MalformedURLException e) {954 e.printStackTrace();955 break;956 }957 case "mac-iphone-simulator":958 case "mac-iphone_simulator":959 objCapabilities = new DesiredCapabilities();960 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");961 objCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Safari");962 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,963 ConfigManager.getProperties().getProperty("Version").toUpperCase().trim());964 objCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME,965 ConfigManager.getProperties().getProperty("iPhoneDeviceName").trim());966 objCapabilities.setCapability("locale", "US");967 objCapabilities.setCapability("deviceReadyTimeout", "450");968 objCapabilities.setCapability("newCommandTimeout", "600000");969 objCapabilities.setCapability("safariIgnoreFraudWarning", true);970 objCapabilities.setCapability("safariAllowPopups", true);971 objCapabilities.setCapability("fullReset", false);972 objCapabilities.setCapability("autoLaunch", true);973 objCapabilities.setCapability("autoAcceptAlerts", true);974 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));975 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));976 if (locationServiceEnabled != null) {977 objCapabilities.setCapability("locationServicesEnabled", locationServiceEnabled);978 objCapabilities.setCapability("useLocationServices", true);979 objCapabilities.setCapability("bundleId", "com.apple.mobilesafari.app");980 objCapabilities.setCapability("locationServicesAuthorized", true);981 }982 objCapabilities.setCapability("orientation", ConfigManager.getProperties().getProperty("Orientation"));983 try {984 // this.setBrowserProxy();985 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()986 .contains("true")) {987 rdriver = null;988 rdriver = new RemoteWebDriver(new URL(989 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),990 objCapabilities);991 this.driver = new EventFiringWebDriver(rdriver);992 eventListener = null;993 eventListener = new WebDriverListener(driver);994 driver.register(eventListener);995 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()996 .contains("true")) {997 rdriver = null;998 rdriver = new RemoteWebDriver(new URL(999 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),1000 objCapabilities);1001 this.driver = new EventFiringWebDriver(rdriver);1002 eventListener = null;1003 eventListener = new WebDriverListener(driver);1004 driver.register(eventListener);1005 break;1006 } else {1007 rdriver = null;1008 this.appiumDriver = new IOSDriver(1009 new URL("http://" + ConfigManager.getProperties().getProperty("appiumServerIP") + ":"1010 + ConfigManager.getProperties().getProperty("appiumPort") + "/wd/hub"),1011 objCapabilities);1012 this.rdriver = appiumDriver;1013 Thread.sleep(20000);1014 for (String winHandle : this.driver.getWindowHandles()) {1015 this.driver.switchTo().window(winHandle);1016 }1017 this.driver = new EventFiringWebDriver(rdriver);1018 eventListener = null;1019 eventListener = new WebDriverListener(driver);1020 driver.register(eventListener);1021 }1022 try {1023 Thread.sleep(2500);1024 } catch (InterruptedException e) {1025 e.printStackTrace();1026 }1027 suppressCredential();1028 break;1029 } catch (MalformedURLException e) {1030 e.printStackTrace();1031 break;1032 }1033 case "mac-ipad_safari":1034 case "mac-ipad-simulator":1035 case "mac-ipad_simulator":1036 // Appium iPad Driver1037 objCapabilities = new DesiredCapabilities();1038 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");1039 objCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Safari");1040 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,1041 ConfigManager.getProperties().getProperty("Version").toUpperCase().trim());1042 objCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME,1043 ConfigManager.getProperties().getProperty("iPadDeviceName").trim());1044 objCapabilities.setCapability("locale", "US");1045 objCapabilities.setCapability("deviceReadyTimeout", "450"); // Timeout1046 objCapabilities.setCapability("newCommandTimeout", "600000");1047 objCapabilities.setCapability("safariIgnoreFraudWarning", true);1048 objCapabilities.setCapability("safariAllowPopups", true);1049 objCapabilities.setCapability("sendKeyStrategy", "grouped");1050 objCapabilities.setCapability("fullReset", false); // for ios1051 objCapabilities.setCapability("autoLaunch", true);1052 objCapabilities.setCapability("autoAcceptAlerts", true);1053 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));1054 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));1055 if (locationServiceEnabled != null) {1056 objCapabilities.setCapability("locationServicesEnabled", locationServiceEnabled);1057 objCapabilities.setCapability("useLocationServices", true);1058 objCapabilities.setCapability("bundleId", "com.apple.mobilesafari.app");1059 objCapabilities.setCapability("locationServicesAuthorized", true);1060 }1061 objCapabilities.setCapability("orientation", ConfigManager.getProperties().getProperty("Orientation"));1062 try {1063 // this.setBrowserProxy();1064 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()1065 .contains("true")) {1066 rdriver = null;1067 rdriver = new RemoteWebDriver(new URL(1068 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),1069 objCapabilities);1070 this.driver = new EventFiringWebDriver(rdriver);1071 eventListener = null;1072 eventListener = new WebDriverListener(driver);1073 driver.register(eventListener);1074 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1075 .contains("true")) {1076 rdriver = null;1077 rdriver = new RemoteWebDriver(new URL(1078 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),1079 objCapabilities);1080 this.driver = new EventFiringWebDriver(rdriver);1081 eventListener = null;1082 eventListener = new WebDriverListener(driver);1083 driver.register(eventListener);1084 break;1085 } else {1086 rdriver = null;1087 this.appiumDriver = new IOSDriver(1088 new URL("http://" + ConfigManager.getProperties().getProperty("appiumServerIP") + ":"1089 + ConfigManager.getProperties().getProperty("appiumPort") + "/wd/hub"),1090 objCapabilities);1091 this.rdriver = appiumDriver;1092 Thread.sleep(20000);1093 for (String winHandle : this.driver.getWindowHandles()) {1094 this.driver.switchTo().window(winHandle);1095 }1096 this.driver = new EventFiringWebDriver(rdriver);1097 eventListener = null;1098 eventListener = new WebDriverListener(driver);1099 driver.register(eventListener);1100 }1101 try {1102 Thread.sleep(2500);1103 } catch (InterruptedException e) {1104 e.printStackTrace();1105 }1106 suppressCredential();1107 break;1108 } catch (MalformedURLException e) {1109 e.printStackTrace();1110 break;1111 }1112 case "windows-android-android_device":1113 objCapabilities = new DesiredCapabilities().iphone();1114 objCapabilities.setCapability("deviceName", "iPhone");1115 objCapabilities.setCapability("version", ConfigManager.getProperties().getProperty("Version"));1116 objCapabilities.setCapability("launchTimeout", "300000");1117 objCapabilities.setCapability("newCommandTimeout", "600");1118 objCapabilities.setCapability("platformVersion",1119 ConfigManager.getProperties().getProperty("macPlatformVersion"));1120 objCapabilities.setCapability("udid", ConfigManager.getProperties().getProperty("iphoneUdId"));1121 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));1122 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));1123 File file1 = new File(ConfigManager.getProperties().getProperty("safariLuancherPath"));1124 objCapabilities.setCapability("app", file1.getAbsolutePath());1125 try {1126 // this.setBrowserProxy();1127 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()1128 .contains("true")) {1129 rdriver = null;1130 rdriver = new RemoteWebDriver(new URL(1131 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),1132 objCapabilities);1133 Thread.sleep(20000);1134 for (String winHandle : this.driver.getWindowHandles()) {1135 this.driver.switchTo().window(winHandle);1136 }1137 this.driver = new EventFiringWebDriver(rdriver);1138 eventListener = null;1139 eventListener = new WebDriverListener(driver);1140 driver.register(eventListener);1141 break;1142 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1143 .contains("true")) {1144 rdriver = null;1145 rdriver = new RemoteWebDriver(new URL(1146 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),1147 objCapabilities);1148 Thread.sleep(20000);1149 for (String winHandle : this.driver.getWindowHandles()) {1150 this.driver.switchTo().window(winHandle);1151 }1152 this.driver = new EventFiringWebDriver(rdriver);1153 eventListener = null;1154 eventListener = new WebDriverListener(driver);1155 driver.register(eventListener);1156 break;1157 } else {1158 rdriver = null;1159 this.appiumDriver = new IOSDriver(1160 new URL("http://" + ConfigManager.getProperties().getProperty("appiumServerIP") + ":"1161 + ConfigManager.getProperties().getProperty("appiumPort") + "/wd/hub"),1162 objCapabilities);1163 this.rdriver = appiumDriver;1164 Thread.sleep(20000);1165 for (String winHandle : this.driver.getWindowHandles()) {1166 this.driver.switchTo().window(winHandle);1167 }1168 this.driver = new EventFiringWebDriver(rdriver);1169 eventListener = null;1170 eventListener = new WebDriverListener(driver);1171 driver.register(eventListener);1172 }1173 try {1174 Thread.sleep(2500);1175 } catch (InterruptedException e) {1176 e.printStackTrace();1177 }1178 suppressCredential();1179 break;1180 } catch (MalformedURLException e) {1181 e.printStackTrace();1182 break;1183 }1184 case "android-chrome":1185 case "mac-android-chrome":1186 case "mac-android_chrome":1187 objCapabilities = null;1188 objCapabilities = DesiredCapabilities.chrome();1189 chromeoptions = new ChromeOptions();1190 chromeoptions.setExperimentalOption("androidPackage", "com.android.chrome");1191 objCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeoptions);1192 objCapabilities.setCapability("platform", "WINDOWS");1193 objCapabilities.setCapability("browserName", "chrome");1194 objCapabilities.setCapability("app", "chrome");1195 objCapabilities.setCapability("enableHighAccuracy", true);1196 objCapabilities.setCapability("launchTimeout", "300000");1197 objCapabilities.setCapability("newCommandTimeout", "300");1198 objCapabilities.setCapability("version", "android");1199 objCapabilities.setCapability("deviceName",1200 ConfigManager.getProperties().getProperty("androidDeviceName"));1201 objCapabilities.setCapability("UDID", ConfigManager.getProperties().getProperty("androidDeviceId"));1202 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));1203 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));1204 if (osname.toLowerCase().contains("windows") || osname.toLowerCase().contains("android")) {1205 DriverPath = System.getProperty("user.dir").replace("\\", "/")1206 + "/Tool/chromedrivers/windows/chromedriver.exe";1207 }1208 System.setProperty("webdriver.chrome.driver", DriverPath);1209 // this.setBrowserProxy();1210 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {1211 rdriver = null;1212 rdriver = new RemoteWebDriver(new URL(1213 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),1214 objCapabilities);1215 this.driver = new EventFiringWebDriver(rdriver);1216 eventListener = null;1217 eventListener = new WebDriverListener(driver);1218 driver.register(eventListener);1219 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1220 .contains("true")) {1221 rdriver = null;1222 rdriver = new RemoteWebDriver(new URL(1223 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),1224 objCapabilities);1225 this.driver = new EventFiringWebDriver(rdriver);1226 eventListener = null;1227 eventListener = new WebDriverListener(driver);1228 driver.register(eventListener);1229 } else {1230 this.wd = null;1231 this.wd = new ChromeDriver(objCapabilities);1232 this.driver = new EventFiringWebDriver(wd);1233 eventListener = null;1234 eventListener = new WebDriverListener(this.driver);1235 this.driver.register(eventListener);1236 }1237 suppressCredential();1238 break;1239 case "windows-PhantomJS":1240 case "windows-phantomjs":1241 if (ConfigManager.getProperties().getProperty("KillDriverBinaries").toLowerCase().trim()1242 .contains("yes")) {1243 KillWindowProcess("phantomjs.exe");1244 }1245 String GhostPath = System.getProperty("user.dir").replace("\\", "/")1246 + "/Tool/PhantomJS/ghostdriver-1.1.1/src/main.js";1247 prefs = new LoggingPreferences();1248 prefs.enable(LogType.BROWSER, Level.ALL);1249 objCapabilities = new DesiredCapabilities();1250 objCapabilities.setCapability(CapabilityType.LOGGING_PREFS, prefs);1251 objCapabilities.setCapability("platform", CommonVariables.PlatformName.get().toUpperCase());1252 // objCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,1253 // PhantomJSPath);1254 objCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_PATH_PROPERTY, GhostPath);1255 // objCapabilities.setCapability(PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_CLI_ARGS,1256 // "");1257 objCapabilities.setCapability("browserName", "phantomjs");1258 objCapabilities.setJavascriptEnabled(true);1259 objCapabilities.setCapability("takesScreenshot", true);1260 objCapabilities.setCapability("handlesAlerts", true);1261 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));1262 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));1263 this.setBrowserProxy();1264 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {1265 rdriver = null;1266 rdriver = new RemoteWebDriver(new URL(1267 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),1268 objCapabilities);1269 this.driver = new EventFiringWebDriver(rdriver);1270 eventListener = null;1271 eventListener = new WebDriverListener(driver);1272 driver.register(eventListener);1273 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1274 .contains("true")) {1275 rdriver = null;1276 rdriver = new RemoteWebDriver(new URL(1277 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),1278 objCapabilities);1279 this.driver = new EventFiringWebDriver(rdriver);1280 eventListener = null;1281 eventListener = new WebDriverListener(driver);1282 driver.register(eventListener);1283 } else {1284 System.setProperty("phantomjs.binary.path",1285 System.getProperty("user.dir").replace("\\", "/") + "/Tool/PhantomJS/phantomjs.exe");1286 this.wd = null;1287 this.wd = new PhantomJSDriver(objCapabilities);1288 this.driver = new EventFiringWebDriver(wd);1289 eventListener = null;1290 eventListener = new WebDriverListener(this.driver);1291 this.driver.register(eventListener);1292 }1293 // this.driver.manage().window().maximize();1294 this.driver.getWrappedDriver().manage().deleteAllCookies();1295 suppressCredential();1296 break;1297 case "windows-edge":1298 if (ConfigManager.getProperties().getProperty("KillDriverBinaries").toLowerCase().trim()1299 .contains("yes")) {1300 KillWindowProcess("MicrosoftWebDriver.exe");1301 }1302 objCapabilities = new DesiredCapabilities();1303 objCapabilities.setCapability(CapabilityType.LOGGING_PREFS, prefs);1304 objCapabilities = DesiredCapabilities.internetExplorer();1305 objCapabilities.setCapability("platform", Platform.WINDOWS);1306 objCapabilities.setCapability("browser", "edge");1307 objCapabilities.setCapability("version", objCapabilities.getVersion());1308 objCapabilities.setCapability("takesScreenshot", true);1309 objCapabilities.setCapability("handlesAlerts", true);1310 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));1311 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));1312 objCapabilities.setJavascriptEnabled(true);1313 this.setBrowserProxy();1314 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {1315 rdriver = null;1316 rdriver = new RemoteWebDriver(new URL(1317 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),1318 objCapabilities);1319 this.driver = new EventFiringWebDriver(rdriver);1320 eventListener = null;1321 eventListener = new WebDriverListener(driver);1322 driver.register(eventListener);1323 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1324 .contains("true")) {1325 rdriver = null;1326 rdriver = new RemoteWebDriver(new URL(1327 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),1328 objCapabilities);1329 this.driver = new EventFiringWebDriver(rdriver);1330 eventListener = null;1331 eventListener = new WebDriverListener(driver);1332 driver.register(eventListener);1333 } else {1334 this.wd = null;1335 // File fileIE = new File("\\Program Files (x86)\\Microsoft1336 // Web Driver\\MicrosoftWebDriver.exe");1337 DriverPath = System.getProperty("user.dir").replace("\\", "/")1338 + "/Tool/EdgeDriver/MicrosoftWebDriver.exe";1339 System.setProperty("webdriver.edge.driver", DriverPath);// fileIE.getAbsolutePath()1340 this.wd = new EdgeDriver();1341 this.driver = new EventFiringWebDriver(wd);1342 eventListener = null;1343 eventListener = new WebDriverListener(this.driver);1344 this.driver.register(eventListener);1345 }1346 this.driver.manage().window().maximize();1347 driver.getWrappedDriver().manage().deleteAllCookies();1348 suppressCredential();1349 break;1350 case "windows-opera":1351 if (ConfigManager.getProperties().getProperty("KillDriverBinaries").toLowerCase().trim()1352 .contains("yes")) {1353 KillWindowProcess("operadriver.exe");1354 }1355 operaOptions = new OperaOptions();1356 operaOptions.addArguments("test-type");1357 operaOptions.addArguments("disable-session-crashed-bubble");1358 if (locationServiceEnabled != null) {1359 if (!locationServiceEnabled) {1360 Map<String, Object> prefs = new HashMap<String, Object>();1361 prefs.put("profile.default_content_settings.geolocation", 2);1362 operaOptions.setExperimentalOption("prefs", prefs);1363 } else if (locationServiceEnabled) {1364 chromeprofilepath = System.getProperty("user.dir").replace("\\", "/")1365 + "/Tool/BrowserProfiles/Chrome/" + chromeProfile;1366 if (locationServiceEnabled && ConfigManager.getProperties().getProperty("seleniumGrid")1367 .toLowerCase().trim().contains("true"))1368 chromeprofilepath = System.getProperty("user.dir").replace("\\", "/")1369 + "/Tool/BrowserProfiles/Chrome/" + chromeProfile;1370 operaOptions.addArguments("user-data-dir=" + chromeprofilepath);1371 }1372 }1373 prefs = new LoggingPreferences();1374 prefs.enable(LogType.BROWSER, Level.ALL);1375 setDownloadPathForFile(downloadedfilepath);1376 objCapabilities = new DesiredCapabilities();1377 objCapabilities.setCapability(CapabilityType.LOGGING_PREFS, prefs);1378 objCapabilities.setCapability(operaOptions.CAPABILITY, operaOptions);1379 objCapabilities.setCapability("platform", Platform.WINDOWS);1380 objCapabilities.setCapability("browser", "opera");1381 objCapabilities.setCapability("version", objCapabilities.getVersion());1382 objCapabilities.setCapability("takesScreenshot", true);1383 objCapabilities.setCapability("handlesAlerts", true);1384 objCapabilities.setCapability("opera.logging.level", Level.CONFIG);1385 // objCapabilities.setCapability("opera.logging.file",1386 // "/var/log/operadriver.log");1387 objCapabilities.setCapability("opera.display", 8);1388 objCapabilities.setJavascriptEnabled(true);1389 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));1390 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));1391 this.setBrowserProxy();1392 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {1393 rdriver = null;1394 rdriver = new RemoteWebDriver(new URL(1395 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),1396 objCapabilities);1397 this.driver = new EventFiringWebDriver(rdriver);1398 eventListener = null;1399 eventListener = new WebDriverListener(driver);1400 driver.register(eventListener);1401 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1402 .contains("true")) {1403 rdriver = null;1404 rdriver = new RemoteWebDriver(new URL(1405 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),1406 objCapabilities);1407 this.driver = new EventFiringWebDriver(rdriver);1408 eventListener = null;1409 eventListener = new WebDriverListener(driver);1410 driver.register(eventListener);1411 } else {1412 if (osname.toLowerCase().contains("windows")) {1413 DriverPath = System.getProperty("user.dir").replace("\\", "/")1414 + "/Tool/Operadrivers/windows/operadriver.exe";1415 } else {1416 DriverPath = System.getProperty("user.dir").replace("\\", "/")1417 + "/Tool/Operadrivers/operadriver";1418 }1419 System.setProperty("webdriver.opera.driver", DriverPath);1420 this.wd = new EdgeDriver();1421 this.driver = new EventFiringWebDriver(wd);1422 eventListener = null;1423 eventListener = new WebDriverListener(this.driver);1424 this.driver.register(eventListener);1425 }1426 this.driver.manage().window().maximize();1427 driver.getWrappedDriver().manage().deleteAllCookies();1428 process = Runtime.getRuntime().exec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");1429 process.waitFor();1430 Thread.sleep(3000);1431 if (locationServiceEnabled) {1432 chromeprofilepath = System.getProperty("user.dir").replace("\\", "/")1433 + "/Tool/BrowserProfiles/Chrome/" + chromeProfile;1434 if (locationServiceEnabled && ConfigManager.getProperties().getProperty("seleniumGrid")1435 .toLowerCase().trim().contains("true"))1436 chromeprofilepath = System.getProperty("user.dir").replace("\\", "/")1437 + "/Tool/BrowserProfiles/Chrome/" + chromeProfile;1438 chromeoptions.addArguments("user-data-dir=" + chromeprofilepath);1439 }1440 suppressCredential();1441 break;1442 default:1443 return null;1444 }1445 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {1446 CommonVariables.gridHubIP.set(GetIPOfSeleniumGridNode(this.driver));1447 } else {1448 CommonVariables.gridHubIP.set(CommonVariables.MachineHostName.get());1449 }1450 System.out.println("Successfully Launched the driver: " + browserType + " on the node IP: "1451 + CommonVariables.gridHubIP.get());1452 if (browserType.toLowerCase().contains("iphone") || browserType.toLowerCase().contains("ipad")) {1453 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1454 .contains("false")) {1455 hwndFirstWindow = driver.getWindowHandle();1456 arrKnownBrowserHwnd = driver.getWindowHandles();1457 }1458 /**1459 * If the location service is enabled set the geo location codes1460 * under test1461 */1462 if (this.locationServiceEnabled && (ConfigManager.getProperties().getProperty("deviceType").toLowerCase()1463 .contains("tablet")1464 || ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("iPad")1465 || ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("android")1466 || ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("iPhone"))) {1467 setGeoLocation();1468 }1469 driverStartfailureCount = 1;1470 CommonVariables.setDriver(this.driver);1471 return driver;1472 } catch (org.openqa.selenium.remote.SessionNotFoundException1473 | org.openqa.selenium.remote.UnreachableBrowserException ex) {1474 System.out.println(ex.getLocalizedMessage());1475 System.out.println(1476 "Caught SessionNotFoundException/UnreachableBrowserException/SessionNotCreatedException in Start Driver Method. Try to start one time more.");1477 if (driverStartfailureCount == 1) {1478 driverStartfailureCount = 2;1479 try {1480 Thread.sleep(50000);1481 } catch (InterruptedException intr) {1482 }1483 this.driver = (EventFiringWebDriver) instantiateDriver(browserType);1484 return driver;1485 } else {1486 System.out.println(1487 "Again Caught UnreachableBrowserException in Start Driver Method. Stopping the execution");1488 Assert.fail("Browser Unreachable twice. Exception message: " + ex.getMessage());1489 return driver;1490 }1491 } catch (Exception e) {1492 e.printStackTrace();1493 Assert.fail(e.getMessage());1494 return driver;1495 }1496 }1497 /**1498 * @author Cigniti1499 * @description : shut down driver :- This method will close all instances1500 * of all drivers.1501 */1502 public void tearDown() {1503 try {1504 if (driver != null && CommonVariables.DeviceName.get().toLowerCase().contains("chrome")1505 && CommonVariables.PlatformName.get().toLowerCase().contains("windows")) {1506 LogEntries logEntries = null;1507 try {1508 logEntries = driver.manage().logs().get(LogType.BROWSER);1509 } catch (Exception e) {1510 }1511 if (logEntries != null) {1512 for (LogEntry entry : logEntries) {1513 if ("SEVERE".equals(entry.getLevel().toString())) {1514 writeCapturedJSErrors(1515 new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());1516 }1517 }1518 }1519 }1520 } catch (Exception e) {1521 }1522 try {1523 try {1524 if (rdriver != null) {1525 //rdriver.quit();1526 rdriver.close();1527 try {1528 Thread.sleep(5000);1529 } catch (InterruptedException e1) {1530 } catch (IllegalStateException e2) {1531 }1532 }1533 } catch (Exception ex) {1534 }1535 try {1536 if (wd != null) {1537 System.out.println("Quitting the driver");1538 wd.quit();1539 try {1540 Thread.sleep(8000);1541 } catch (InterruptedException e1) {1542 } catch (IllegalStateException e2) {1543 }1544 }1545 } catch (Exception ex) {1546 }1547 try {1548 if (driver != null) {1549 //driver.quit();1550 driver.close();1551 try {1552 Thread.sleep(8000);1553 } catch (InterruptedException e1) {1554 } catch (IllegalStateException e2) {1555 }1556 }1557 } catch (Exception ex) {1558 }1559 try {1560 CommonVariables.CommonDriver.get().quit();1561 CommonVariables.CommonDriver.set(null);1562 } catch (Exception e) {1563 CommonVariables.CommonDriver.set(null);1564 }1565 if (ConfigManager.getProperties().getProperty("deviceType").trim().toLowerCase().contains("android")1566 || CommonVariables.DeviceName.get().toLowerCase().contains("safari")1567 || CommonVariables.DeviceName.get().toLowerCase().contains("iphone")) {1568 if (driver != null || wd != null || rdriver != null) {1569 try {1570 Thread.sleep(20000);1571 } catch (InterruptedException e1) {1572 }1573 ;1574 rdriver = null;1575 driver = null;1576 wd = null;1577 }1578 }1579 } catch (WebDriverException e) {1580 CommonVariables.CommonDriver.set(null);1581 try {1582 Thread.sleep(2500);1583 } catch (InterruptedException e1) {1584 } catch (IllegalStateException e2) {1585 }1586 } catch (Exception e) {1587 e.printStackTrace();1588 }1589 CommonVariables.CommonDriver.set(null);1590 }1591 /**1592 * @author Cigniti1593 * @description : In this method, it will set the proxy for BMP server1594 */1595 @SuppressWarnings("rawtypes")1596 private void setBrowserProxy() {1597 if (ConfigManager.getProperties().getProperty("IsBrowserMobProxyRequire").trim().equalsIgnoreCase("yes")) {1598 System.out.println("BMP Proxy will be used for this browser session");1599 Proxy proxy = null;1600 try {1601 // proxy = new Proxy();1602 proxy = BMP_Proxy_Controller.Server.seleniumProxy();1603 proxy.setAutodetect(false);1604 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")1605 || ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()1606 .contains("true")) {1607 String localIP = "";1608 Enumeration e = NetworkInterface.getNetworkInterfaces();1609 while (e.hasMoreElements()) {1610 NetworkInterface n = (NetworkInterface) e.nextElement();1611 Enumeration ee = n.getInetAddresses();1612 while (ee.hasMoreElements()) {1613 InetAddress i = (InetAddress) ee.nextElement();1614 if (i.getHostAddress().toString()1615 .startsWith(ConfigManager.getProperties().getProperty("proxyIPSeries"))) {1616 System.out.println(i.getHostAddress());1617 localIP = i.getHostAddress().toString();1618 break;1619 }1620 }1621 }1622 if (localIP.equals("")) {1623 InetAddress addr = InetAddress.getLocalHost();1624 String ipAddress = addr.getHostAddress();1625 localIP = ipAddress;1626 }1627 proxy.setHttpProxy(localIP + ":" + CommonVariables.portNumForBMP);1628 proxy.setSslProxy(localIP + ":" + CommonVariables.portNumForBMP);1629 } else if ((ConfigManager.getProperties().getProperty("isAWSExecution").trim()1630 .equalsIgnoreCase("true"))) {1631 String AWSBMPmachineIP = ConfigManager.getProperties().getProperty("AWSMachineIP");1632 String httpProxy = AWSBMPmachineIP + ":" + CommonVariables.portNumForBMP;1633 proxy = new Proxy();1634 proxy.setProxyType(Proxy.ProxyType.MANUAL);1635 proxy.setHttpProxy(httpProxy);1636 proxy.setSslProxy(httpProxy);1637 objCapabilities.setCapability(CapabilityType.PROXY, proxy);1638 objCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);1639 System.out.println("BMP proxy for the browser set to: " + httpProxy);1640 } else {1641 proxy.setHttpProxy("localhost:" + CommonVariables.portNumForBMP);1642 proxy.setSslProxy("localhost:" + CommonVariables.portNumForBMP);1643 }1644 if (CommonVariables.DeviceName.get().toLowerCase().contains("iphone")) {1645 objCapabilities.setCapability(MobileCapabilityType.PROXY, proxy);1646 objCapabilities.setCapability(MobileCapabilityType.ACCEPT_SSL_CERTS, true);1647 } else {1648 objCapabilities.setCapability(CapabilityType.PROXY, proxy);1649 objCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);1650 }1651 System.out.println("setting browser proxy on port:" + CommonVariables.portNumForBMP);1652 Thread.sleep(3000);1653 } catch (Exception e) {1654 System.out.println("Exception while setting the proxy for browser");1655 e.printStackTrace();1656 }1657 }1658 }1659 /**1660 * @author Cigniti1661 * @description : In this method, it will return the driver information1662 * like, if android or iOS return mobile else windows on this1663 * basis of browser selected by the user.1664 * @return1665 */1666 public static Map<String, String> GetDriverInfo() {1667 Map<String, String> DriverInfo = new HashMap<String, String>();1668 WebDriver driver = null;1669 if (wd != null) {1670 driver = wd;1671 } else if (rdriver != null) {1672 driver = rdriver;1673 } else {1674 driver = ActionsLibrary.driver;1675 }1676 try {1677 String DriverType = "";1678 String DriverName = "";1679 String osName = "";1680 if (driver == null || driver.getClass().toString().toLowerCase().contains("androiddriver")1681 || driver.getClass().toString().toLowerCase().contains("iosdriver")1682 || driver.getClass().toString().toLowerCase().contains("remotewebdriver")) {1683 try {1684 osName = CommonVariables.PlatformName.get();1685 DriverName = CommonVariables.DeviceName.get();1686 } catch (NullPointerException e) {1687 }1688 switch (osName.toUpperCase()) {1689 case "WINDOWS": {1690 if (DriverName.equals("android-chrome")) {1691 DriverType = "mobile";1692 } else {1693 DriverType = "desktop";1694 }1695 }1696 break;1697 case "MAC": {1698 if (DriverName.toLowerCase().contains("ipad")) {1699 DriverType = "tablet";1700 } else if (DriverName.toLowerCase().contains("iphone")) {1701 DriverType = "mobile";1702 } else {1703 DriverType = "desktop";1704 }1705 }1706 break;1707 case "ANDROID": {1708 DriverType = "mobile";1709 }1710 break;1711 default: {1712 }1713 }1714 } else if (driver.getClass().toString().toLowerCase().contains("chrome")) {1715 if (driver.toString().contains("chrome on ANDROID")) {1716 DriverType = "mobile";1717 DriverName = CommonVariables.DeviceName.get();1718 } else {1719 DriverType = "Desktop";1720 DriverName = "Chrome";1721 }1722 } else if (driver.getClass().toString().toLowerCase().contains("safari")) {1723 DriverType = "Desktop";1724 DriverName = "Safari";1725 } else if (driver.getClass().toString().toLowerCase().contains("firefox")) {1726 DriverType = "Desktop";1727 DriverName = "Firefox";1728 } else if (driver.getClass().toString().toLowerCase().contains("ie")1729 || driver.getClass().toString().toLowerCase().contains("internet_explorer")) {1730 DriverType = "Desktop";1731 DriverName = "internet_explorer";1732 } else if (driver.getClass().toString().toLowerCase().contains("Edge")1733 || driver.getClass().toString().toLowerCase().contains("Microsoft")) {1734 DriverType = "Desktop";1735 DriverName = "Edge";1736 } else if (driver.getClass().toString().toLowerCase().contains("Opera")) {1737 DriverType = "Desktop";1738 DriverName = "Opera";1739 } else if (driver.getClass().toString().toLowerCase().contains("PhantomJS")) {1740 DriverType = "Desktop";1741 DriverName = "PhantomJS";1742 }1743 DriverInfo.put("DriverType", DriverType);1744 // DriverInfo.put("DriverType", "tablet");1745 DriverInfo.put("DriverName", DriverName);1746 return DriverInfo;1747 } catch (Exception e) {1748 return DriverInfo;1749 }1750 }1751 /**1752 * @author Cigniti1753 * @description : write JS Errors1754 * @param errors1755 */1756 private void writeCapturedJSErrors(String errors) {1757 try {1758 // archiveFile();1759 String filePath = System.getProperty("user.dir").replace("\\", "/") + "/logs/CapturedJSErrors/jsErrors.txt";1760 fw = new FileWriter(filePath, true);1761 pw = new PrintWriter(fw);1762 pw.write(errors);1763 pw.write("\n");1764 pw.close();1765 fw.close();1766 } catch (IOException e) {1767 e.printStackTrace();1768 }1769 }1770 /**1771 * @author Cigniti1772 * @description : Archive File1773 * @throws IOException1774 */1775 private void archiveFile(String srcFilePath, String destFilePath) throws IOException {1776 try {1777 File source = new File(srcFilePath);1778 File destination = new File(destFilePath);1779 FileUtils.copyFile(source, destination);1780 } catch (FileNotFoundException e) {1781 e.getLocalizedMessage();1782 }1783 }1784 /**1785 * @author Cigniti1786 * @description : Method to Find Element1787 * @param by1788 * @param timeoutInSeconds1789 * @return1790 * @throws Throwable1791 */1792 public WebElement FindElement(By by, Optional<Long> timeoutInSeconds) {1793 long timeout = timeoutInSeconds.isPresent() ? timeoutInSeconds.get() : -1;1794 if (timeout == -1) {1795 timeout = Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut"));1796 }1797 WebElement webElement = null;1798 try {1799 AcceptAlert();1800 webElement = (new WebDriverWait(driver, timeout)).until(ExpectedConditions.presenceOfElementLocated(by));1801 try {1802 if (webElement != null || CommonVariables.TestCaseLog.get() != null) {1803 extentLogs.pass("Find Element",1804 "Successfully find an element on '" + driver.getTitle() + "' page.");1805 CommonVariables.TestCaseLog.get()1806 .info("Successfully find '" + by + "' element on '" + driver.getTitle() + "' page");1807 } else {1808 extentLogs.fail("Find Element", "Element not found on '" + driver.getTitle() + "' page.");1809 CommonVariables.TestClassLog.get()1810 .info("Successfully find '" + by + "' element on '" + driver.getTitle() + "' page");1811 }1812 } catch (NullPointerException e) {1813 extentLogs.error("Find Element", "Element not found on '" + driver.getTitle()1814 + "' page due to exception - " + e.getLocalizedMessage());1815 throw new NullPointerException();1816 }1817 try {1818 ScrollToElementVisible(by);1819 } catch (org.openqa.selenium.ElementNotVisibleException e) {1820 if (CommonVariables.TestCaseLog.get() != null) {1821 CommonVariables.TestCaseLog.get()1822 .info("Element (" + by + ") is not visible on '" + driver.getTitle() + "' page");1823 } else {1824 CommonVariables.TestClassLog.get()1825 .info("Element (" + by + ") is not visible on '" + driver.getTitle() + "' page");1826 }1827 extentLogs.error("Find Element", "Element not visible on '" + driver.getTitle()1828 + "' page due to exception - " + e.getLocalizedMessage());1829 throw new ElementNotVisibleException("Element not visible.");1830 } catch (org.openqa.selenium.WebDriverException e) {1831 if (CommonVariables.TestCaseLog.get() != null) {1832 CommonVariables.TestCaseLog.get()1833 .info("Failed to move Element (" + by + ") on the running driver type.");1834 } else {1835 CommonVariables.TestClassLog.get()1836 .info("Failed to move Element (" + by + ") on the running driver type.");1837 }1838 extentLogs.error("Find Element",1839 "Failed to move to an Element due to exception - " + e.getLocalizedMessage());1840 throw new WebDriverException();1841 } catch (NullPointerException ex) {1842 System.out.println("Getting exception when movetoElement under FindElement method in" + getClass()1843 + " class. Driver info under CommonVariable :" + CommonVariables.getDriver());1844 throw new NullPointerException();1845 }1846 return webElement;1847 } catch (Exception ex) {1848 if (ex.getCause().toString().contains("SessionNotFoundException")) {1849 throw new SessionNotFoundException();1850 } else if (ex.getCause().toString().contains("UnhandledAlertException")) {1851 if (AcceptAlert()) {1852 return driver.findElement(by);1853 }1854 if (CommonVariables.TestCaseLog.get() != null) {1855 CommonVariables.TestCaseLog.get().info("caught 'UnhandledAlertException' exception while finding '"1856 + by + "' element on '" + driver.getTitle() + "' page");1857 } else {1858 CommonVariables.TestClassLog.get().info("caught 'UnhandledAlertException' exception while finding '"1859 + by + "' element on '" + driver.getTitle() + "' page");1860 }1861 extentLogs.error("Find Element",1862 "caught 'UnhandledAlertException' exception while finding an element on '" + driver.getTitle()1863 + "' page");1864 throw new UnhandledAlertException("");1865 } else if (ex.getCause().toString().contains("NoSuchElementException")) {1866 if (AcceptAlert()) {1867 return driver.findElement(by);1868 }1869 if (CommonVariables.TestCaseLog.get() != null) {1870 CommonVariables.TestCaseLog.get().info("No such element(" + by + ") found on '" + driver.getTitle()1871 + "' page at " + driver.getCurrentUrl() + "' url.");1872 } else {1873 CommonVariables.TestClassLog.get().info("No such element(" + by + ") found on '" + driver.getTitle()1874 + "' page at " + driver.getCurrentUrl() + "' url.");1875 }1876 extentLogs.error("Find Element", "No such element éxception found on '" + driver.getTitle()1877 + "' page at " + driver.getCurrentUrl() + "' url.");1878 throw new NoSuchElementException("No such Element");1879 } else if (ex.getCause().toString().contains("TimeoutException")) {1880 if (AcceptAlert()) {1881 return driver.findElement(by);1882 } else {1883 if (CommonVariables.TestCaseLog.get() != null) {1884 CommonVariables.TestCaseLog.get()1885 .info("No such element(" + by + ") found on '" + driver.getTitle() + "' page at "1886 + driver.getCurrentUrl() + "' url within timelimit (" + timeout + ").");1887 } else {1888 CommonVariables.TestClassLog.get()1889 .info("No such element(" + by + ") found on '" + driver.getTitle() + "' page at "1890 + driver.getCurrentUrl() + "' url within timelimit (" + timeout + ").");1891 }1892 extentLogs.error("Find Element", "No such element exception found on '" + driver.getTitle()1893 + "' page at " + driver.getCurrentUrl() + "' url within timelimit (" + timeout + ").");1894 }1895 throw new TimeoutException();1896 } else if (ex.getCause().toString().contains("StaleElementReferenceException")) {1897 if (CommonVariables.TestCaseLog.get() != null) {1898 CommonVariables.TestCaseLog.get()1899 .info("Info. Caught 'StaleElementReferenceException' exception while finding (" + by1900 + ") element. Class: " + ex.getClass());1901 } else {1902 CommonVariables.TestClassLog.get()1903 .info("Info. Caught 'StaleElementReferenceException' exception while finding (" + by1904 + ") element. Class: " + ex.getClass());1905 }1906 extentLogs.error("Find Element",1907 "Caught 'StaleElementReferenceException' exception while finding an element. Class: "1908 + ex.getClass());1909 }1910 AcceptAlert();1911 try {1912 webElement = driver.findElement(by);1913 ScrollToElementVisible(by);1914 return webElement;1915 } catch (Exception e) {1916 if (CommonVariables.TestCaseLog.get() != null) {1917 CommonVariables.TestCaseLog.get()1918 .info("Error. Caught 'StaleElementReferenceException' exception while finding (" + by1919 + ") element. Exception Type: " + e.getClass());1920 } else {1921 CommonVariables.TestClassLog.get()1922 .info("Error. Caught 'StaleElementReferenceException' exception while finding (" + by1923 + ") element. Exception Type: " + e.getClass());1924 }1925 throw new StaleElementReferenceException("Stale Exception while finding an element.");1926 }1927 }1928 }1929 /**1930 * @author Cigniti1931 * @description: click on webElement1932 * @param webElement1933 * @return1934 */1935 public boolean Click(WebElement webElement) {1936 return Click(webElement, 4);1937 }1938 /**1939 * @author Cigniti1940 * @description: click on webElement1941 * @param webElement1942 * @return1943 */1944 public boolean Click(WebElement webElement, String str) {1945 return Click(webElement, 4, str);1946 }1947 /**1948 * @author Cigniti1949 * @description: click on webElement1950 * @param webElement1951 * @return1952 */1953 public boolean Click(By locators, String str) {1954 WebElement webElement=driver.findElement(locators);1955 return Click(webElement, 4, str);1956 }1957 1958 /**1959 * @author Cigniti1960 * @description : Webdriver and Java Script Click. Wait time in seconds i.e.1961 * 8 for 8 seconds1962 * @param webElement1963 * and wait time in seconds1964 * @return1965 */1966 public boolean Click(WebElement webElement, Integer waitTime) {1967 boolean state = false;1968 try {1969 Thread.sleep(500);1970 webElement.click();1971 try {1972 Thread.sleep(waitTime * 1000);1973 extentLogs.pass("Click", "Successfully clicked.");1974 if (CommonVariables.TestCaseLog.get() != null) {1975 CustomLogs.addToLog("CurrentTestCaseLog", "info", "Passed. Successfully clicked.");1976 } else {1977 CustomLogs.addToLog("CurrentTestClassLog", "info", "Passed. Successfully clicked.");1978 }1979 state = true;1980 } catch (InterruptedException e) {1981 e.printStackTrace();1982 }1983 } catch (ElementNotVisibleException e1) {1984 extentLogs.error("Click", "Element is not visible.");1985 if (CommonVariables.TestCaseLog.get() != null) {1986 CommonVariables.TestCaseLog.get().debug("Error: Element (" + webElement + ") is not visible.");1987 } else {1988 CommonVariables.TestClassLog.get().debug("Error: Element (" + webElement + ") is not visible.");1989 }1990 } catch (StaleElementReferenceException e2) {1991 extentLogs.error("Click", "Caught 'StaleElementReferenceException' exception while clicking on element.");1992 if (CommonVariables.TestCaseLog.get() != null) {1993 CommonVariables.TestCaseLog.get()1994 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"1995 + webElement + "' element.");1996 } else {1997 CommonVariables.TestClassLog.get()1998 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"1999 + webElement + "' element.");2000 }2001 AcceptAlert();2002 // driver.navigate().refresh();2003 try {2004 if (webElement.isEnabled()) {2005 webElement.click();2006 }2007 } catch (Exception e) {2008 }2009 } catch (org.openqa.selenium.UnhandledAlertException e3) {2010 extentLogs.error("Click", "Error. Caught 'UnhandledAlertException' exception while clicking on element.");2011 AcceptAlert();2012 try {2013 if (webElement.isDisplayed()) {2014 webElement.click();2015 }2016 } catch (Exception e) {2017 if (CommonVariables.TestCaseLog.get() != null) {2018 CommonVariables.TestCaseLog.get()2019 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement2020 + "' element.");2021 } else {2022 CommonVariables.TestClassLog.get()2023 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement2024 + "' element.");2025 }2026 e.printStackTrace();2027 }2028 } catch (NullPointerException e5) {2029 extentLogs.error("Click", "Error. Caught 'NullPointerException' exception while clicking element on '"2030 + driver.getTitle() + "'.");2031 if (CommonVariables.TestCaseLog.get() != null) {2032 CommonVariables.TestCaseLog.get()2033 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"2034 + driver.getTitle() + "'.");2035 } else {2036 CommonVariables.TestClassLog.get()2037 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"2038 + driver.getTitle() + "'.");2039 }2040 } catch (org.openqa.selenium.WebDriverException e6) {2041 if (e6.getMessage().toString().toLowerCase().contains("user supplied")) {2042 try {2043 JavascriptExecutor js = (JavascriptExecutor) (driver);2044 js.executeScript("arguments[0].click();", webElement);2045 Thread.sleep(8000);2046 state = true;2047 } catch (Exception e) {2048 if (!state) {2049 try {2050 JavascriptExecutor js = (JavascriptExecutor) (driver);2051 js.executeScript("$(arguments[0]).focusin();", webElement);2052 Thread.sleep(8000);2053 state = true;2054 } catch (Exception e1) {2055 state = false;2056 }2057 }2058 }2059 }2060 if (e6.getMessage().toString().toLowerCase().contains("Element is not clickable")) {2061 extentLogs.error("Click",2062 "Caught exception about 'Element is not clickable' while clicking element on '"2063 + driver.getTitle()2064 + "'. So Scroll Top/Bottom and wait for sometime to make clickable");2065 if (CommonVariables.TestCaseLog.get() != null) {2066 CommonVariables.TestCaseLog.get()2067 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"2068 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"2069 + webElement + "' clickable");2070 } else {2071 CommonVariables.TestClassLog.get()2072 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"2073 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"2074 + webElement + "' clickable");2075 }2076 }2077 try {2078 try {2079 if (ScrollToElementVisible(webElement)) {2080 try {2081 new WebDriverWait(driver, Long.parseLong("2"))2082 .until(ExpectedConditions.elementToBeClickable(webElement)).click();2083 Thread.sleep(8000);2084 return true;2085 } catch (Exception ex) {2086 try {2087 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2088 js.executeScript("arguments[0].click();", webElement);2089 } catch (Exception e) {2090 return false;2091 }2092 }2093 }2094 } catch (Exception e) {2095 return false;2096 }2097 try {2098 ScrollToTop();2099 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2100 js.executeScript("arguments[0].focusin();", webElement);2101 new WebDriverWait(driver, Long.parseLong("10"))2102 .until(ExpectedConditions.elementToBeClickable(webElement)).click();2103 Thread.sleep(8000);2104 state = true;2105 } catch (Exception e1) {2106 if (e6.getMessage().toString().toLowerCase().contains("element is not clickable")) {2107 try {2108 ScrollToBottom();2109 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2110 js.executeScript("arguments[0].focusin();", webElement);2111 new WebDriverWait(driver, Long.parseLong("10"))2112 .until(ExpectedConditions.elementToBeClickable(webElement)).click();2113 state = true;2114 } catch (Exception e) {2115 return false;2116 }2117 } else {2118 state = false;2119 }2120 }2121 } catch (Exception e) {2122 try {2123 Actions clicker = new Actions(CommonVariables.CommonDriver.get());2124 clicker.moveToElement(webElement).click().perform();2125 } catch (Exception e7) {2126 state = false;2127 extentLogs.error("Click", "Element is not clickable.");2128 if (CommonVariables.TestCaseLog.get() != null) {2129 CommonVariables.TestCaseLog.get().error("Error: element is not clickable.");2130 } else {2131 CommonVariables.TestClassLog.get().error("Error: element is not clickable.");2132 }2133 }2134 }2135 } catch (Exception e4) {2136 state = false;2137 }2138 return state;2139 }2140 public boolean Click(WebElement webElement, Integer waitTime, String str) {2141 boolean state = false;2142 try {2143 Thread.sleep(500);2144 webElement.click();2145 try {2146 Thread.sleep(waitTime * 1000);2147 extentLogs.pass("Click", "Successfully clicked '" + str + "'");2148 if (CommonVariables.TestCaseLog.get() != null) {2149 CustomLogs.addToLog("CurrentTestCaseLog", "info", "Passed. Successfully clicked.");2150 } else {2151 CustomLogs.addToLog("CurrentTestClassLog", "info", "Passed. Successfully clicked.");2152 }2153 state = true;2154 } catch (InterruptedException e) {2155 e.printStackTrace();2156 }2157 } catch (ElementNotVisibleException e1) {2158 extentLogs.error("Click", "Element is not visible.");2159 if (CommonVariables.TestCaseLog.get() != null) {2160 CommonVariables.TestCaseLog.get().debug("Error: Element (" + webElement + ") is not visible.");2161 } else {2162 CommonVariables.TestClassLog.get().debug("Error: Element (" + webElement + ") is not visible.");2163 }2164 } catch (StaleElementReferenceException e2) {2165 extentLogs.error("Click", "Caught 'StaleElementReferenceException' exception while clicking on element.");2166 if (CommonVariables.TestCaseLog.get() != null) {2167 CommonVariables.TestCaseLog.get()2168 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"2169 + webElement + "' element.");2170 } else {2171 CommonVariables.TestClassLog.get()2172 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"2173 + webElement + "' element.");2174 }2175 AcceptAlert();2176 // driver.navigate().refresh();2177 try {2178 if (webElement.isEnabled()) {2179 webElement.click();2180 }2181 } catch (Exception e) {2182 }2183 } catch (org.openqa.selenium.UnhandledAlertException e3) {2184 extentLogs.error("Click", "Error. Caught 'UnhandledAlertException' exception while clicking on element.");2185 AcceptAlert();2186 try {2187 if (webElement.isDisplayed()) {2188 webElement.click();2189 }2190 } catch (Exception e) {2191 if (CommonVariables.TestCaseLog.get() != null) {2192 CommonVariables.TestCaseLog.get()2193 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement2194 + "' element.");2195 } else {2196 CommonVariables.TestClassLog.get()2197 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement2198 + "' element.");2199 }2200 e.printStackTrace();2201 }2202 } catch (NullPointerException e5) {2203 extentLogs.error("Click", "Error. Caught 'NullPointerException' exception while clicking element on '"2204 + driver.getTitle() + "'.");2205 if (CommonVariables.TestCaseLog.get() != null) {2206 CommonVariables.TestCaseLog.get()2207 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"2208 + driver.getTitle() + "'.");2209 } else {2210 CommonVariables.TestClassLog.get()2211 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"2212 + driver.getTitle() + "'.");2213 }2214 } catch (org.openqa.selenium.WebDriverException e6) {2215 if (e6.getMessage().toString().toLowerCase().contains("user supplied")) {2216 try {2217 JavascriptExecutor js = (JavascriptExecutor) (driver);2218 js.executeScript("arguments[0].click();", webElement);2219 Thread.sleep(8000);2220 state = true;2221 } catch (Exception e) {2222 if (!state) {2223 try {2224 JavascriptExecutor js = (JavascriptExecutor) (driver);2225 js.executeScript("$(arguments[0]).focusin();", webElement);2226 Thread.sleep(8000);2227 state = true;2228 } catch (Exception e1) {2229 state = false;2230 }2231 }2232 }2233 }2234 if (e6.getMessage().toString().toLowerCase().contains("Element is not clickable")) {2235 extentLogs.error("Click",2236 "Caught exception about 'Element is not clickable' while clicking element on '"2237 + driver.getTitle()2238 + "'. So Scroll Top/Bottom and wait for sometime to make clickable");2239 if (CommonVariables.TestCaseLog.get() != null) {2240 CommonVariables.TestCaseLog.get()2241 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"2242 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"2243 + webElement + "' clickable");2244 } else {2245 CommonVariables.TestClassLog.get()2246 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"2247 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"2248 + webElement + "' clickable");2249 }2250 }2251 try {2252 try {2253 if (ScrollToElementVisible(webElement)) {2254 try {2255 new WebDriverWait(driver, Long.parseLong("2"))2256 .until(ExpectedConditions.elementToBeClickable(webElement)).click();2257 Thread.sleep(8000);2258 return true;2259 } catch (Exception ex) {2260 try {2261 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2262 js.executeScript("arguments[0].click();", webElement);2263 } catch (Exception e) {2264 return false;2265 }2266 }2267 }2268 } catch (Exception e) {2269 return false;2270 }2271 try {2272 ScrollToTop();2273 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2274 js.executeScript("arguments[0].focusin();", webElement);2275 new WebDriverWait(driver, Long.parseLong("10"))2276 .until(ExpectedConditions.elementToBeClickable(webElement)).click();2277 Thread.sleep(8000);2278 state = true;2279 } catch (Exception e1) {2280 if (e6.getMessage().toString().toLowerCase().contains("element is not clickable")) {2281 try {2282 ScrollToBottom();2283 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2284 js.executeScript("arguments[0].focusin();", webElement);2285 new WebDriverWait(driver, Long.parseLong("10"))2286 .until(ExpectedConditions.elementToBeClickable(webElement)).click();2287 state = true;2288 } catch (Exception e) {2289 return false;2290 }2291 } else {2292 state = false;2293 }2294 }2295 } catch (Exception e) {2296 try {2297 Actions clicker = new Actions(CommonVariables.CommonDriver.get());2298 clicker.moveToElement(webElement).click().perform();2299 } catch (Exception e7) {2300 state = false;2301 extentLogs.error("Click", "Element is not clickable.");2302 if (CommonVariables.TestCaseLog.get() != null) {2303 CommonVariables.TestCaseLog.get().error("Error: element is not clickable.");2304 } else {2305 CommonVariables.TestClassLog.get().error("Error: element is not clickable.");2306 }2307 }2308 }2309 } catch (Exception e4) {2310 state = false;2311 }2312 return state;2313 }2314 /**2315 * @author Cigniti2316 * @description : javascript Click2317 * @param webElement2318 * @return2319 */2320 public boolean JSClick(By loc,String strText)2321 {2322 WebElement elem=driver.findElement(loc);2323 return javascriptClick(elem);2324 }2325 2326 /**2327 * @author Cigniti2328 * @description : javascript Click2329 * @param webElement2330 * @return2331 */2332 public boolean javascriptClick(WebElement webElement) {2333 boolean state = false;2334 try {2335 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2336 js.executeScript("arguments[0].click();", webElement);2337 Thread.sleep(4000);2338 state = true;2339 return true;2340 } catch (NullPointerException ex) {2341 return false;2342 } catch (Exception e) {2343 try {2344 if (ScrollToElementVisible(By.xpath(getElementXPath(webElement)))) {2345 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2346 js.executeScript("$(arguments[0]).click();", webElement);2347 Thread.sleep(4000);2348 state = true;2349 return true;2350 } else {2351 return false;2352 }2353 } catch (Exception ex) {2354 }2355 if (!state) {2356 try {2357 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2358 js.executeScript("$(arguments[0]).focusin();", webElement);2359 Thread.sleep(8000);2360 state = true;2361 }2362 catch (Exception e1) {2363 state = false;2364 }2365 }2366 }2367 return state;2368 }2369 /**2370 * @author Cigniti2371 * @description : javascript Send Keys2372 * @param webElement2373 * @return2374 */2375 public boolean javascriptSendKeys(WebElement locator, String valueToType) {2376 boolean state = false;2377 try {2378 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());2379 js.executeScript("arguments[0].value=\"" + valueToType + "\";", locator);2380 state = true;2381 extentLogs.pass("Type", "Successfully entered text value - '" + valueToType + "'.");2382 } catch (Exception ex) {2383 extentLogs.error("Type",2384 "Failed to enter text value - '" + valueToType + "' due to execption - " + ex.getMessage() + ".");2385 state = false;2386 }2387 return state;2388 }2389 /**2390 * @author Cigniti2391 * @description: webdriver send keys2392 * @param locator2393 * the locator2394 * @param valueToType2395 * the value to type2396 * @param locatorName2397 * the locator name2398 * @return true, if successful2399 * @throws Throwable2400 * the throwable2401 */2402 public boolean type(WebElement element, String valueToType) throws Throwable {2403 boolean status = false;2404 try {2405 WebDriverWait wait = new WebDriverWait(this.driver, 60);2406 ScrollToElementVisible(element);2407 wait.until(ExpectedConditions.elementToBeClickable(element));2408 element.clear();2409 element.sendKeys(valueToType);2410 status = true;2411 extentLogs.pass("Type", "Successfully entered text value - '" + valueToType + "'.");2412 } catch (Exception e) {2413 status = false;2414 extentLogs.error("Type",2415 "Failed to enter text value - '" + valueToType + "' due to execption - " + e.getMessage() + ".");2416 if (CommonVariables.TestCaseLog.get() != null) {2417 CommonVariables.TestCaseLog.get().error("Error: Failed to enter text value - '" + valueToType2418 + "' due to execption - " + e.getMessage() + ".");2419 } else {2420 CommonVariables.TestClassLog.get().error("Error: Failed to enter text value - '" + valueToType2421 + "' due to execption - " + e.getMessage() + ".");2422 }2423 }2424 return status;2425 }2426 2427 2428 public boolean type(By locators, String valueToType,String objectName) throws Throwable2429 {2430 WebElement element=driver.findElement(locators);2431 return type(element,valueToType,objectName);2432 }2433 2434 public boolean type(WebElement element, String valueToType,String objectName) throws Throwable {2435 boolean status = false;2436 try {2437 WebDriverWait wait = new WebDriverWait(this.driver, 60);2438 ScrollToElementVisible(element);2439 wait.until(ExpectedConditions.elementToBeClickable(element));2440 element.clear();2441 element.sendKeys(valueToType);2442 status = true;2443 extentLogs.pass("Type", "Successfully entered text value - '" + valueToType +" at "+objectName+ "'.");2444 } catch (Exception e) {2445 status = false;2446 extentLogs.error("Type",2447 "Failed to enter text value - '" + valueToType + "' at "+objectName+"due to execption - " + e.getMessage() + ".");2448 if (CommonVariables.TestCaseLog.get() != null) {2449 CommonVariables.TestCaseLog.get().error("Error: Failed to enter text value - '" + valueToType2450 +" at "+objectName+ "' due to execption - " + e.getMessage() + ".");2451 } else {2452 CommonVariables.TestClassLog.get().error("Error: Failed to enter text value - '" + valueToType2453 +" at "+objectName+ "' due to execption - " + e.getMessage() + ".");2454 }2455 }2456 return status;2457 }2458 /**2459 * @author Cigniti2460 * @description: browser specific send keys.2461 * @param locator2462 * @param value2463 * @param locatorName2464 * @throws Throwable2465 */2466 public void browserSpecificSendKeys(WebElement locator, String valueToType) throws Throwable {2467 String browserName = CommonVariables.DeviceName.get();2468 try {2469 switch (browserName.toLowerCase()) {2470 case "firefox":2471 case "chrome":2472 case "opera": {2473 type(locator, valueToType);2474 break;2475 }2476 case "ie":2477 case "safari":2478 case "edge":2479 case "pahntomjs": {2480 javascriptSendKeys(locator, valueToType);2481 break;2482 }2483 }2484 } catch (Exception ex) {2485 ex.printStackTrace();2486 }2487 }2488 /**2489 * Select by visible text.2490 * 2491 * @description: select a value from drop down list on the basis of visible2492 * text2493 * @param locator2494 * the locator2495 * @param value2496 * the value2497 * @param locatorName2498 * the locator name2499 * @return true, if successful2500 * @throws Throwable2501 * the throwable2502 */2503 public boolean selectByVisibleText(By locator, String value, String locatorName) throws Throwable {2504 boolean flag = false;2505 try {2506 //ScrollToElementVisible(locator);2507 WebElement dropDownListBox = driver.findElement(locator);2508 Select clickThis = new Select(dropDownListBox);2509 //Select clickThis = new Select(driver.findElement(locator));2510 clickThis.selectByVisibleText(value);2511 fluentWait(30, 6);2512 flag = true;2513 } catch (Exception e) {2514 extentLogs.error("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName2515 + " due to exception - " + e.getLocalizedMessage());2516 flag = false;2517 } finally {2518 if (flag == false) {2519 extentLogs.fail("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName);2520 } else if (flag == true) {2521 extentLogs.pass("Select", "'" + value + "'" + "is selected from the DropDown " + locatorName);2522 }2523 }2524 return flag;2525 }2526 public boolean asserTitle(String title) throws Throwable {2527 boolean flag = false;2528 try {2529 By windowTitle = By.xpath("//title[contains(text(),'" + title2530 + "')]");2531 if (waitForTitlePresent(windowTitle)) {2532 Assert.assertEquals(GetPageTitle(), title);2533 flag = true;2534 return true;2535 } else {2536 return false;2537 }2538 } catch (Exception ex) {2539 ex.printStackTrace();2540 return false;2541 } finally {2542 if (!flag) {2543 extentLogs.fail("AsserTitle ",2544 "Page title is not matched with " + title);2545 return false;2546 } else if (flag) {2547 extentLogs.pass("AsserTitle ",2548 " Page title is verified with " + title);2549 }2550 }2551 }2552 2553 public boolean isElementPresent(By by, String locatorName)2554 throws Throwable {2555 boolean flag = false;2556 try {2557 driver.findElement(by);2558 flag = true;2559 return true;2560 } catch (Exception e) {2561 Assert.assertTrue(flag,"Element: <b>"+ locatorName+"</b> is <b>NOT</b> present on the page ");2562 e.printStackTrace();2563 return false;2564 } finally {2565 if (!flag) {2566 extentLogs.fail("Is Element Present ", locatorName2567 + "Element: <b>"+ locatorName+"</b> is <b>NOT</b> present on the page ");2568 Assert.assertTrue(flag,"Element: <b>"+ locatorName+"</b> is <b>NOT</b> present on the page ");2569 } else if (flag) {2570 extentLogs.pass("IsElementPresent ",2571 "Able to locate element <b>" + locatorName + "</b>");2572 }2573 }2574 }2575 2576 public boolean waitForVisibilityOfElementWithOutAssertion(By by, String locator)2577 throws Throwable {2578 boolean flag = false;2579 WebDriverWait wait = new WebDriverWait(driver, 20,30);2580 try {2581 wait.until(ExpectedConditions.visibilityOfElementLocated(by));2582 flag = true;2583 return true;2584 } catch (Exception e) {2585 //Assert.assertTrue(flag," Element "2586 // + locator + " is not visible");2587 return false;2588 } finally {2589 if (!flag) {2590 extentLogs.fail("WsaitForVisibilityOfElementWithOutAssertion ", " Element "2591 + locator + " is not visible");2592 } else if ( flag) {2593 extentLogs.pass("WaitForVisibilityOfElementWithOutAssertion ", " Element "2594 + locator + " is visible");2595 }2596 }2597 }2598 2599 public boolean waitForVisibilityOfElement(By by, String locator)2600 throws Throwable {2601 boolean flag = false;2602 WebDriverWait wait = new WebDriverWait(driver, 20,30);2603 try {2604 wait.until(ExpectedConditions.visibilityOfElementLocated(by));2605 flag = true;2606 return true;2607 } catch (Exception e) {2608 Assert.assertTrue(flag," Element "2609 + locator + " is not visible");2610 return false;2611 } finally {2612 if (!flag) {2613 extentLogs.fail("WaitForVisibilityOfElement ", " Element "2614 + locator + " is not visible");2615 } else if ( flag) {2616 extentLogs.pass("WaitForVisibilityOfElement ", " Element "2617 + locator + " is visible");2618 }2619 }2620 }2621 2622 public List<String> fnGetAllList(By locator,String locatorName) throws Throwable{2623 List<String>totalContentList=new ArrayList<String>();2624 List<WebElement>contentElement =null;2625 try{2626 contentElement=driver.findElements(locator);2627 extentLogs.pass("Total List Found ", "Available list is <b>"+contentElement.size()+"</b>");2628 for(int i=0;i<contentElement.size();i++){2629 totalContentList.add(contentElement.get(i).getText());2630 2631 }2632 }catch(Exception e){2633 e.printStackTrace();2634 extentLogs.fail("Total List Not Found ", "List is not available <b>"+contentElement.size()+"</b>");2635 e.printStackTrace();2636 }2637 return totalContentList;2638 }2639 public List<WebElement> fnGetAllWebElementList(By locator,String locatorName) throws Throwable{2640 List<WebElement>totalContentWebElementList=new ArrayList<WebElement>();2641 List<WebElement>contentElement =null;2642 try{2643 contentElement=driver.findElements(locator);2644 extentLogs.pass("Total WebElement List Found ", "Available WebElement list is <b>"+contentElement.size()+"</b>");2645 for(int i=1;i<contentElement.size();i++){2646 System.out.println("contentElement.size() "+contentElement.size());2647 totalContentWebElementList.add(contentElement.get(i));2648 //System.out.println("totalContentWebElementList "+totalContentWebElementList);2649 //return totalContentWebElementList;2650 }2651 2652 }catch(Exception e){2653 e.printStackTrace();2654 extentLogs.fail("Total WebElement List Not Found ", "WebElement List is not available <b>"+contentElement.size()+"</b>");2655 2656 }2657 System.out.println("totalContentWebElementList +++"+totalContentWebElementList);2658 return totalContentWebElementList;2659 }2660 2661 2662 public List<WebElement> fnGetAllElementList(By locator,String locatorName) throws Throwable{2663 List<WebElement>totalContentWebElementList=new ArrayList<WebElement>();2664 List<WebElement>contentElement =null;2665 try{2666 contentElement=driver.findElements(locator);2667 extentLogs.pass("Total WebElement List Found ", "Available WebElement list is <b>"+contentElement.size()+"</b>");2668 for(int i=0;i<contentElement.size();i++){2669 System.out.println("contentElement.size() "+contentElement.size());2670 totalContentWebElementList.add(contentElement.get(i));2671 //System.out.println("totalContentWebElementList "+totalContentWebElementList);2672 //return totalContentWebElementList;2673 }2674 2675 }catch(Exception e){2676 e.printStackTrace();2677 extentLogs.fail("Total WebElement List Not Found ", "WebElement List is not available <b>"+contentElement.size()+"</b>");2678 2679 }2680 System.out.println("totalContentWebElementList +++"+totalContentWebElementList);2681 return totalContentWebElementList;2682 }2683 2684 public boolean mousehoverWithOutAssertion(By locator, String locatorName)2685 throws Throwable {2686 boolean flag = false;2687 try {2688 WebElement mo = driver.findElement(locator);2689 new Actions(driver).moveToElement(mo).build().perform();2690 2691 flag = true;2692 return true;2693 } catch (Exception e) {2694 //Assert.assertTrue(flag,"MouseOver action is not performed on " + locatorName);2695 return false;2696 } finally {2697 if (!flag) {2698 extentLogs.fail("MouseOver",2699 "MouseOver action is not performed on " + locatorName);2700 //Assert.assertTrue(flag,"Unable find the element "+ locatorName);2701 } else if ( flag) {2702 extentLogs.pass("MouseOver ",2703 "MouserOver Action is performed on <b>" + locatorName + "</b>");2704 }2705 }2706 }2707 2708 public boolean mouseHoverByJavaScriptByLocator(By locator, String locatorName)2709 throws Throwable {2710 boolean flag = false;2711 try {2712 WebElement mo = driver.findElement(locator);2713 String javaScript = "var evObj = document.createEvent('MouseEvents');"2714 + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"2715 + "arguments[0].dispatchEvent(evObj);";2716 JavascriptExecutor js = (JavascriptExecutor) driver;2717 js.executeScript(javaScript, mo);2718 flag = true;2719 return true;2720 }2721 catch (Exception e) {2722 return false;2723 } finally {2724 if (!flag) {2725 extentLogs.fail("MouseOver ",2726 "MouseOver Action was <b>NOT</b> perform on <b>" + locatorName + "</b>");2727 } else if ( flag) {2728 extentLogs.pass("MouseOver ",2729 "MouserOver Action was performed on <b>" + locatorName + "</b>");2730 }2731 }2732 }2733 2734 public boolean isElementDisplayed(By loc)2735 throws Throwable {2736 boolean flag = false;2737 try {2738 WebDriverWait newWait = new WebDriverWait(driver,20,30);2739 WebElement element = null;2740 element = newWait.until(ExpectedConditions.presenceOfElementLocated(loc));2741 flag = element.isDisplayed();2742 } catch (Exception e) {2743 return false;2744 }2745 return flag;2746 }2747 public boolean mouseHoverByJavaScript(WebElement we)2748 throws Throwable {2749 boolean flag = false;2750 try {2751 WebElement mo = we;2752 String javaScript = "var evObj = document.createEvent('MouseEvents');"2753 + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"2754 + "arguments[0].dispatchEvent(evObj);";2755 JavascriptExecutor js = (JavascriptExecutor) driver;2756 js.executeScript(javaScript, mo);2757 flag = true;2758 return true;2759 }2760 catch (Exception e) {2761 return false;2762 } /*finally {2763 if (!flag) {2764 Reporter.failureReport("MouseOver ",2765 " MouseOver action is not perform on " + locatorName);2766 } else if (b && flag) {2767 Reporter.SuccessReport("MouseOver ",2768 " MouserOver Action is Done on " + locatorName);2769 }2770 }*/2771 }2772 2773 public boolean waitForTitlePresent(By locator) throws Throwable {2774 boolean flag = false;2775 boolean bValue = false;2776 try {2777 for (int i = 0; i < 200; i++) {2778 if (driver.findElements(locator).size() > 0) {2779 flag = true;2780 bValue = true;2781 break;2782 } else {2783 driver.wait(50);2784 }2785 }2786 } catch (Exception e) {2787 e.printStackTrace();2788 } finally {2789 if (!flag) {2790 extentLogs.fail("WaitForTitlePresent ", "Title is wrong");2791 } else if (flag) {2792 extentLogs.pass("WaitForTitlePresent ",2793 "Launched successfully expected Title ");2794 }2795 }2796 return bValue;2797 }2798 2799 2800 /**2801 * @author Cigniti Select a value from Dropdown using send keys.2802 *2803 * @param locator2804 * : Action to be performed on element (Get it from Object2805 * repository)2806 * @param value2807 * : Value wish type in dropdown list2808 * @param locatorName2809 * : Meaningful name to the element (Ex:Year Dropdown, items2810 * Listbox etc..)2811 * @return true, if successful2812 * @throws Throwable2813 * the throwable2814 */2815 public boolean selectBySendkeys(By locator, String value, String locatorName) throws Throwable {2816 boolean flag = false;2817 try {2818 WebDriverWait wait = new WebDriverWait(this.driver, 60);2819 ScrollToElementVisible(locator);2820 wait.until(ExpectedConditions.elementToBeClickable(locator));2821 if (CommonVariables.DeviceName.get().equalsIgnoreCase("ie")2822 || CommonVariables.DeviceName.get().equalsIgnoreCase("safari")) {2823 this.driver.findElement(locator).click();2824 Select drp = new Select(this.driver.findElement(locator));2825 drp.selectByVisibleText(value);2826 } else {2827 this.driver.findElement(locator).sendKeys(value);2828 }2829 fluentWait(30, 6);2830 flag = true;2831 } catch (Exception e) {2832 extentLogs.error("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName2833 + " due to exception - " + e.getLocalizedMessage());2834 flag = false;2835 } finally {2836 if (flag == false) {2837 extentLogs.fail("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName);2838 } else if (flag == true) {2839 extentLogs.pass("Select", "'" + value + "'" + "is selected from the DropDown " + locatorName);2840 }2841 }2842 return flag;2843 }2844 /**2845 * @author Cigniti select value from DropDown by using selectByIndex.2846 * @param locator:2847 * Action to be performed on element (Get it from Object2848 * repository)2849 * @param index:2850 * Index of value wish to select from dropdown list.2851 * @param locatorName:2852 * Meaningful name to the element (Ex:Year Dropdown, items2853 * Listbox etc..)2854 * @return true, if successful2855 * @throws Throwable2856 * the throwable2857 */2858 public boolean selectByIndex(By locator, int index, String locatorName) throws Throwable {2859 boolean flag = false;2860 try {2861 WebDriverWait wait = new WebDriverWait(this.driver, 60);2862 ScrollToElementVisible(locator);2863 wait.until(ExpectedConditions.elementToBeClickable(locator));2864 Select s = new Select(this.driver.findElement(locator));2865 s.selectByIndex(index);2866 flag = true;2867 } catch (Exception e) {2868 extentLogs.error("Select", " Option at index " + index + " is Not selected from the DropDown" + locatorName2869 + " due to exception - " + e.getLocalizedMessage());2870 flag = false;2871 } finally {2872 if (flag == false) {2873 extentLogs.fail("Select",2874 " Option at index " + index + " is not Selected from the DropDown" + locatorName);2875 } else if (flag == true) {2876 extentLogs.pass("Select", " Option at index " + index + " is Selected from the DropDown" + locatorName);2877 }2878 }2879 return flag;2880 }2881 /**2882 * @description: waitForVisibilityOfElement2883 * @param locator2884 * @param locatorName2885 * @param timeOutInSeconds2886 * @return2887 * @throws Throwable2888 */2889 public boolean waitForVisibilityOfElement(By locator, String locatorName, long timeOutInSeconds) throws Throwable {2890 try {2891 WebDriverWait wait = new WebDriverWait(this.driver, timeOutInSeconds);2892 wait.until(ExpectedConditions.visibilityOfElementLocated(locator));2893 this.driver.findElement(locator);2894 return true;2895 } catch (Exception e) {2896 e.printStackTrace();2897 return false;2898 }2899 }2900 /**2901 * @author Cigniti2902 * @description: Get all the options from drop down list2903 * @param locator2904 * @param value2905 * @param locatorName2906 * @return2907 * @throws Throwable2908 */2909 public List<String> getAllOptionsFromDropdown(By locator, String locatorName) throws Throwable {2910 try {2911 Select dropdown = new Select(this.driver.findElement(locator));2912 List<WebElement> optionsList = dropdown.getOptions();2913 List<String> optionNamesList = new ArrayList<String>();2914 for (WebElement option : optionsList) {2915 optionNamesList.add(option.getText());2916 }2917 return optionNamesList;2918 } catch (Exception e) {2919 return null;2920 }2921 }2922 /**2923 * @author Cigniti2924 * @description: Verify alert present or not2925 * @return true, if successful2926 * @throws Throwable2927 * the throwable2928 * @return: Boolean (True: If alert preset, False: If no alert)2929 */2930 public boolean JSAcceptAlert() throws Throwable {2931 boolean flag = false;2932 try {2933 JavascriptExecutor executor = (JavascriptExecutor) this.driver;2934 executor.executeScript("confirm = function(message){return true;};");2935 executor.executeScript("alert = function(message){return true;};");2936 executor.executeScript("prompt = function(message){return true;}");2937 flag = true;2938 } catch (Exception e) {2939 extentLogs.fail("Accept Alert", "Failed to accept alert due to execption - " + e.getLocalizedMessage());2940 } finally {2941 if (flag == false) {2942 extentLogs.fail("Accept Alert", "Failed to accept alert.");2943 return flag;2944 } else if (flag == true) {2945 extentLogs.fail("Accept Alert", "Alert accepted successfully.");2946 return flag;2947 }2948 }2949 return flag;2950 }2951 public boolean selectByValue(By locator, String value,2952 String locatorName) throws Throwable {2953 boolean flag = false;2954 try {2955 Select s = new Select(driver.findElement(locator));2956 s.selectByValue(value);2957 flag = true;2958 return true;2959 } catch (Exception e) {2960 Assert.assertTrue(flag,"Option with value attribute " + value2961 + " is Not Selected from the DropDown "2962 + locatorName);2963 e.printStackTrace();2964 return false;2965 } finally {2966 if (!flag) {2967 extentLogs.fail("Select",2968 "Option with value attribute " + value2969 + " is Not Select from the DropDown "2970 + locatorName);2971 } else if ( flag) {2972 extentLogs.pass("Select ",2973 "Option with value attribute " + value2974 + " is Selected from the DropDown "2975 + locatorName);2976 }2977 }2978 }2979 2980 public String getSelectedOption(By locator,2981 String locatorName) throws Throwable {2982 String strSelectdOption="";2983 boolean flag = false;2984 try {2985 Select s = new Select(driver.findElement(locator));2986 strSelectdOption=s.getFirstSelectedOption().getText();2987 flag = true;2988 return strSelectdOption;2989 } catch (Exception e) {2990 return strSelectdOption;2991 } finally {2992 if (!flag) {2993 extentLogs.fail("Get Selected Value","Not Able to Get Selected Value from the DropDown " + locatorName);2994 } else if (flag) {2995 extentLogs.pass("Get Selected Value ",strSelectdOption + " is Selected from the DropDown " + locatorName);2996 }2997 }2998 }2999 3000 3001 /**3002 * @author Cigniti3003 * @description: Switch to window3004 * @param driver3005 * @return3006 */3007 public static String switchToLatestWindow(WebDriver driver) {3008 String newWindowHandle = null;3009 try {3010 Iterator<String> allWindowHandles = driver.getWindowHandles().iterator();3011 while (allWindowHandles.hasNext()) {3012 newWindowHandle = allWindowHandles.next();3013 driver.switchTo().window(newWindowHandle);3014 }3015 } catch (Exception e) {3016 e.printStackTrace();3017 }3018 return newWindowHandle;3019 }3020 /**3021 * @author Cigniti3022 * @description : Set Window Handles3023 */3024 public void SetWindowHandles() {3025 try {3026 Thread.sleep(2000);3027 } catch (InterruptedException e1) {3028 }3029 try {3030 // Retrieve handles for all opened browser windows3031 if (appiumDriver != null && this.driver != null) {3032 /*3033 * arrKnownBrowserHwnd= appiumDriver.getContextHandles();3034 */} else {3035 arrKnownBrowserHwnd = driver.getWindowHandles();3036 }3037 if (appiumDriver == null) {3038 if (arrKnownBrowserHwnd.size() >= 1) {3039 for (String winHandle : arrKnownBrowserHwnd) {3040 hwndMostRecentWindow = winHandle; // Set variable value3041 // to the newly3042 // opened window3043 }3044 } else if (arrKnownBrowserHwnd.size() == 0) {3045 // No window appeared3046 hwndMostRecentWindow = null;3047 }3048 }3049 } catch (Exception e) {3050 System.out.println(e.getMessage());3051 }3052 }3053 /**3054 * @author Cigniti3055 * @description : Switch to most recent browser3056 * @return3057 */3058 public String switchToMostRecentBrowser() {3059 return switchToMostRecentBrowser("");3060 }3061 /**3062 * @author Cigniti3063 * @description : Switch to most recent browser with title3064 * @param windowTitle3065 * @return3066 */3067 public String switchToMostRecentBrowser(String windowTitle) {3068 try {3069 try {3070 Thread.sleep(1000);3071 } catch (InterruptedException excep) {3072 }3073 ;3074 SetWindowHandles();3075 if (windowTitle.isEmpty()) {3076 if (appiumDriver != null && this.driver != null) {3077 /*3078 * appiumDriver.context(hwndMostRecentWindow); this.driver =3079 * appiumDriver; driver = new3080 * EventFiringWebDriver(this.driver); eventListener = null;3081 * eventListener = new WebDriverListeners(driver);3082 * driver.register(eventListener);3083 */} else {3084 driver.getWrappedDriver().switchTo().window(hwndMostRecentWindow);3085 }3086 // If its IE browser and locally running, set focus as well3087 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("false")) {3088 activateCurrentBrowserWindow();3089 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()3090 .contains("false")) {3091 activateCurrentBrowserWindow();3092 }3093 } else {3094 if (appiumDriver != null && this.driver != null) {3095 /*3096 * appiumDriver.context(windowTitle.trim()); this.driver =3097 * appiumDriver; driver = new3098 * EventFiringWebDriver(this.driver); eventListener = null;3099 * eventListener = new WebDriverListeners(driver);3100 * driver.register(eventListener);3101 */} else {3102 windowTitle.trim().toLowerCase();3103 for (String winHandle : arrKnownBrowserHwnd) {3104 if (driver.switchTo().window(winHandle).getTitle().trim().toLowerCase().contains(windowTitle)) {3105 WebdriverWaitForPage();3106 break;3107 }3108 }3109 }3110 }3111 } catch (Exception e) {3112 return null;3113 }3114 return hwndMostRecentWindow;3115 }3116 /**3117 * @author Cigniti3118 * @description : Activate current browser window3119 * @return3120 */3121 public String activateCurrentBrowserWindow() {3122 // Try to switch to most recent browser window, if require3123 return hwndMostRecentWindow;3124 }3125 /**3126 * @author Cigniti3127 * @description : open application using url3128 * @param url3129 */3130 public void OpenApplication(String url) {3131 OpenUrl(url);3132 }3133 /**3134 * @author Cigniti3135 * @description : Open url3136 * @param url3137 * @return3138 */3139 public boolean OpenUrl(String url) {3140 try {3141 driverStartfailureCount = 1;3142 if (CommonVariables.TestCaseLog.get() != null) {3143 CommonVariables.TestClassLog.get().info("Info: navigating URL : '" + url + "'");3144 } else {3145 CommonVariables.TestClassLog.get().info("Info: navigating URL : '" + url + "'");3146 }3147 driver.navigate().to(url);3148 return true;3149 } catch (org.openqa.selenium.NoSuchElementException e) {3150 if (AcceptAlert()) {3151 driver.navigate().to(url);3152 try {3153 Thread.sleep(15000);3154 } catch (InterruptedException e1) {3155 }3156 return true;3157 } else {3158 extentLogs.info("Open URL",3159 "caught 'NoSuchElementException' exception while try to open '" + url + "'.");3160 if (CommonVariables.TestCaseLog.get() != null) {3161 CommonVariables.TestClassLog.get()3162 .info("Info: caught 'NoSuchElementException' exception while try to open '" + url + "'.");3163 } else {3164 CommonVariables.TestClassLog.get()3165 .info("Info: caught 'NoSuchElementException' exception while try to open '" + url + "'.");3166 }3167 }3168 throw new NoSuchElementException("");3169 } catch (org.openqa.selenium.UnhandledAlertException e) {3170 if (AcceptAlert()) {3171 driver.navigate().to(url);3172 try {3173 Thread.sleep(15000);3174 } catch (InterruptedException e1) {3175 }3176 return true;3177 }3178 extentLogs.info("Open URL", "caught 'UnhandledAlertException' exception while try to open '" + url + "'.");3179 throw new UnhandledAlertException("");3180 } catch (TimeoutException e1) {3181 extentLogs.info("Open URL", "Timed out receiving message from renderer.");3182 this.RefreshBrowser();3183 throw new TimeoutException();3184 } catch (Exception e) {3185 AcceptAlert();3186 extentLogs.info("Open URL",3187 "Failed to open Url. Err : " + e.getMessage() + "Stace track" + e.getStackTrace());3188 return false;3189 }3190 }3191 /**3192 * @author Cigniti3193 * @description : open url using SupressCredential for BMP3194 */3195 public void suppressCredential() {3196 if (ConfigManager.getProperties().getProperty("IsBrowserMobProxyRequire").trim().equalsIgnoreCase("yes")) {3197 Boolean credentials = false;3198 if (ConfigManager.getProperties().getProperty("isBMPAuthenticationRequired").trim()3199 .equalsIgnoreCase("yes")) {3200 credentials = ConfigManager.getProperties().getProperty("urlSuppressCredential").trim().contains("@");3201 }3202 if (credentials) {3203 String url = ConfigManager.getProperties().getProperty("urlSuppressCredential");3204 url = url.replace("https://", "http://");3205 OpenUrl(url);3206 url = url.replace("http://", "https://");3207 OpenUrl(url);3208 }3209 } else {3210 ConfigManager.getProperties().setProperty("urlSuppressCredential",3211 ConfigManager.getProperties().getProperty("urlSuppressCredential"));3212 }3213 }3214 /**3215 * @author Cigniti3216 * @description: Get WebElement attribute value3217 * @param objWebElement3218 * @param attribute3219 * @return3220 */3221 public boolean checkRegularExpression(String pattern, String actual)3222 throws Throwable {3223 boolean flag = false;3224 try {3225 Pattern patternRegex;3226 Matcher matcher;3227 patternRegex = Pattern.compile(pattern);3228 matcher = patternRegex.matcher(actual);3229 flag = matcher.matches();3230 } catch (Exception e) {3231 return false;3232 }3233 return flag;3234 }3235 3236 /**3237 * @author Cigniti3238 * @description: Get WebElement attribute value3239 * @param objWebElement3240 * @param attribute3241 * @return3242 */3243 public boolean verifyElementAbsent(By by, String locatorName)3244 throws Throwable {3245 boolean flag = true;3246 try {3247 driver.findElement(by);3248 flag = false;3249 return false;3250 } catch (Exception e) {3251 extentLogs.pass("Verify Element is NOT displayed",3252 "Element: <b>" + locatorName + " </b> is <b> NOT </b> displayed");3253 return true;3254 } finally {3255 if (!flag) {3256 extentLogs.fail("Verify Element is NOT displayed",3257 "Element: <b>" + locatorName + " </b> is <b> displayed</b>");3258 Assert.assertTrue(flag,"Failed to Assert Element is absent"+ locatorName);3259 } else if (flag) {3260 extentLogs.pass("Verify Element is NOT displayed",3261 "Element: <b>" + locatorName + " </b> is <b> NOT </b> displayed");3262 return flag;3263 }3264 }3265 }3266 /**3267 * @author Cigniti3268 * @description: Get switchToFrameByIndex3269 * @param objWebElement3270 * @param attribute3271 * @return3272 */3273 public boolean switchToFrameByIndex(int index) throws Throwable {3274 boolean flag = false;3275 try {3276 driver.switchTo().frame(index);3277 flag = true;3278 return true;3279 } catch (Exception e) {3280 return false;3281 } finally {3282 if (!flag) {3283 extentLogs.fail("SelectFrame ", " Frame with index "3284 + index + " is not selected");3285 } else if ( flag) {3286 extentLogs.pass("SelectFrame ", " Frame with index "3287 + index + " is selected");3288 }3289 }3290 }3291 3292 /**3293 * @author Cigniti3294 * @description: Get WebElement attribute value3295 * @param objWebElement3296 * @param attribute3297 * @return3298 */3299 public boolean assertText(By by, String text) throws Throwable {3300 boolean flag = false;3301 try {3302 Assert.assertEquals(getElementText(by, text).trim(), text.trim());3303 flag = true;3304 return true;3305 } catch (Exception e) {3306 e.printStackTrace();3307 return false;3308 } finally {3309 if (!flag) {3310 extentLogs.fail("AssertText ", text3311 + " is not present in the element ");3312 return false;3313 } else if (flag) {3314 extentLogs.pass("AssertText ", text3315 + " is present in the element ");3316 }3317 }3318 }3319 3320 3321 /**3322 * @author Cigniti3323 * @description: Get WebElement attribute value3324 * @param objWebElement3325 * @param attribute3326 * @return3327 */3328 public boolean switchToDefaultFrame() throws Throwable {3329 boolean flag = false;3330 try {3331 driver.switchTo().defaultContent();3332 flag = true;3333 return true;3334 } catch (Exception e) {3335 e.printStackTrace();3336 return false;3337 } finally {3338 if (!flag) {3339 extentLogs.fail("SelectFrame ",3340 " The Frame is not selected");3341 } else if (flag) {3342 extentLogs.pass("SelectFrame ",3343 " Frame with Name is selected");3344 }3345 }3346 }3347 3348 /**3349 * @author Cigniti3350 * @description: Get WebElement attribute value3351 * @param objWebElement3352 * @param attribute3353 * @return3354 */3355 public String GetElementAttributeValue(WebElement objWebElement, String attribute) {3356 try {3357 return objWebElement.getAttribute(attribute);3358 } catch (org.openqa.selenium.NoSuchElementException e) {3359 extentLogs.error("Attribute Value",3360 "caught 'ElementNotFoundException' exception. Failed to get attribute - '" + attribute + "' on "3361 + driver.getTitle() + "' page.");3362 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3363 "Error: caught 'ElementNotFoundException' exception. Failed to get '" + attribute + "' value for '"3364 + objWebElement + "' on '" + driver.getTitle() + "' page");3365 return "";3366 } catch (ElementNotVisibleException e) {3367 extentLogs.error("Attribute Value",3368 "caught 'ElementNotVisibleException' exception. Failed to get attribute - '" + attribute + "' on "3369 + driver.getTitle() + "' page.");3370 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3371 "Error: caught 'ElementNotVisibleException' exception. Failed to get '" + attribute3372 + "' value for '" + objWebElement + "' on '" + driver.getTitle() + "' page");3373 return "";3374 } catch (WebDriverException e) {3375 extentLogs.error("Attribute Value", "caught 'WebDriverException' exception. Failed to attribute - '"3376 + attribute + "' on " + driver.getTitle() + "' page.");3377 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3378 "Error: caught 'WebDriverException' exception. Failed to get '" + attribute + "' value for '"3379 + objWebElement + "' on '" + driver.getTitle() + "' page");3380 return "";3381 } catch (NullPointerException e5) {3382 extentLogs.error("Attribute Value", "Caught 'NullPointerException' exception while try to get attribute - '"3383 + attribute + "' on " + driver.getTitle() + "' page.");3384 CommonVariables.TestCaseLog.get()3385 .info("Info. Caught 'NullPointerException' exception while try to get Element Attribute ("3386 + attribute + ") value on '" + driver.getTitle() + "'.");3387 return "";3388 } catch (Exception e) {3389 extentLogs.error("Attribute Value", "Failed to attribute - '" + attribute + "' on " + driver.getTitle()3390 + "' page due to exception - " + e.getMessage());3391 CommonVariables.TestCaseLog.get()3392 .error("Failed to get '" + attribute + "' value. Error Message: " + e.getMessage());3393 return "";3394 }3395 }3396 /**3397 * @author Cigniti3398 * @description: check the existence of an element in DOM3399 * @param by3400 * @param timeoutInSeconds3401 * @return3402 */3403 public boolean IsElementExist(By by, Optional<Long> timeoutInSeconds) {3404 long timeout = timeoutInSeconds.isPresent() ? timeoutInSeconds.get() : 999999;3405 if (timeout == 999999) {3406 timeout = Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut"));3407 }3408 try {3409 AcceptAlert();3410 if (FindElement(by, Optional.of(timeout)) != null) {3411 extentLogs.pass("Presence of Element", "Element exists on '" + driver.getTitle() + "' page.");3412 if (CommonVariables.TestCaseLog.get() != null) {3413 CommonVariables.TestCaseLog.get()3414 .info("Info. Element '" + by + "' exists on '" + driver.getTitle() + "' page.");3415 } else {3416 CommonVariables.TestClassLog.get()3417 .info("Info. Element '" + by + "' exists on '" + driver.getTitle() + "' page.");3418 }3419 return true;3420 } else {3421 extentLogs.fail("Presence of Element", "Element does not exist on '" + driver.getTitle() + "' page.");3422 if (CommonVariables.TestCaseLog.get() != null) {3423 CommonVariables.TestCaseLog.get()3424 .info("Info. Element '" + by + "' deos not exist on '" + driver.getTitle() + "' page.");3425 } else {3426 CommonVariables.TestClassLog.get()3427 .info("Info. Element '" + by + "' deos not exist on '" + driver.getTitle() + "' page.");3428 }3429 return false;3430 }3431 } catch (NullPointerException e) {3432 extentLogs.error("Presence of Element",3433 "Element not exist on " + driver.getTitle() + "' page due to exception - " + e.getMessage());3434 throw e;3435 } catch (NoSuchElementException e) {3436 extentLogs.error("Presence of Element",3437 "Element not exist on " + driver.getTitle() + "' page due to exception - " + e.getMessage());3438 throw e;3439 } catch (Exception e) {3440 extentLogs.error("Presence of Element",3441 "Element not exist on " + driver.getTitle() + "' page due to exception - " + e.getMessage());3442 throw e;3443 }3444 }3445 /**3446 * @author Cigniti3447 * @description : Get URL3448 * @return3449 */3450 public String GetURl() {3451 try {3452 extentLogs.pass("Get URL", "Successfully navigate to url - '" + driver.getCurrentUrl() + "'.");3453 return driver.getCurrentUrl();3454 } catch (StaleElementReferenceException e2) {3455 extentLogs.error("Get URL", "caught 'StaleElementReferenceException' exception while getting '"3456 + driver.getTitle() + "' page.");3457 CommonVariables.TestCaseLog.get()3458 .error("Info: caught 'StaleElementReferenceException' exception while getting '" + driver.getTitle()3459 + "' page title");3460 return "";3461 } catch (org.openqa.selenium.UnhandledAlertException e) {3462 extentLogs.error("Get URL",3463 "caught 'UnhandledAlertException' exception while getting '" + driver.getTitle() + "' page.");3464 CommonVariables.TestCaseLog.get().error("Info: caught 'UnhandledAlertException' exception while getting '"3465 + driver.getTitle() + "' page title");3466 return "";3467 }3468 }3469 /**3470 * @author Cigniti3471 * @description : Navigate Back3472 */3473 public void NavigateBack() {3474 try {3475 driver.navigate().back();3476 extentLogs.pass("Navigate Back", "Successfully navigate back to page - '" + driver.getTitle() + "' page.");3477 try {3478 Thread.sleep(2000);3479 } catch (InterruptedException e) {3480 }3481 } catch (org.openqa.selenium.UnhandledAlertException e) {3482 extentLogs.error("Navigate Back", "caught 'UnhandledAlertException' exception while navigating back from '"3483 + driver.getTitle() + "' page.");3484 CommonVariables.TestCaseLog.get()3485 .info("Info: caught 'UnhandledAlertException' exception while navigating back from '"3486 + driver.getTitle() + "' page");3487 AcceptAlert();3488 } catch (org.openqa.selenium.StaleElementReferenceException e) {3489 extentLogs.error("Navigate Back",3490 "caught 'StaleElementReferenceException' exception while navigating back from '" + driver.getTitle()3491 + "' page.");3492 CommonVariables.TestCaseLog.get()3493 .error("Info: caught 'StaleElementReferenceException' exception while navigating back from '"3494 + driver.getTitle() + "' page");3495 AcceptAlert();3496 }3497 }3498 /**3499 * @author Cigniti3500 * @description : Refresh browser3501 */3502 public void RefreshBrowser() {3503 try {3504 driver.navigate().refresh();3505 extentLogs.pass("Refresh Browser",3506 "Successfully refresh browser at page - '" + driver.getTitle() + "' page.");3507 try {3508 Thread.sleep(6000);3509 } catch (InterruptedException e) {3510 AcceptAlert();3511 }3512 } catch (org.openqa.selenium.UnhandledAlertException e) {3513 extentLogs.error("Refresh Browser",3514 "caught 'UnhandledAlertException' exception while refresh '" + driver.getTitle() + "' page");3515 if (CommonVariables.TestCaseLog.get() != null) {3516 CommonVariables.TestCaseLog.get()3517 .info("Info: caught 'UnhandledAlertException' exception while refresh '" + driver.getTitle()3518 + "' page");3519 } else {3520 CommonVariables.TestClassLog.get()3521 .info("Info: caught 'UnhandledAlertException' exception while refresh '" + driver.getTitle()3522 + "' page");3523 }3524 AcceptAlert();3525 } catch (org.openqa.selenium.StaleElementReferenceException e) {3526 extentLogs.error("Refresh Browser", "caught 'StaleElementReferenceException' exception while refresh '"3527 + driver.getTitle() + "' page.");3528 if (CommonVariables.TestCaseLog.get() != null) {3529 CommonVariables.TestCaseLog.get()3530 .info("Info: caught 'StaleElementReferenceException' exception while refresh '"3531 + driver.getTitle() + "' page");3532 } else {3533 CommonVariables.TestClassLog.get()3534 .info("Info: caught 'StaleElementReferenceException' exception while refresh '"3535 + driver.getTitle() + "' page");3536 }3537 AcceptAlert();3538 } catch (org.openqa.selenium.UnsupportedCommandException e) {3539 extentLogs.error("Refresh Browser",3540 "caught 'UnsupportedCommandException' exception while refresh '" + driver.getTitle() + "' page.");3541 if (CommonVariables.TestCaseLog.get() != null) {3542 CommonVariables.TestCaseLog.get()3543 .info("Info: caught 'UnsupportedCommandException' exception while refresh '" + driver.getTitle()3544 + "' page");3545 } else {3546 CommonVariables.TestClassLog.get()3547 .info("Info: caught 'UnsupportedCommandException' exception while refresh '" + driver.getTitle()3548 + "' page");3549 }3550 try {3551 driver.getWrappedDriver().navigate().refresh();3552 } catch (Exception e2) {3553 extentLogs.error("Refresh Browser",3554 "caught 'Exception' exception while refresh '" + driver.getTitle() + "' page.");3555 if (CommonVariables.TestCaseLog.get() != null) {3556 CommonVariables.TestCaseLog.get()3557 .info("Info: caught 'Exception' exception while refresh '" + driver.getTitle() + "' page");3558 } else {3559 CommonVariables.TestClassLog.get()3560 .info("Info: caught 'Exception' exception while refresh '" + driver.getTitle() + "' page");3561 }3562 driver.navigate().to(driver.getCurrentUrl());3563 try {3564 Thread.sleep(6000);3565 } catch (InterruptedException e1) {3566 AcceptAlert();3567 }3568 }3569 try {3570 Thread.sleep(6000);3571 } catch (InterruptedException e1) {3572 AcceptAlert();3573 }3574 }3575 }3576 /**3577 * @author Cigniti3578 * @description : get Page Title3579 * @return3580 */3581 public String GetPageTitle() {3582 try {3583 return driver.getTitle();3584 } catch (org.openqa.selenium.UnhandledAlertException e) {3585 extentLogs.error("Page Title",3586 "caught 'UnhandledAlertException' exception while getting '" + driver.getTitle() + "' page.");3587 CommonVariables.TestCaseLog.get().info("Info: caught 'UnhandledAlertException' exception while getting '"3588 + driver.getTitle() + "' page title");3589 if (AcceptAlert()) {3590 return driver.getTitle();3591 }3592 return null;3593 } catch (org.openqa.selenium.StaleElementReferenceException e) {3594 extentLogs.error("Page Title", "caught 'StaleElementReferenceException' exception while getting '"3595 + driver.getTitle() + "' page.");3596 CommonVariables.TestCaseLog.get()3597 .info("Info: caught 'StaleElementReferenceException' exception while getting '" + driver.getTitle()3598 + "' page title");3599 try {3600 if (AcceptAlert()) {3601 return driver.getTitle();3602 } else {3603 return null;3604 }3605 } catch (WebDriverException ex) {3606 return null;3607 }3608 } catch (org.openqa.selenium.TimeoutException e) {3609 extentLogs.error("Page Title",3610 "caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page.");3611 CommonVariables.TestCaseLog.get().info(3612 "Info: caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page title");3613 return null;3614 }3615 }3616 /**3617 * @author Cigniti3618 * @description : Get collection webelements using Find Elements3619 * @param by3620 * @param timeoutInSeconds3621 * @return3622 */3623 public List<WebElement> FindElements(By by, Optional<Long> timeoutInSeconds) {3624 long timeout = timeoutInSeconds.isPresent() ? timeoutInSeconds.get() : -1;3625 if (timeout == -1) {3626 timeout = Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut"));3627 }3628 List<WebElement> webElement;3629 try {3630 webElement = (new WebDriverWait(driver, timeout))3631 .until(ExpectedConditions.presenceOfAllElementsLocatedBy(by));3632 extentLogs.pass("Find Elements", "Successfully find matched elements on '" + driver.getTitle() + "' page.");3633 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3634 "Info: Successfully find matched elements by '" + by + "' on '" + driver.getTitle() + "' page.");3635 return webElement;3636 } catch (org.openqa.selenium.UnhandledAlertException e) {3637 if (AcceptAlert()) {3638 return FindElements(by, timeoutInSeconds);3639 }3640 extentLogs.error("Find Elements",3641 "caught 'UnhandledAlertException' exception while finding an elements on '" + driver.getTitle()3642 + "' page.");3643 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3644 "Info: caught 'UnhandledAlertException' exception while finding '" + by + "' element on '"3645 + driver.getTitle() + "' page");3646 throw new UnhandledAlertException("");3647 } catch (StaleElementReferenceException e2) {3648 if (AcceptAlert()) {3649 return FindElements(by, timeoutInSeconds);3650 }3651 extentLogs.error("Find Elements", "caught 'StaleElementReferenceException' exception while getting '"3652 + driver.getTitle() + "' page title.");3653 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3654 "Info: caught 'StaleElementReferenceException' exception while getting '" + driver.getTitle()3655 + "' page title");3656 throw new StaleElementReferenceException("");3657 } catch (TimeoutException e3) {3658 if (AcceptAlert()) {3659 return FindElements(by, timeoutInSeconds);3660 }3661 extentLogs.error("Find Elements",3662 "caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page title.");3663 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3664 "Info: caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page title");3665 throw new TimeoutException();3666 } catch (NoSuchElementException e4) {3667 if (AcceptAlert()) {3668 return FindElements(by, timeoutInSeconds);3669 }3670 extentLogs.error("Find Elements",3671 "caught 'NoSuchElement' exception while getting '" + driver.getTitle() + "' page title.");3672 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3673 "Info: caught 'NoSuchElement' exception while getting '" + driver.getTitle() + "' page title");3674 throw new NoSuchElementException("No such Element");3675 }3676 }3677 /**3678 * @author Cigniti3679 * @Description: Accept alert pop-ups3680 * @return3681 */3682 public boolean AcceptAlert() {3683 try {3684 Alert alert = driver.switchTo().alert();3685 alert.accept();3686 return true;3687 } catch (Exception e) {3688 return false;3689 }3690 }3691 /**3692 * @author Cigniti3693 * @description : Decline Alert3694 * @return3695 */3696 public boolean declineAlert() {3697 try {3698 Alert alert = driver.switchTo().alert();3699 alert.dismiss();3700 return true;3701 } catch (Exception e) {3702 return false;3703 }3704 }3705 /**3706 * @author Cigniti3707 * @description : Wait for Element Visible3708 * @param by3709 * @param waitTime3710 */3711 public void WaitForElementVisible(final By by, int waitTime) {3712 wait = new WebDriverWait(driver, waitTime);3713 try {3714 wait.until(ExpectedConditions.visibilityOfElementLocated(by));3715 extentLogs.pass("Element Visible", "Element visibile at '" + driver.getTitle() + "' page.");3716 } catch (TimeoutException e) {3717 extentLogs.error("Element Visible",3718 "caught 'TimeoutException' exception while wait for element visibility at '" + driver.getTitle()3719 + "' page.");3720 if (CommonVariables.TestCaseLog.get() != null) {3721 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3722 "Info: caught 'TimeoutException' exception while wait for element ( " + by.toString()3723 + " ) visibility at '" + driver.getTitle() + "' page");3724 } else {3725 CommonVariables.TestClassLog.get()3726 .info("Info: caught 'TimeoutException' exception while wait for element ( " + by.toString()3727 + " ) visibility at '" + driver.getTitle() + "' page");3728 }3729 }3730 }3731 /**3732 * @author Cigniti Description: capture screenshot3733 * @param driver3734 * @param fileName3735 */3736 private void takesScreenShot(WebDriver driver, String fileName) {3737 WebDriver driverScreenShot = new Augmenter().augment(driver);3738 File scrFile = ((TakesScreenshot) driverScreenShot).getScreenshotAs(OutputType.FILE);3739 try {3740 FileUtils.copyFile(scrFile, new File(fileName));3741 } catch (IOException e) {3742 e.printStackTrace();3743 }3744 }3745 /**3746 * @author Cigniti3747 * @description : Save Screenshot3748 * @param ImgPath3749 * @return3750 */3751 public static boolean saveScreenshot(String ImgPath) {3752 try {3753 // This is the ultimate implementation. Right now, we are able to3754 // get the joined images in chrome ONLY.3755 if (GetDriverInfo().get("DriverName").contains("Chrome")) {3756 try {3757 saveFullScreenShot(ImgPath);3758 return true;3759 } catch (Exception e) {3760 System.out.println(3761 "Getting exception while taking full screenshot. Exception message:" + e.getStackTrace());3762 }3763 }3764 // This needs to be removed if we are able to get the joined images3765 // in other browsers3766 if (CommonVariables.getDriver() != null && !driver.getWrappedDriver().getWindowHandle().isEmpty()) {3767 File screenshot = null;3768 if (ConfigManager.getProperties().getProperty("seleniumGrid").trim().equalsIgnoreCase("true")) {3769 org.openqa.selenium.WebDriver augmentedDriver = new Augmenter()3770 .augment(CommonVariables.getDriver());3771 try {3772 screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);3773 } catch (WebDriverException e) {3774 e.printStackTrace();3775 }3776 } else if (ConfigManager.getProperties().getProperty("cloudExecution").trim()3777 .equalsIgnoreCase("true")) {3778 org.openqa.selenium.WebDriver augmentedDriver = new Augmenter().augment(driver.getWrappedDriver());3779 try {3780 screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);3781 } catch (WebDriverException e) {3782 e.printStackTrace();3783 }3784 } else if (driver.getWrappedDriver().getClass().toString().toLowerCase().contains("chromedriver")3785 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("safari")3786 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("firefox")3787 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("internet")3788 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("ie")3789 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("edge")3790 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("Microsoft")3791 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("opera")3792 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("PhantomJS")3793 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("remotewebdriver")) {3794 screenshot = ((TakesScreenshot) driver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);3795 }3796 File screenshotfile = new File(ImgPath);3797 try {3798 FileUtils.copyFile(screenshot, screenshotfile);3799 if (driver.getWrappedDriver().getClass().toString().toLowerCase().contains("internet")3800 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("ie")) {3801 Thread.sleep(1500);3802 }3803 return true;3804 } catch (IOException e) {3805 e.printStackTrace();3806 }3807 }3808 } catch (Exception e) {3809 System.out.println();3810 e.printStackTrace();3811 return false;3812 }3813 return false;3814 }3815 /**3816 * @author Cigniti3817 * @description : Capture Full Screenshot3818 * @param ImgPath3819 */3820 public static void saveFullScreenShot(String ImgPath) {3821 CaptureScreenShot fullscreenshot = new CaptureScreenShot();3822 try {3823 fullscreenshot.seleniumCaptureBrowserScreenShot(driver, ImgPath);3824 } catch (InterruptedException | IOException e) {3825 // TODO Auto-generated catch block3826 e.printStackTrace();3827 }3828 }3829 /****************************************************************************************************************************3830 * Function Name : isElementEnabled() Description : Element is disabled or not3831 * 3832 * @param objLocator3833 * : Action to be performed on element (Get it from Object3834 * repository)3835 * @param strLocatorName3836 * : Meaningful name to the element (Ex:Login Button, UserName3837 * Textbox etc..)3838 * @return: boolean value (True: if the element is enabled, false: if it not3839 * enabled).3840 ****************************************************************************************************************************/3841 public boolean isElementEnabled(WebElement objLocator, String strLocatorName) throws Throwable {3842 Boolean blnFlag = false;3843 try {3844 if ((objLocator).isEnabled()) {3845 blnFlag = true;3846 extentLogs.pass("Web Locator Status", "Web locator is enabled for - '" + strLocatorName + "'.");3847 }3848 return blnFlag;3849 } catch (NoSuchElementException e) {3850 gStrErrMsg = e.getMessage();3851 return blnFlag;3852 } 3853 }3854 /****************************************************************************************************************************3855 * Function Name : isElementDisabled() Description : Element is disabled or not3856 * 3857 * @param objLocator3858 * : Action to be performed on element (Get it from Object3859 * repository)3860 * @param strLocatorName3861 * : Meaningful name to the element (Ex:Login Button, UserName3862 * Textbox etc..)3863 * @return: boolean value (True: if the element is enabled, false: if it not3864 * enabled).3865 ****************************************************************************************************************************/3866 public boolean isElementDisabled(WebElement objLocator, String strLocatorName) throws Throwable {3867 Boolean blnFlag = false;3868 try {3869 if (!(objLocator).isEnabled()) {3870 blnFlag = true;3871 extentLogs.pass("Web Locator Status", "Web locator is disabled for - '" + strLocatorName + "'.");3872 }3873 return blnFlag;3874 } catch (NoSuchElementException e) {3875 gStrErrMsg = e.getMessage();3876 return blnFlag;3877 } 3878 }3879 /**3880 * @author Cigniti3881 * @description : Is Element Visible in UI3882 * @param by3883 * @return3884 */3885 public boolean IsElementVisible(final By by) {3886 try {3887 wait = new WebDriverWait(driver, 1);3888 wait.until(ExpectedConditions.visibilityOfElementLocated(by));3889 if ((driver.findElement(by).getSize().height == 0) && (driver.findElement(by).getSize().width == 0)) {3890 return false;3891 } else {3892 return true;3893 }3894 } catch (Exception e) {3895 try {3896 if ((e.getClass().isInstance(new TimeoutException(""))3897 || getClass().isInstance(new ElementNotVisibleException("")))3898 || (e.getClass().isInstance(new NoSuchElementException("")))) {3899 if (ScrollToElementVisible(by)) {3900 wait.until(ExpectedConditions.visibilityOfElementLocated(by));3901 if ((driver.findElement(by).getSize().height == 0)3902 && (driver.findElement(by).getSize().width == 0)) {3903 return false;3904 } else {3905 return true;3906 }3907 } else {3908 throw e;3909 }3910 } else {3911 throw e;3912 }3913 } catch (Exception e1) {3914 if (e1.getCause().toString().contains("NoSuchElementException")) {3915 throw new NoSuchElementException("");3916 } else if (e1.getCause().toString().contains("ElementNotVisibleException")) {3917 throw new ElementNotVisibleException("");3918 } else if (e1.getCause().toString().contains("TimeoutException")) {3919 throw new TimeoutException();3920 } else {3921 throw e1;3922 }3923 }3924 }3925 }3926 /**3927 * @author Cigniti3928 * @description : Is Element Visible in UI3929 * @param by3930 * @return3931 */3932 public boolean IsElementVisible(WebElement element) {3933 try {3934 wait = new WebDriverWait(driver, 1);3935 wait.until(ExpectedConditions.visibilityOf(element));3936 if ((element.getSize().height == 0) && (element.getSize().width == 0)) {3937 return false;3938 } else {3939 return true;3940 }3941 } catch (Exception e) {3942 try {3943 if ((e.getClass().isInstance(new TimeoutException(""))3944 || getClass().isInstance(new ElementNotVisibleException("")))3945 || (e.getClass().isInstance(new NoSuchElementException("")))) {3946 if (ScrollToElementVisible(element)) {3947 wait.until(ExpectedConditions.visibilityOf(element));3948 if ((element.getSize().height == 0) && (element.getSize().width == 0)) {3949 return false;3950 } else {3951 return true;3952 }3953 } else {3954 throw e;3955 }3956 } else {3957 throw e;3958 }3959 } catch (Exception e1) {3960 if (e1.getCause().toString().contains("NoSuchElementException")) {3961 throw new NoSuchElementException("");3962 } else if (e1.getCause().toString().contains("ElementNotVisibleException")) {3963 throw new ElementNotVisibleException("");3964 } else if (e1.getCause().toString().contains("TimeoutException")) {3965 throw new TimeoutException();3966 } else {3967 throw e1;3968 }3969 }3970 }3971 }3972 /**3973 * @author Cigniti3974 * @description : Start Video3975 * @param element3976 */3977 public void StartVideo(WebElement element) {3978 try {3979 double browser_top_offset = 80;3980 if (GetDriverInfo().get("DriverName").contains("iphone")) {3981 browser_top_offset = 50;3982 } else if (GetDriverInfo().get("DriverName").contains("ipad")) {3983 browser_top_offset = 80;3984 }3985 RemoteWebElement remoteelem = ((RemoteWebElement) element);3986 JavascriptExecutor js = (JavascriptExecutor) driver;3987 String script = "return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)";3988 Long pageheight1 = (Long) js.executeScript(script);3989 Long pageheight2 = (Long) js.executeScript("return window.innerHeight");3990 Point eloc = remoteelem.getLocation();3991 double yloc = eloc.getY();3992 double elemheight = remoteelem.getSize().getHeight() / 2;3993 double yratio = (yloc + elemheight + browser_top_offset) / pageheight1;3994 HashMap<String, Double> tapObject = new HashMap<String, Double>();3995 tapObject.put("x", 0.5);3996 tapObject.put("y", yratio);3997 js.executeScript("mobile: tap", tapObject);3998 } catch (Exception e) {3999 }4000 }4001 /**4002 * @author Cigniti4003 * @description: scroll to top of the page4004 */4005 public void ScrollToTop() {4006 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("desktop")) {4007 try {4008 JavascriptExecutor js = (JavascriptExecutor) driver;4009 js.executeScript("window.scrollTo(0,0);");4010 } catch (Exception e) {4011 }4012 } else {4013 try {4014 JavascriptExecutor js = (JavascriptExecutor) driver;4015 js.executeScript("$('body').scrollTop(0);");4016 } catch (Exception e) {4017 System.out.println(4018 "Failed to Swipe on Top on Non-Desktop device. Check 'ScrollToTop' method under action library");4019 }4020 }4021 }4022 /**4023 * @author Cigniti4024 * @description: scroll page to bottom of the page4025 */4026 public void ScrollToBottom() {4027 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("desktop")) {4028 try {4029 JavascriptExecutor js = (JavascriptExecutor) driver;4030 js.executeScript("window.scrollTo(0,document.documentElement.scrollHeight);");4031 } catch (Exception e) {4032 }4033 } else {4034 JavascriptExecutor js = (JavascriptExecutor) driver;4035 int height_covered = 0, pageHeightLeft = 0;4036 Long pageheight1 = (Long) js.executeScript("return window.innerHeight");4037 Long maxPageHeight1 = (Long) js4038 .executeScript("return Math.max(document.documentElement.scrollHeight, document.body.scrollHeight,"4039 + "document.documentElement.clientHeight, window.innerHeight)");4040 float sections = (float) maxPageHeight1 / pageheight1;4041 int numberOfRows = (int) Math.ceil(sections);4042 int pageheight = pageheight1.intValue();4043 int maxPageHeight = maxPageHeight1.intValue();4044 for (int row = 0; row < numberOfRows; row++) {4045 pageHeightLeft = maxPageHeight - height_covered;4046 if ((pageHeightLeft < pageheight)) {4047 } else {4048 height_covered = height_covered + pageheight;4049 js.executeScript("window.scrollTo(0," + height_covered + ")");4050 }4051 }4052 }4053 }4054 /**4055 * @author Cigniti4056 * @description : Set GeoLocation with latitide and longitude4057 * @param latitude4058 * @param longitude4059 */4060 public void setGeoLocation(double latitude, double longitude) {4061 try {4062 if (GetDriverInfo().toString().toLowerCase().contains("ipad")4063 || GetDriverInfo().toString().toLowerCase().contains("iphone")4064 || GetDriverInfo().toString().toLowerCase().contains("android")) {4065 JavascriptExecutor js = (JavascriptExecutor) driver;4066 // AppiumDriver dr = (AppiumDriver) this.driver;4067 Location loc = new Location(latitude, longitude, 10);4068 appiumDriver.setLocation(loc);4069 try {4070 Thread.sleep(2000);4071 } catch (Exception e) {4072 }4073 } else if (ConfigManager.getProperties().getProperty("deviceType").contains("android")) {4074 System.out.println("Skipping location set..need to be impletemented on Android.");4075 }4076 } catch (Exception ex) {4077 ex.printStackTrace();4078 }4079 }4080 /**4081 * @author Cigniti4082 * @description : Set GeoLocation4083 */4084 public void setGeoLocation() {4085 setGeoLocation(Double.valueOf(ConfigManager.getProperties().getProperty("latitude").trim()),4086 Double.valueOf(ConfigManager.getProperties().getProperty("longitude").trim()));4087 }4088 /**4089 * @param driver4090 * Current driver instance, which is to be nullified.4091 * @param locationServiceEnabled.4092 * Permitted values are: true/false/ask4093 * @param latitude4094 * The latitude of the location to be mocked, if provided with 0,4095 * then this method will pick value from configuration file.4096 * @param longitude4097 * The longitude of the location to be mocked, if provided with4098 * 0, then this method will pick value from configuration file.4099 * @return driver Returns updated driver instance.4100 */4101 public WebDriver resetLocationCapability(WebDriver driver, String locationServiceEnabled, double latitude,4102 double longitude) {4103 if (ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("safari-mac")) {4104 if (locationServiceEnabled.trim().toLowerCase().contains("false")4105 || locationServiceEnabled.trim().toLowerCase().contains("ask")) {4106 throw new SkipException(4107 "Skipping because of can't handle location Pop-up. So set-up in Safari profile to share the location always.");4108 } else4109 return driver;4110 }4111 String previousUrl = "";4112 if (GetURl().toLowerCase().contains("http://") || GetURl().toLowerCase().contains("https://")) {4113 previousUrl = GetURl();4114 }4115 tearDown();4116 driver = null;4117 if (GetDriverInfo().toString().toLowerCase().contains("ipad")4118 | GetDriverInfo().toString().toLowerCase().contains("iphone")) {4119 initPropertiesFile();4120 if (locationServiceEnabled.trim().toLowerCase().contains("false")) {4121 this.locationServiceEnabled = false;4122 } else4123 this.locationServiceEnabled = true;4124 this.doFullReset = true;4125 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"));4126 this.driver = (EventFiringWebDriver) driver;4127 if (locationServiceEnabled != null && (!locationServiceEnabled.trim().toLowerCase().contains("false"))) {4128 if (locationServiceEnabled.trim().toLowerCase().contains("ask")) {4129 } else if (latitude == 0 && longitude == 0) {4130 setGeoLocation();4131 } else if (latitude != 0 && longitude != 0) {4132 setGeoLocation(latitude, longitude);4133 } else {4134 System.err.println("Invalid value under locationServiceEnabled flag. Can not start webdriver.");4135 }4136 }4137 if (previousUrl.isEmpty()) {4138 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));4139 } else {4140 if (!previousUrl.contains("@"))4141 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));4142 OpenUrl(previousUrl);4143 }4144 AcceptAlert();4145 try {4146 Thread.sleep(15000);4147 } catch (InterruptedException ex) {4148 }4149 } else if (GetDriverInfo().toString().toLowerCase().contains("chrome")) {4150 if (locationServiceEnabled.toLowerCase().contains("true")) {4151 this.chromeProfile = "browser-profile-location-boston";4152 this.locationServiceEnabled = true;4153 driver = instantiateDriver(CommonVariables.PlatformName.get() + "-" + CommonVariables.DeviceName.get());4154 } else if (locationServiceEnabled.toLowerCase().contains("false")) {4155 this.chromeProfile = "browser-profile-location-No";4156 driver = instantiateDriver(CommonVariables.PlatformName.get() + "-" + CommonVariables.DeviceName.get());4157 } else if (locationServiceEnabled.toLowerCase().contains("ask")) {4158 this.chromeProfile = "browser-profile-location-yes-ask";4159 driver = instantiateDriver(CommonVariables.PlatformName.get() + "-" + CommonVariables.DeviceName.get());4160 } else {4161 System.err.println("Invalid value under locationServiceEnabled flag. Can not start webdriver.");4162 }4163 if (driver != null) {4164 if (previousUrl.isEmpty()) {4165 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));4166 } else {4167 if (!previousUrl.contains("@"))4168 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));4169 OpenUrl(previousUrl);4170 }4171 AcceptAlert();4172 try {4173 Thread.sleep(10000);4174 } catch (InterruptedException ex) {4175 }4176 }4177 } else if (GetDriverInfo().toString().toLowerCase().contains("firefox")) {4178 if (locationServiceEnabled.toLowerCase().contains("true")) {4179 this.locationServiceEnabled = true;4180 this.firefoxProfilePath = "Firefox_profile_For_Location_Simulate";4181 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"));4182 } else if (locationServiceEnabled.toLowerCase().contains("false")) {4183 this.locationServiceEnabled = false;4184 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"));4185 } else if (locationServiceEnabled.toLowerCase().contains("ask")) {4186 this.locationServiceEnabled = true;4187 this.firefoxProfilePath = "Firefox_Profile__Ask_Location_To_Share";4188 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"));4189 } else {4190 System.err.println("Invalid value under locationServiceEnabled flag. Can not start webdriver.");4191 }4192 if (driver != null) {4193 if (previousUrl.isEmpty()) {4194 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));4195 } else {4196 if (!previousUrl.contains("@"))4197 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));4198 OpenUrl(previousUrl);4199 }4200 AcceptAlert();4201 try {4202 Thread.sleep(10000);4203 } catch (InterruptedException ex) {4204 }4205 }4206 } else if (GetDriverInfo().toString().toLowerCase().contains("android-chrome")) {4207 }4208 return driver;4209 }4210 /**4211 * @author Cigniti4212 * @description : Location Alert Present4213 * @param alertShouldBeThereOrNot4214 * @param waitingTime4215 * @return4216 */4217 public boolean assertLocationAlertPresent(boolean alertShouldBeThereOrNot, Long waitingTime) {4218 WebDriverWait wait = new WebDriverWait(driver, waitingTime);4219 Alert alert = null;4220 try {4221 alert = wait.until(ExpectedConditions.alertIsPresent());4222 } catch (TimeoutException e) {4223 }4224 Set<String> windowHandles = driver.getWindowHandles();4225 if (windowHandles.size() > 1 && alertShouldBeThereOrNot == true) {4226 alert = driver.switchTo().alert();4227 /**4228 * The alert text should be the one that is shown on IPhone/IPad. It4229 * should have Allow and Don't Allow buttons.4230 */4231 String alertText = alert.getText();4232 if (!alertText.equals("\"Safari\" Would Like to Use Your Current Location")) {4233 alert = null;4234 }4235 }4236 if (alert != null) {4237 System.out.println("alert is present");4238 } else {4239 System.out.println("alert is not present");4240 }4241 if (alertShouldBeThereOrNot == true && alert != null) {4242 return true;4243 } else if (alertShouldBeThereOrNot == true && alert == null) {4244 return false;4245 }4246 if (alertShouldBeThereOrNot == false && alert != null) {4247 return false;4248 } else if (alertShouldBeThereOrNot == false && alert == null) {4249 return true;4250 } else4251 return false;4252 }4253 public boolean isLocationServiceEnabled() {4254 boolean value = false;4255 if (locationServiceEnabled != null)4256 value = this.locationServiceEnabled.booleanValue();4257 return value;4258 }4259 /**4260 * @author Cigniti4261 * @description : Get Element Xpath4262 * @param element4263 * @return4264 */4265 public String getElementXPath(WebElement element) {4266 try {4267 String str = element.toString().split("->")[1].trim();4268 if (str.contains("xpath")) {4269 String str2 = str.split("xpath: ")[1].trim();4270 str = str2.substring(0, str2.length() - 1);4271 } else {4272 String str2 = str.split(": ")[1].trim();4273 str = str.split(": ")[0].trim() + "=" + str2.substring(0, str2.length() - 1);4274 }4275 return str;4276 } catch (Exception e) {4277 return "<failed to retrive xpath>";4278 }4279 }4280 /**4281 * @author Cigniti4282 * @description : Kill window process4283 * @param processName4284 * @throws Exception4285 */4286 public void KillWindowProcess(String processName) throws Exception {4287 Platform p = Platform.getCurrent();4288 if (!p.is(Platform.MAC)) {4289 String TASKLIST = "tasklist";4290 String KILL = "taskkill /F /IM ";4291 Process proc = Runtime.getRuntime().exec(TASKLIST);4292 BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));4293 String line;4294 while ((line = reader.readLine()) != null) {4295 if (line.contains(processName)) {4296 Runtime.getRuntime().exec(KILL + processName);4297 }4298 }4299 } else {4300 try {4301 Runtime.getRuntime().exec("killall " + processName);4302 Runtime.getRuntime().exec("taskkill /F /IM " + processName);4303 } catch (Exception e) {4304 }4305 }4306 }4307 /**4308 * @author Cigniti4309 * @description: Select values from drop down button using visible text4310 * @param ddb4311 * @param value4312 * @param index4313 */4314 public void SelectFromDropDown(WebElement ddb, String value, int index) {4315 try {4316 Select dropdown = new Select(ddb);4317 dropdown.selectByVisibleText(value);4318 } catch (Exception e) {4319 try {4320 JavascriptExecutor js = (JavascriptExecutor) driver;4321 js.executeScript("arguments[0].selectedIndex = arguments[1];", ddb, index);4322 js.executeScript("$(arguments[0]).trigger('change');", ddb);4323 } catch (Exception e5) {4324 }4325 }4326 }4327 /**4328 * @author Cigniti4329 * @description: Elements counts4330 * @param by4331 * @param timeoutInSeconds4332 * @param description4333 * @return4334 */4335 public Integer CountElement(By by, Optional<Long> timeoutInSeconds, String description) {4336 try {4337 if (!description.equals("")) {4338 extentLogs.info("Elements Count", "Get the count for " + description);4339 }4340 return FindElements(by, timeoutInSeconds).size();4341 } catch (NoSuchElementException e) {4342 extentLogs.error("Elements Count",4343 "Unable to get the count of elements due to exeception - " + e.getLocalizedMessage());4344 return 0;4345 } catch (Exception e) {4346 extentLogs.error("Elements Count",4347 "Unable to get the count of elements due to exeception - " + e.getLocalizedMessage());4348 return 0;4349 }4350 }4351 /**4352 * @author Cigniti4353 * @description: get element inner text directly using locator value4354 * @param by4355 * @param description4356 * @return4357 */4358 public String getElementInnerText(By by, String description) throws Throwable {4359 try {4360 if (!description.equals("")) {4361 extentLogs.pass("Inner Text of Element", "Get text for " + description);4362 }4363 WebElement elem = FindElement(by, Optional.of(Long.parseLong("4")));4364 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4365 String text = (String) js.executeScript("return arguments[0].innerHTML.toString();", elem);4366 return text;4367 } catch (NoSuchElementException e) {4368 extentLogs.error("Inner Text of Element",4369 "No such element found to get inner text due to execption - " + e.getLocalizedMessage());4370 return "";4371 } catch (Exception e) {4372 driver.findElement(by).getText();4373 return "";4374 }4375 }4376 /**4377 * @author Cigniti4378 * @description: get element inner text using WebElement4379 * @param elem4380 * @param description4381 * @return4382 */4383 public String getElementInnerText(WebElement elem, String description) {4384 try {4385 if (!description.equals("")) {4386 extentLogs.pass("Inner Text of Element", "Get text for " + description);4387 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "Get text for " + description);4388 }4389 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4390 String text = (String) js.executeScript("return arguments[0].innerHTML.toString();", elem);4391 return text;4392 } catch (NoSuchElementException e) {4393 extentLogs.error("Inner Text of Element", "No such element found to get element inner text.");4394 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "error", "No such element found");4395 return "";4396 } catch (Exception e) {4397 return "";4398 }4399 }4400 /**4401 * @author Cigniti4402 * @description: get text between open and close tag4403 * @param by4404 * @param description4405 * @return4406 */4407 public String getElementText(By by, String description) throws Throwable {4408 try {4409 if (!description.equals("")) {4410 extentLogs.pass("Element Text", "Get text for " + description);4411 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "Get text for " + description);4412 }4413 return FindElement(by, Optional.of(Long.parseLong("4"))).getText();4414 } catch (NoSuchElementException e) {4415 extentLogs.error("Element Text",4416 "No such element found to get element text due to exception - " + e.getLocalizedMessage());4417 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "No such element found XPATH: " + by);4418 return "";4419 } catch (NullPointerException e) {4420 extentLogs.error("Element Text",4421 "No such element found to get element text due to exception - " + e.getLocalizedMessage());4422 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "No such element found XPATH: " + by);4423 return "";4424 } catch (Exception e) {4425 driver.findElement(by).getText();4426 extentLogs.error("Element Text",4427 "No such element found to get element text due to exception - " + e.getLocalizedMessage());4428 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", e.getLocalizedMessage() + " - " + by);4429 return "";4430 }4431 }4432 /**4433 * @author Cigniti4434 * @description: compare values for validation4435 * @param actual4436 * @param expected4437 * @param errorText4438 * @return4439 */4440 public boolean verifyText(By by, String text, String locatorName)4441 throws Throwable {4442 boolean flag = false;4443 try {4444 String vtxt = getElementText(by, locatorName).trim();4445 vtxt.equals(text.trim());4446 flag = true;4447 return true;4448 } catch (Exception e) {4449 return false;4450 } finally {4451 if (!flag) {4452 extentLogs.fail("VerifyText ", "<b>" +text4453 + "</b> is <b>NOT</b> present in the location: <b>" + locatorName + "</b>");4454 flag = true;4455 } else if (flag) {4456 extentLogs.pass("VerifyText ", "<b>" +text4457 + "</b> is present in the location: <b>" + locatorName + "</b>");4458 flag = false;4459 }4460 }4461 }4462 4463 /**4464 * @author Cigniti4465 * @description: compare values for validation4466 * @param actual4467 * @param expected4468 * @param errorText4469 * @return4470 */4471 public Boolean compareValues(String actual, String expected, String errorText) {4472 boolean flag = true;4473 if (!actual.trim().equalsIgnoreCase(expected.trim())) {4474 extentLogs.fail("Compare Text Values",4475 "" + errorText + " did not match. Expected text is-" + expected + " and Actual text is-" + actual);4476 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "error",4477 errorText + " did not match. Expected text is-" + expected + " and Actual text is-" + actual);4478 flag = false;4479 } else {4480 extentLogs.pass("Compare Text Values",4481 "Actual and Expected Value are matched, expected and actual value is " + expected);4482 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",4483 "Actual and Expected Value are matched, expected and actual value is " + expected);4484 flag = true;4485 }4486 return flag;4487 }4488 /**4489 * @author Cigniti4490 * @description: verify string contains for validation4491 * @param actual4492 * @param expected4493 * @param errorText4494 * @return4495 */4496 public Boolean checkStringContains(String actual, String expected, String errorText) {4497 boolean flag = true;4498 if (!actual.trim().contains(expected.trim())) {4499 extentLogs.fail("Presence of Text", "" + errorText + " did not contain expected String. Expected string is-"4500 + expected + " and Actual string is-" + actual);4501 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "error",4502 errorText + " did not contain expected String. Expected string is-" + expected4503 + " and Actual string is-" + actual);4504 flag = false;4505 } else {4506 extentLogs.pass("Presence of Text",4507 "Actual string contains the expected String, expected and actual string is " + expected);4508 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "PASS",4509 "Actual string contains the expected String, expected and actual string is " + expected);4510 flag = true;4511 }4512 return flag;4513 }4514 /**4515 * @author Cigniti4516 * @description: get element attribute value with description.4517 * @param by4518 * @param attribute4519 * @param description4520 * @return4521 */4522 public String getElementAttribute(By by, String attribute, String description) {4523 try {4524 return driver.findElement(by).getAttribute(attribute).toString();4525 } catch (NoSuchElementException e) {4526 extentLogs.error("Attribute Value",4527 "No such element found to get attribute value due to exception - " + e.getLocalizedMessage());4528 return "";4529 } catch (Exception e) {4530 driver.findElement(by).getText();4531 extentLogs.error("Attribute Value",4532 "No such element found to get attribute value due to exception - " + e.getLocalizedMessage());4533 return "";4534 }4535 }4536 /**4537 * @author Cigniti4538 */4539 public static enum Mode {4540 ALPHA, ALPHANUMERIC, NUMERIC4541 }4542 /**4543 * @author Cigniti4544 * @description: get calendar month value in numeric format4545 * @param monthCharValue4546 * @return4547 */4548 public String getMonthNumericValue(String monthCharValue) {4549 switch (monthCharValue.trim().toUpperCase()) {4550 case "JAN":4551 case "JANUARY":4552 return "01";4553 case "FEB":4554 case "FEBRUARY":4555 return "02";4556 case "MAR":4557 case "MARCH":4558 return "03";4559 case "APR":4560 case "APRIL":4561 return "04";4562 case "MAY":4563 return "05";4564 case "JUN":4565 case "JUNE":4566 return "06";4567 case "JULY":4568 case "JUL":4569 return "07";4570 case "AUGUST":4571 case "AUG":4572 return "08";4573 case "SEP":4574 case "SEPTEMBER":4575 return "09";4576 case "OCT":4577 case "OCTOBER":4578 return "10";4579 case "NOV":4580 case "NOVEMBER":4581 return "11";4582 case "DECEMBER":4583 case "DEC":4584 return "12";4585 default:4586 extentLogs.info("Numeric value of the Month", "Incorrect value specified :" + monthCharValue);4587 return "";4588 }4589 }4590 /**4591 * Get Month Name4592 * 4593 * @param monthNumericValue4594 * @return4595 */4596 public String getMonthName(String monthNumericValue) {4597 switch (monthNumericValue.trim()) {4598 case "01":4599 return "January";4600 case "02":4601 return "February";4602 case "03":4603 return "March";4604 case "04":4605 return "April";4606 case "05":4607 return "May";4608 case "06":4609 return "June";4610 case "07":4611 return "July";4612 case "08":4613 return "August";4614 case "09":4615 return "September";4616 case "10":4617 return "October";4618 case "11":4619 return "November";4620 case "12":4621 return "December";4622 default:4623 return "";4624 }4625 }4626 /**4627 * @author Cigniti4628 * @descriton: generate random number - alpa,num,alphnum4629 * @param length4630 * @param mode4631 * @return4632 */4633 public static String generateRandomString(int length, Mode mode) {4634 StringBuffer buffer = new StringBuffer();4635 String characters = "";4636 Boolean isNumericOnly = false;4637 String automationTextPrefix = "";4638 switch (mode) {4639 case ALPHA:4640 characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";4641 break;4642 case ALPHANUMERIC:4643 characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";4644 break;4645 case NUMERIC:4646 isNumericOnly = true;4647 characters = "123456789";4648 break;4649 }4650 int charactersLength = characters.length();4651 if (length >= 3 && !isNumericOnly) {4652 length = length - 2;4653 automationTextPrefix = "AT";4654 }4655 for (int i = 0; i < length; i++) {4656 double index = Math.random() * charactersLength;4657 buffer.append(characters.charAt((int) index));4658 }4659 if (isNumericOnly) {4660 return buffer.toString();4661 } else {4662 return automationTextPrefix + buffer.toString();4663 }4664 }4665 /**4666 * @author Cigniti4667 * @description: download pdf document4668 * @param pdfPagedriver4669 * @param documentName4670 * @param filePath4671 */4672 public void DownloadPDFDocument(WebDriver pdfPagedriver, String documentName, String filePath) {4673 HttpClient httpClient = new DefaultHttpClient();4674 httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);4675 CookieStore cookieStore = new BasicCookieStore();4676 Set<org.openqa.selenium.Cookie> cookies = pdfPagedriver.manage().getCookies();4677 for (org.openqa.selenium.Cookie cookie : cookies) {4678 BasicClientCookie2 cookie2 = new BasicClientCookie2(cookie.getName(), cookie.getValue());4679 cookie2.setAttribute(ClientCookie.VERSION_ATTR, "1");4680 cookie2.setAttribute(ClientCookie.DOMAIN_ATTR, cookie.getDomain());4681 cookie2.setDomain(cookie.getDomain());4682 cookie2.setPath(cookie.getPath());4683 cookie2.setExpiryDate(cookie.getExpiry());4684 cookieStore.addCookie(cookie2);4685 }4686 HttpContext httpContext = new BasicHttpContext();4687 httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);4688 try {4689 HttpResponse httpResponse = httpClient.execute(new HttpGet(pdfPagedriver.getCurrentUrl()), httpContext);4690 InputStream inputStream = httpResponse.getEntity().getContent();4691 FileOutputStream fos = new FileOutputStream(filePath + "\\" + documentName.replaceAll("\\s+", "") + ".pdf");4692 byte[] buffer = new byte[2048];4693 int bytesRead = 0;4694 while ((bytesRead = inputStream.read(buffer)) != -1) {4695 fos.write(buffer, 0, bytesRead);4696 }4697 fos.close();4698 } catch (ClientProtocolException e) {4699 } catch (IOException e) {4700 }4701 httpClient.getConnectionManager().shutdown();4702 }4703 /**4704 * @author Cigniti4705 * @description: verify text presence in UI4706 * @param txtValue4707 * @return4708 */4709 public boolean isTextPresentOnPage(String txtValue) {4710 boolean b = false;4711 try {4712 String bodyText = driver.findElement(By.tagName("body")).getText();4713 b = bodyText.contains(txtValue.trim());4714 if (b) {4715 extentLogs.pass("Presence of Text", "Info : '" + txtValue + "' is found on Page.");4716 b = true;4717 } else {4718 extentLogs.fail("Presence of Text", "Info : '" + txtValue + "' is not found on Page ");4719 b = false;4720 }4721 } catch (Exception e) {4722 extentLogs.error("Presence of Text", "Exception in isTextPresentOnPage" + e.getMessage());4723 b = false;4724 }4725 return b;4726 }4727 /**4728 * @author Cigniti4729 * @description e.g. for Jul 16 2014 03:32:06 AM format pass 'MMM dd yyyy4730 * hh:mm:ss aa' as dateformat value.4731 * @param dateformat4732 * @return4733 */4734 public String getCurrentDataTime(String dateformat) {4735 Calendar cal = Calendar.getInstance();4736 SimpleDateFormat sdf = new SimpleDateFormat(dateformat);4737 try {4738 return sdf.format(cal.getTime());4739 } catch (Exception e) {4740 e.getMessage();4741 return "";4742 }4743 }4744 /**4745 * @author Cigniti4746 * @param -4747 * dateValue = "Jul 16 2014 03:32:06 AM" and format =4748 * "MMM dd yyyy hh:mm:ss aa"4749 * @param -4750 * dateValue = "7-Jun-2013" and format = "dd-MMM-yyyy"4751 * @param dateValue4752 * @param format4753 * @return4754 */4755 public Date getDateTimeFromProvidedString(String dateValue, String format) {4756 SimpleDateFormat formatter = new SimpleDateFormat(format);4757 try {4758 Date date = formatter.parse(dateValue);4759 return date;4760 } catch (ParseException e) {4761 e.getMessage();4762 return null;4763 }4764 }4765 /**4766 * @author Cigniti4767 * @description: get date in user's required format4768 * @param date4769 * @param dateformat4770 * @return4771 */4772 public String getDateTimeFromProvidedString(Date date, String dateformat) {4773 SimpleDateFormat sdf = new SimpleDateFormat(dateformat);4774 try {4775 return sdf.format(date);4776 } catch (Exception e) {4777 // AddToLog("CurrentTestCaseLog", "error","Failed to convert current4778 // Date and Time in the provided format ("+dateformat+")");4779 return "";4780 }4781 }4782 /**4783 * @author Cigniti4784 * @description: wait for element present4785 * @param by4786 * @param timeout4787 * @return4788 */4789 public Boolean waitForElementPresent(By by, Integer timeout) {4790 Boolean flag = false;4791 for (Integer i = 1; i <= timeout; i++) {4792 if (IsElementExist(by, Optional.of(Long.parseLong("0")))) {4793 flag = true;4794 break;4795 }4796 try {4797 Thread.sleep(1000);4798 } catch (InterruptedException e) {4799 }4800 }4801 return flag;4802 }4803 /**4804 * @author Cigniti4805 * @description: wait for element not present4806 * @param by4807 * @param timeout4808 * @return4809 */4810 public Boolean waitForElementNotPresent(By by, Integer timeout) {4811 Boolean flag = false;4812 for (Integer i = 1; i <= timeout; i++) {4813 if (!IsElementExist(by, Optional.of(Long.parseLong("0")))) {4814 flag = true;4815 break;4816 }4817 try {4818 Thread.sleep(1000);4819 } catch (InterruptedException e) {4820 }4821 }4822 return flag;4823 }4824 /**4825 * @author Cigniti4826 * @description: move to element directly using locator value4827 * @param xpath4828 */4829 public void setFocusByXpath(String xpath) {4830 try {4831 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4832 js.executeScript(4833 "$(document.evaluate(\"" + xpath + "\", document, null, 9, null).singleNodeValue).focusin();");4834 } catch (NullPointerException ex) {4835 try {4836 JavascriptExecutor js = (JavascriptExecutor) (driver);4837 js.executeScript(4838 "$(document.evaluate(\"" + xpath + "\", document, null, 9, null).singleNodeValue).focusin();");4839 } catch (Exception e) {4840 }4841 }4842 }4843 /**4844 * @author Cigniti4845 * @description: get current date and time4846 * @param format4847 * @return4848 */4849 public String getCurrentDateTime(String timeZOne, String format) {4850 SimpleDateFormat sdf = new SimpleDateFormat(format);4851 sdf.setTimeZone(TimeZone.getTimeZone(timeZOne));4852 Calendar c = Calendar.getInstance();4853 String fdate = sdf.format(c.getTime());4854 return fdate;4855 }4856 /**4857 * @author Cigniti4858 * @description: add no. of days from current date4859 * @param format4860 * @param AddNoOfDays4861 * @return4862 */4863 public String AddNoOfDaysInCurrentDate(String format, int AddNoOfDays) {4864 String Timezone = ConfigManager.getProperties().getProperty("usTimeZone".trim());4865 SimpleDateFormat sdf = new SimpleDateFormat(format);4866 sdf.setTimeZone(TimeZone.getTimeZone(Timezone));4867 Calendar c = Calendar.getInstance();4868 c.add(Calendar.DATE, AddNoOfDays);4869 String fdate = sdf.format(c.getTime());4870 return fdate;4871 }4872 /**4873 * @author Cigniti4874 * @description: change first character of string to Capital Letter4875 * @param str4876 * @return4877 */4878 public static String ChangeStringFirstCharToCapital(String str) {4879 StringBuilder b = new StringBuilder(str);4880 int i = 0;4881 do {4882 b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());4883 i = b.indexOf(" ", i) + 1;4884 } while (i > 0 && i < b.length());4885 return b.toString();4886 }4887 /**4888 * @author Cigniti4889 * @description: get first day of current week4890 * @param format4891 * @return4892 * @throws ParseException4893 */4894 public String getFirstDayOfCurrentWeek(String format) throws ParseException {4895 String fdate;4896 Calendar cal = Calendar.getInstance();4897 SimpleDateFormat sdf = new SimpleDateFormat(format);4898 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);4899 fdate = sdf.format(cal.getTime());4900 Date date1 = sdf.parse(fdate);4901 Date date = new Date();4902 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");4903 Date date2 = sdf2.parse(sdf2.format(date));4904 if (date1.after(date2)) {4905 Calendar cal1 = Calendar.getInstance();4906 SimpleDateFormat sdf1 = new SimpleDateFormat(format);4907 cal1.add(Calendar.DAY_OF_WEEK, -6);4908 fdate = sdf1.format(cal1.getTime());4909 }4910 return fdate;4911 }4912 /**4913 * @author Cigniti4914 * @description: get last day of current week4915 * @param format4916 * @return4917 */4918 public String getLastDayOfCurrentWeek(String format) {4919 String ldate;4920 Calendar cal = Calendar.getInstance();4921 SimpleDateFormat sdf = new SimpleDateFormat(format);4922 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);4923 cal.add(Calendar.DAY_OF_WEEK, 6);4924 ldate = sdf.format(cal.getTime());4925 return ldate;4926 }4927 /**4928 * @author Cigniti4929 * @description: get last day of current month in user's format4930 * @param format4931 * @return4932 */4933 public String getLastDayOfMonth(String format) {4934 Calendar cal = Calendar.getInstance();4935 SimpleDateFormat sdf = new SimpleDateFormat(format);4936 cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));4937 String ldate = sdf.format(cal.getTime());4938 return ldate;4939 }4940 /**4941 * '4942 * 4943 * @author Cigniti4944 * @description: get last day of current month and year4945 * @param month4946 * @param year4947 * @return4948 */4949 public String getLastDayOfMonth(int month, int year) {4950 Calendar calendar = Calendar.getInstance();4951 // passing month-1 because 0-->jan, 1-->feb... 11-->dec4952 calendar.set(year, month - 1, 1);4953 calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));4954 Date date = calendar.getTime();4955 DateFormat DATE_FORMAT = new SimpleDateFormat("dd");4956 SimpleDateFormat sdf = new SimpleDateFormat("dd");4957 sdf.format(date);4958 DATE_FORMAT.format(date);4959 return DATE_FORMAT.format(date);4960 }4961 /**4962 * @author Cigniti4963 * @description: get http url response code, RGV2UHJldmlldzpFcXVpbm94MSE=4964 * @param URL4965 * @return4966 */4967 public boolean GetResponseCode(String URL) {4968 boolean passflag = true;4969 try {4970 URL url = new URL(URL);4971 HttpURLConnection connection = (HttpURLConnection) url.openConnection();4972 connection.setRequestMethod("GET");4973 // connection.setDoInput(true);4974 // connection.setRequestProperty("Authorization", "Basic " + "");4975 connection.connect();4976 int code = connection.getResponseCode();4977 if (HttpURLConnection.HTTP_OK == code && code != 200) {4978 passflag = false;4979 }4980 } catch (Exception e) {4981 e.printStackTrace();4982 passflag = false;4983 }4984 return passflag;4985 }4986 /**4987 * @author Cigniti4988 * @description: get last sunday from current date/day in user's format4989 * @param format4990 * @return4991 */4992 public String getPreviousSunday(String format) {4993 SimpleDateFormat df = new SimpleDateFormat(format);4994 Calendar now = new GregorianCalendar();4995 Calendar start = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH),4996 now.get(Calendar.DAY_OF_MONTH));4997 while (start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {4998 start.add(Calendar.DAY_OF_WEEK, -1);4999 }5000 Calendar end = (Calendar) start.clone();5001 end.add(Calendar.DAY_OF_MONTH, 7);5002 return df.format(start.getTime());5003 }5004 /**5005 * @author Cigniti5006 * @description: get next sunday from current date/day in user's format5007 * @param format5008 * @return5009 */5010 public String getNextSunday(String format) {5011 SimpleDateFormat df = new SimpleDateFormat(format);5012 // DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,5013 // DateFormat.FULL);5014 Calendar now = new GregorianCalendar();5015 Calendar start = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH),5016 now.get(Calendar.DAY_OF_MONTH));5017 while (start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {5018 start.add(Calendar.DAY_OF_WEEK, +1);5019 }5020 Calendar end = (Calendar) start.clone();5021 end.add(Calendar.DAY_OF_MONTH, 7);5022 return df.format(start.getTime());5023 }5024 /**5025 * @author Cigniti5026 * @description : get Date In Expected Format5027 * @param format5028 * @param dateInString5029 * @param returnformat5030 * @return5031 */5032 public String getDateInExpectedFormat(String format, String dateInString, String returnformat) {5033 SimpleDateFormat formatter = new SimpleDateFormat(format);5034 SimpleDateFormat returnFormatter = new SimpleDateFormat(returnformat);5035 Date date = null;5036 try {5037 date = formatter.parse(dateInString);5038 // formatter = new SimpleDateFormat(returnformat);5039 return returnFormatter.format(date);5040 } catch (ParseException e) {5041 e.printStackTrace();5042 return null;5043 }5044 }5045 /**5046 * @author Cigniti5047 * @description : Get Total Number of days in the Current Month5048 * @return5049 */5050 public int getTotalNoOfDayInMonth() {5051 try {5052 Calendar c = Calendar.getInstance();5053 int monthMaxDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);5054 CurrentMonthDays = monthMaxDays;5055 } catch (Exception e) {5056 e.getMessage();5057 }5058 return CurrentMonthDays;5059 }5060 /**5061 * @author Cigniti5062 * @description : Swipe To Element Visible5063 * @param elementBy5064 * @return5065 */5066 public boolean ScrollToElementVisible(By elementBy) {5067 try {5068 WebElement elem = (new WebDriverWait(driver, 1))5069 .until(ExpectedConditions.presenceOfElementLocated(elementBy));5070 return ScrollToElementVisible(elem);5071 } catch (Exception ex) {5072 ex.getLocalizedMessage();5073 return false;5074 }5075 }5076 /**5077 * @author Cigniti5078 * @description : Scroll To Element Visible5079 * @param WebElement5080 * @return5081 */5082 public boolean ScrollToElementVisible(WebElement element) {5083 if (CommonVariables.PlatformName.get().equalsIgnoreCase("windows")) {5084 try {5085 ScrollToTop();5086 Point p = element.getLocation();5087 if (p.getX() == 0 && p.getY() == 0) {5088 return false;5089 } else {5090 ((JavascriptExecutor) driver)5091 .executeScript("window.scroll(" + p.getX() + "," + (p.getY() - 120) + ");");5092 try {5093 if (driver.getWrappedDriver().getClass().toString().toLowerCase().contains("internet")5094 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("ie")5095 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("edge")5096 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("safari")5097 || driver.getWrappedDriver().getClass().toString().toLowerCase().contains("opera")) {5098 Thread.sleep(800);5099 }5100 } catch (Exception e) {5101 }5102 return true;5103 }5104 } catch (Exception ex) {5105 throw ex;5106 }5107 } else {5108 try {5109 Dimension d = element.getSize();5110 if (d.height != 0 && d.width != 0) {5111 new Actions(driver.getWrappedDriver()).moveToElement(element).perform();5112 return true;5113 } else {5114 JavascriptExecutor js = (JavascriptExecutor) driver;5115 int height_covered = 0, pageHeightLeft = 0;5116 Long pageCurrentHeight = (Long) js.executeScript("return window.innerHeight");5117 ScrollToTop();5118 Long pageheight1 = (Long) js.executeScript("return window.innerHeight");5119 Long maxPageHeight1 = (Long) js.executeScript(5120 "return Math.max(document.documentElement.scrollHeight, document.body.scrollHeight,"5121 + "document.documentElement.clientHeight, window.innerHeight)");5122 float sections = (float) maxPageHeight1 / pageheight1;5123 int numberOfRows = (int) Math.ceil(sections);5124 int pageheight = pageheight1.intValue();5125 int maxPageHeight = maxPageHeight1.intValue();5126 for (int row = 0; row < numberOfRows; row++) {5127 pageHeightLeft = maxPageHeight - height_covered;5128 if ((pageHeightLeft < pageheight)) {5129 d = element.getSize();5130 if (d.height == 0 && d.width == 0) {5131 js.executeScript("window.scrollTo(0," + pageCurrentHeight + ")");5132 return false;5133 } else {5134 new Actions(driver.getWrappedDriver()).moveToElement(element).perform();5135 return true;5136 }5137 } else {5138 d = element.getSize();5139 if (!(d.height != 0 && d.width != 0)) {5140 height_covered = height_covered + pageheight;5141 js.executeScript("window.scrollTo(0," + height_covered + ")");5142 try {5143 Thread.sleep(100);5144 } catch (InterruptedException e) {5145 }5146 } else {5147 new Actions(driver.getWrappedDriver()).moveToElement(element).perform();5148 return true;5149 }5150 }5151 }5152 ScrollToTop();5153 return false;5154 }5155 } catch (org.openqa.selenium.ElementNotVisibleException e) {5156 throw new ElementNotVisibleException("");5157 } catch (Exception ex) {5158 throw ex;5159 }5160 }5161 }5162 /**5163 * @author Cigniti5164 * @description : Mouse Over5165 * @param webelement5166 */5167 public void Mouseover(WebElement webelement) {5168 try {5169 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());5170 js.executeScript("$(arguments[0]).trigger('mouseover');", webelement);5171 } catch (Exception e) {5172 e.getLocalizedMessage();5173 }5174 }5175 public String GetXpathFromBy(By by) {5176 try {5177 return by.toString().split("By.xpath: ")[1].trim();5178 } catch (Exception e) {5179 return "";5180 }5181 }5182 /**5183 * @author Cigniti5184 * @description : Is Element Display In Current View5185 * @param xpath5186 * @return5187 */5188 5189 public boolean verifyElementDisplayed(By by, String elementName) throws Throwable{5190 boolean displayFlag = false;5191 try {5192 if(IsElementDisplayInCurrentView(by)){5193 displayFlag = true;5194 extentLogs.pass("Verify Element is displayed","<b>" + elementName + "</b>" + " is displayed");5195 }else{5196 5197 extentLogs.fail("Verify Element is displayed","<b>" + elementName + "</b>" + " is NOT displayed");5198 }5199 }5200 catch (Exception e) {5201 e.printStackTrace();5202 }5203 return displayFlag;5204 5205 }5206 5207 /**5208 * @author Cigniti5209 * @description : Is Element Display In Current View5210 * @param xpath5211 * @return5212 */5213 public boolean IsElementDisplayInCurrentView(By xpath) {5214 try {5215 return IsElementDisplayInCurrentView(driver.findElement(xpath));5216 } catch (Exception ex) {5217 return false;5218 }5219 }5220 /**5221 * @author Cigniti5222 * @description: verify visibility of an element in current open view in UI5223 * @param webElement5224 * @return5225 */5226 public boolean IsElementDisplayInCurrentView(WebElement webElement) {5227 double browser_top_offset = 0.0;5228 try {5229 JavascriptExecutor js = (JavascriptExecutor) driver;5230 Long pageheight = (Long) js.executeScript("return $(window).height()");5231 double elemPos = 0;5232 try {5233 Long posY = (Long) js.executeScript("return $(arguments[0]).offset().top - $(window).scrollTop()",5234 webElement);5235 elemPos = posY.doubleValue();5236 } catch (ClassCastException cc) {5237 elemPos = (Double) js.executeScript("return $(arguments[0]).offset().top - $(window).scrollTop()",5238 webElement);5239 }5240 double pageheight1 = pageheight.doubleValue();5241 if (elemPos >= browser_top_offset && elemPos < pageheight1)5242 return true;5243 else5244 return false;5245 } catch (Exception ex) {5246 System.out.println("" + ex.getMessage());5247 return false;5248 }5249 }5250 /**5251 * @author Cigniti5252 * @description : Calculate Age5253 * @param year5254 * @param month5255 * @param day5256 * @return5257 */5258 public int calculateAge(int year, int month, int day) // Enter Date of Birth5259 // //5260 {5261 try {5262 LocalDate birthdate = new LocalDate(year, month, day);5263 LocalDate now = new LocalDate();5264 Years ageInYear = Years.yearsBetween(birthdate, now);5265 return ageInYear.getYears();5266 } catch (Exception ex) {5267 throw ex;5268 }5269 }5270 /**5271 * @author Cigniti5272 * @param dob5273 * 1986-10-31, 1955-30-125274 * @param format5275 * - yyyy-mm-dd , yyyy-dd-mm5276 * @return Age as a integer5277 */5278 @SuppressWarnings("deprecation")5279 public int calculateAge(String dob, String format) throws Exception// Enter5280 // Date5281 // od5282 // Birth5283 // //5284 {5285 try {5286 Date dob_DateObj = getDateTimeFromProvidedString(dob, format);5287 long ageInMillis = new Date().getTime() - dob_DateObj.getTime();5288 return new Date(ageInMillis).getYear();5289 } catch (IllegalArgumentException ex) {5290 extentLogs.info("calculate Age",5291 "Failed to get Age from provided format (" + format + ") and date value (" + dob + ")");5292 throw ex;5293 } catch (NullPointerException ex) {5294 extentLogs.info("calculate Age",5295 "Failed to get Age from provided format (" + format + ") and dob value (" + dob + ")");5296 throw ex;5297 }5298 }5299 /**5300 * @author Cigniti5301 * @param url5302 * @param userAgent5303 * @return5304 */5305 public Map<String, String> getHTTPResponseCodeAndSize(String url, String userAgent) {5306 Map<String, String> httpResponseMetaData = new HashMap<String, String>();5307 try {5308 URL obj = new URL(url);5309 HttpURLConnection con = (HttpURLConnection) obj.openConnection();5310 con.setRequestMethod("GET");5311 con.setRequestProperty("User-Agent", userAgent);5312 httpResponseMetaData.put("code", String.valueOf(con.getResponseCode()));5313 httpResponseMetaData.put("size", String.valueOf(con.getContentLength()));5314 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));5315 String inputLine;5316 StringBuffer response = new StringBuffer();5317 while ((inputLine = in.readLine()) != null) {5318 response.append(inputLine);5319 }5320 in.close();5321 httpResponseMetaData.put("content", response.toString());5322 return httpResponseMetaData;5323 } catch (Exception e) {5324 httpResponseMetaData.put("code", "500");5325 httpResponseMetaData.put("size", "0");5326 httpResponseMetaData.put("content", e.getMessage());5327 return httpResponseMetaData;5328 }5329 }5330 /**5331 * @author Cigniti5332 * @description : get cookies5333 * @return5334 */5335 public String[] getcookies() {5336 String[] stringArray = null;5337 try {5338 Set<Cookie> cookie = CommonVariables.CommonDriver.get().manage().getCookies();5339 Object[] cookie_text = cookie.toArray();5340 stringArray = new String[cookie_text.length];5341 for (int i = 0; i < cookie_text.length; i++) {5342 stringArray[i] = cookie_text[i].toString();5343 }5344 } catch (Exception e) {5345 System.out.println("Not able to get cookies for the selected page due to error message :" + e.getMessage());5346 }5347 return stringArray;5348 }5349 /**5350 * @param upper5351 * upper limit5352 * @param lower5353 * lower limit5354 * @return5355 */5356 public Integer getRandomNumberBetween(Integer upper, Integer lower) {5357 return (int) ((Math.random() * (upper - lower)) + lower);5358 }5359 public void setDownloadPathForFile(String downloadpath) {5360 try {5361 String downloadFilepath = downloadpath;5362 File fl = new File(downloadFilepath);5363 if (!fl.exists()) {5364 fl.mkdir();5365 }5366 Map<String, Object> prefs = new HashMap<String, Object>();5367 prefs.put("profile.default_content_settings.popups", 0);5368 prefs.put("download.default_directory", downloadFilepath);5369 prefs.put("savefile.default_directory", downloadFilepath);5370 chromeoptions.setExperimentalOption("prefs", prefs);5371 } catch (Exception e) {5372 e.getMessage();5373 }5374 }5375 /**5376 * @author Cigniti5377 * @description: hightlight WebElement5378 * @param elem5379 * @param durationInSeconds5380 */5381 public void HighlightWebElement(WebElement elem, int durationInSeconds) {5382 try {5383 durationInSeconds = durationInSeconds * 1000;5384 String original_style = elem.getAttribute("style");5385 ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute(arguments[1], arguments[2])", elem,5386 "style", "border: 2px solid red; border-style: dashed;");5387 if (durationInSeconds > 0) {5388 Thread.sleep(durationInSeconds);5389 ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute(arguments[1], arguments[2])",5390 elem, "style", original_style);5391 }5392 } catch (Exception e) {5393 }5394 }5395 /**5396 * @author Cigniti5397 * @description : Switch In to iFrame5398 * @param iFrameID5399 * @return5400 */5401 public boolean SwitchIntoFrame(WebElement iFrameID) {5402 try {5403 driver.switchTo().frame(iFrameID);5404 System.out.println("switch to frame sucessfully.");5405 return true;5406 } catch (Exception e) {5407 System.out.println("Failed to switch to frame due to error :" + e.getMessage());5408 return false;5409 }5410 }5411 /**5412 * @author Cigniti5413 * @return5414 */5415 public WebDriver SwitchOutfromFrame() {5416 return driver.switchTo().defaultContent();5417 }5418 /**5419 * @author Cigniti5420 * @description : get Current Month5421 * @return5422 */5423 public String getCurrentMonth() {5424 String CurrentMonth = "";5425 try {5426 SimpleDateFormat sdf = new SimpleDateFormat("MMMM");5427 Calendar cal = Calendar.getInstance();5428 CurrentMonth = sdf.format(cal.getTime());5429 System.out.println("Current Month :" + CurrentMonth);5430 } catch (Exception e) {5431 e.getStackTrace();5432 }5433 return CurrentMonth;5434 }5435 /**5436 * @author Cigniti5437 * @description : get Next Month5438 * @return5439 */5440 public String getNextMonth() {5441 String NextMonth = "";5442 try {5443 SimpleDateFormat sdf = new SimpleDateFormat("MMMM");5444 Calendar cal = Calendar.getInstance();5445 cal.add(Calendar.MONTH, 1);5446 cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));5447 NextMonth = sdf.format(cal.getTime());5448 System.out.println("Next Month :" + NextMonth);5449 } catch (Exception e) {5450 e.getStackTrace();5451 }5452 return NextMonth;5453 }5454 /**5455 * @author Cigniti5456 * @param file5457 * @return5458 */5459 public Boolean deleteFile(File file) {5460 try {5461 if (file.isDirectory()) {5462 String fileList[] = file.list();5463 if (fileList.length == 0) {5464 extentLogs.info("Delete File", "Deleting Directory : " + file.getPath());5465 file.delete();5466 extentLogs.info("Delete File", "Deleted Directory : " + file.getPath());5467 } else {5468 int size = fileList.length;5469 for (int i = 0; i < size; i++) {5470 String fileName = fileList[i];5471 extentLogs.info("Delete File", "File path : " + file.getPath() + " and name :" + fileName);5472 String fullPath = file.getPath() + "/" + fileName;5473 File fileOrFolder = new File(fullPath);5474 extentLogs.info("Delete File", "File copied, full path is: " + fileOrFolder.getPath());5475 deleteFile(fileOrFolder);5476 }5477 }5478 return true;5479 } else {5480 extentLogs.info("Delete File", "Deleting file : " + file.getPath());5481 file.delete();5482 extentLogs.info("Delete File", "Deleted file : " + file.getPath());5483 return true;5484 }5485 } catch (Exception e) {5486 extentLogs.error("Delete File", "Deleted file : " + file.getPath());5487 return false;5488 }5489 }5490 /**5491 * @description: Verify the presence of a file at a particular location.5492 * File name is not case sensitive and can provide5493 * complete/partial name of the file.5494 * @param path5495 * - Complete Path of the folder which suppose to contain file5496 * @param fileName5497 * - Name of the file. It'll compare case5498 * @return True, if file found.5499 */5500 public Boolean verifyPresenceOfFileOrFolderAtLocation(String path, String fileName) {5501 try {5502 File file = new File(path);5503 File[] listOfFiles = file.listFiles();5504 if (listOfFiles.length != 0) {5505 for (int i = 0; i < listOfFiles.length; i++) {5506 if (listOfFiles[i].getName().toLowerCase().contains(fileName.toLowerCase())) {5507 return true;5508 }5509 }5510 }5511 return false;5512 } catch (Exception e) {5513 return false;5514 }5515 }5516 /**5517 * <b>Description:</b> Copies the entire src File to Dest5518 * 5519 * @param src5520 * @param dest5521 * @throws Exception5522 */5523 public void copyFile(File src, File dest) throws Exception {5524 if (src.isDirectory()) {5525 if (!dest.exists()) {5526 dest.mkdir();5527 System.out.println("Directory copied from " + src + " to " + dest);5528 }5529 String files[] = src.list();5530 for (String file : files) {5531 File srcFile = new File(src, file);5532 File destFile = new File(dest, file);5533 copyFile(srcFile, destFile);5534 }5535 } else {5536 InputStream in = new FileInputStream(src);5537 OutputStream out = new FileOutputStream(dest);5538 byte[] buffer = new byte[1024];5539 int length;5540 while ((length = in.read(buffer)) > 0) {5541 out.write(buffer, 0, length);5542 }5543 in.close();5544 out.close();5545 System.out.println("File copied from " + src + " to " + dest);5546 }5547 }5548 /**5549 * <b>Description:</b> Copies the entire src File to Dest5550 * 5551 * @param src5552 * @param dest5553 * @throws Exception5554 */5555 public static void staticCopyFile(File src, File dest) throws Exception {5556 if (src.isDirectory()) {5557 if (!dest.exists()) {5558 dest.mkdir();5559 System.out.println("Directory copied from " + src + " to " + dest);5560 }5561 String files[] = src.list();5562 for (String file : files) {5563 File srcFile = new File(src, file);5564 File destFile = new File(dest, file);5565 staticCopyFile(srcFile, destFile);5566 }5567 } else {5568 InputStream in = new FileInputStream(src);5569 OutputStream out = new FileOutputStream(dest);5570 byte[] buffer = new byte[1024];5571 int length;5572 while ((length = in.read(buffer)) > 0) {5573 out.write(buffer, 0, length);5574 }5575 in.close();5576 out.close();5577 }5578 }5579 /**5580 * @author Cigniti5581 * @param startTime5582 * - Start Time as a Date class object5583 * @param endTime5584 * - End Time as a Date class object5585 */5586 public long getTimeDifferenceInMin(Date startTime, Date endTime) {5587 long ageInMillis = endTime.getTime() - startTime.getTime();5588 return ageInMillis / (1000 * 60);5589 }5590 /**5591 * @author Cigniti5592 * @description: get IP of selenium grid 'node'5593 * @param remotewebdriver5594 * @return5595 */5596 public String GetIPOfSeleniumGridNode(WebDriver remotewebdriver) {5597 String hostFound = null;5598 try {5599 HttpCommandExecutor commandexecutor = (HttpCommandExecutor) ((RemoteWebDriver) remotewebdriver)5600 .getCommandExecutor();5601 String hostName = commandexecutor.getAddressOfRemoteServer().getHost();5602 int port = commandexecutor.getAddressOfRemoteServer().getPort();5603 HttpHost host = new HttpHost(hostName, port);5604 @SuppressWarnings("deprecation")5605 DefaultHttpClient client = new DefaultHttpClient();5606 URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session="5607 + ((RemoteWebDriver) remotewebdriver).getSessionId());5608 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",5609 sessionURL.toExternalForm());5610 HttpResponse response = client.execute(host, r);5611 JSONObject object = extractObject(response);5612 URL myURL = new URL(object.getString("proxyId"));5613 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {5614 hostFound = myURL.getHost();5615 }5616 } catch (Exception e) {5617 e.printStackTrace();5618 }5619 return hostFound;5620 }5621 /**5622 * @author Cigniti5623 * @param resp5624 * @return5625 * @throws IOException5626 * @throws JSONException5627 */5628 private static JSONObject extractObject(HttpResponse resp) throws IOException, JSONException {5629 InputStream contents = resp.getEntity().getContent();5630 StringWriter writer = new StringWriter();5631 IOUtils.copy(contents, writer, "UTF8");5632 JSONObject objToReturn = new JSONObject(writer.toString());5633 return objToReturn;5634 }5635 /**5636 * @author Cigniti5637 * @description: WebElement click5638 * @param webElement5639 * @param time5640 * @return5641 */5642 public boolean javascriptClick(WebElement webElement, long time) {5643 boolean state = false;5644 try {5645 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());5646 js.executeScript("arguments[0].click();", webElement);5647 Thread.sleep(time);5648 state = true;5649 return true;5650 } catch (NullPointerException ex) {5651 return false;5652 } catch (Exception e) {5653 try {5654 if (ScrollToElementVisible(By.xpath(getElementXPath(webElement)))) {5655 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());5656 js.executeScript("$(arguments[0]).click();", webElement);5657 Thread.sleep(time);5658 state = true;5659 return true;5660 } else {5661 return false;5662 }5663 } catch (Exception ex) {5664 }5665 if (!state) {5666 try {5667 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());5668 js.executeScript("$(arguments[0]).focusin();", webElement);5669 Thread.sleep(time);5670 state = true;5671 }5672 catch (Exception e1) {5673 state = false;5674 }5675 }5676 }5677 return state;5678 }5679 /**5680 * @author Cigniti5681 * @description : get Last Month5682 * @return5683 */5684 public String getLastMonth() {5685 String LastMonth = "";5686 try {5687 SimpleDateFormat sdf = new SimpleDateFormat("MMMM");5688 Calendar cal = Calendar.getInstance();5689 cal.add(Calendar.MONTH, -1);5690 cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));5691 LastMonth = sdf.format(cal.getTime());5692 System.out.println("Next Month :" + LastMonth);5693 } catch (Exception e) {5694 e.getStackTrace();5695 }5696 return LastMonth;5697 }5698 /**5699 * @author Cigniti5700 * @description: get alert5701 * @return5702 */5703 public String getAlertText() {5704 try {5705 Alert alert = driver.switchTo().alert();5706 return alert.getText();5707 } catch (Exception e) {5708 return null;5709 }5710 }5711 /**5712 * @author Cigniti5713 * @param remotewebdriver5714 * @return5715 */5716 public String getIPOfSeleniumGridNode(RemoteWebDriver remotewebdriver) {5717 String hostFound = null;5718 try {5719 HttpCommandExecutor commandexecutor = (HttpCommandExecutor) remotewebdriver.getCommandExecutor();5720 String hostName = commandexecutor.getAddressOfRemoteServer().getHost();5721 int port = commandexecutor.getAddressOfRemoteServer().getPort();5722 HttpHost host = new HttpHost(hostName, port);5723 @SuppressWarnings("deprecation")5724 DefaultHttpClient client = new DefaultHttpClient();5725 URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session="5726 + remotewebdriver.getSessionId());5727 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",5728 sessionURL.toExternalForm());5729 HttpResponse response = client.execute(host, r);5730 JSONObject object = extractObject(response);5731 URL myURL = new URL(object.getString("proxyId"));5732 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {5733 hostFound = myURL.getHost();5734 }5735 } catch (Exception e) {5736 e.printStackTrace();5737 }5738 return hostFound;5739 }5740 /**5741 * @return Clipboard text5742 * @throws UnsupportedFlavorException5743 * @throws IOException5744 */5745 public String getTextFromClipboard() throws UnsupportedFlavorException, IOException {5746 Toolkit toolkit = Toolkit.getDefaultToolkit();5747 Clipboard clipboard = toolkit.getSystemClipboard();5748 return (String) clipboard.getData(DataFlavor.stringFlavor);5749 }5750 /**5751 * @author Cigniti5752 * @description: kill unwanted pop in web5753 */5754 public void killPopup(String textInURL) {5755 try {5756 String windowHandle = driver.getWindowHandle();5757 for (String window : driver.getWindowHandles()) {5758 WebDriver temp = driver.switchTo().window(window);5759 if (temp.getCurrentUrl().toLowerCase().contains(textInURL)) {5760 temp.close();5761 }5762 }5763 driver.switchTo().window(windowHandle);5764 } catch (Exception e) {5765 }5766 }5767 /**5768 * @author Cigniti5769 * @description: switch to iframe5770 * @param frame_element5771 * @return5772 */5773 public static WebDriver SwitchToiFrame(WebElement frame_element) {5774 CommonVariables.getDriver().switchTo().frame(frame_element);5775 CommonVariables.setDriver((EventFiringWebDriver) CommonVariables.getDriver());5776 return CommonVariables.getDriver();5777 }5778 /**5779 * @author Cigniti5780 * @description: switch back to default content from iframe5781 * @return5782 */5783 public static WebDriver SwitchBackFromiFrameToMaincontent() {5784 CommonVariables.getDriver().switchTo().defaultContent();5785 CommonVariables.setDriver((EventFiringWebDriver) CommonVariables.getDriver());5786 return CommonVariables.getDriver();5787 }5788 /**5789 * @author Cigniti5790 * @description: get current time zone5791 * @return5792 */5793 public static String getCurrentTimeZone() {5794 String timeZone = null;5795 // get Calendar instance5796 Calendar now = Calendar.getInstance();5797 // get current TimeZone using getTimeZone method of Calendar class5798 TimeZone tZone = now.getTimeZone();5799 // display current TimeZone using getDisplayName() method of TimeZone5800 // class5801 timeZone = tZone.getDisplayName();5802 return timeZone;5803 }5804 /**5805 * @author Cigniti5806 * @description: Robot class should be use only when keyboard inputs are5807 * required and all other Options like, ACtion Class,5808 * Webdriver Send Keys.. are not working.5809 * @return5810 * @throws AWTException5811 */5812 public Robot roboticMethod() throws AWTException {5813 Robot robot = new Robot();5814 return robot;5815 }5816 /**5817 * @author Cigniti5818 * @description: Maximum '6' times user can use tab click through robotium.5819 * @param numberofClick5820 * @throws AWTException5821 */5822 public void roboticTabClick(int numberofClick) throws AWTException {5823 switch (numberofClick) {5824 case 1:5825 roboticMethod().keyPress(KeyEvent.VK_TAB);5826 break;5827 case 2:5828 roboticMethod().keyPress(KeyEvent.VK_TAB);5829 roboticMethod().keyPress(KeyEvent.VK_TAB);5830 break;5831 case 3:5832 roboticMethod().keyPress(KeyEvent.VK_TAB);5833 roboticMethod().keyPress(KeyEvent.VK_TAB);5834 roboticMethod().keyPress(KeyEvent.VK_TAB);5835 break;5836 case 4:5837 roboticMethod().keyPress(KeyEvent.VK_TAB);5838 roboticMethod().keyPress(KeyEvent.VK_TAB);5839 roboticMethod().keyPress(KeyEvent.VK_TAB);5840 roboticMethod().keyPress(KeyEvent.VK_TAB);5841 break;5842 case 5:5843 roboticMethod().keyPress(KeyEvent.VK_TAB);5844 roboticMethod().keyPress(KeyEvent.VK_TAB);5845 roboticMethod().keyPress(KeyEvent.VK_TAB);5846 roboticMethod().keyPress(KeyEvent.VK_TAB);5847 roboticMethod().keyPress(KeyEvent.VK_TAB);5848 break;5849 case 6:5850 roboticMethod().keyPress(KeyEvent.VK_TAB);5851 roboticMethod().keyPress(KeyEvent.VK_TAB);5852 roboticMethod().keyPress(KeyEvent.VK_TAB);5853 roboticMethod().keyPress(KeyEvent.VK_TAB);5854 roboticMethod().keyPress(KeyEvent.VK_TAB);5855 roboticMethod().keyPress(KeyEvent.VK_TAB);5856 break;5857 default:5858 System.out.println("Tab not clicked.");5859 break;5860 }5861 }5862 /**5863 * @author Cigniti5864 * @return5865 */5866 public static Action actionMethod() {5867 Action action = (Action) new Actions(CommonVariables.CommonDriver.get());5868 return action;5869 }5870 public String GetCurrentTime() {5871 DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss a");5872 String currenttime = df.format(Calendar.getInstance().getTime());5873 return currenttime;5874 }5875 /**5876 * @author Cigniti5877 * @param filename5878 */5879 public void fileSeparator(String filename) {5880 try {5881 String workingDirectory = System.getProperty("user.dir").replace("\\", "/");5882 String absoluteFilePath = "";5883 String osname = System.getProperty("os.name");5884 String fileSeparator = File.separator;5885 if (osname.contains("windows")) {5886 fileSeparator = "/";5887 } else {5888 if (osname.contains("linux") || osname.contains("Unix") || osname.contains("Mac")) {5889 fileSeparator = "/";5890 }5891 }5892 absoluteFilePath = workingDirectory + fileSeparator + filename;5893 System.out.println("Final filepath : " + absoluteFilePath);5894 } catch (Exception e) {5895 e.printStackTrace();5896 }5897 }5898 /**5899 * @author Cigniti5900 * @param workbookName5901 * @throws IOException5902 */5903 public void DeleteFiles(String workbookName) throws IOException {5904 try {5905 System.out.println("Called deleteFiles");5906 File file = new File(System.getProperty("user.dir") + "\\TestData\\" + workbookName);5907 String[] myFiles;5908 if (file.isDirectory()) {5909 myFiles = file.list();5910 for (int i = 0; i < myFiles.length; i++) {5911 File myFile = new File(file, myFiles[i]);5912 System.out.println(myFile);5913 myFile.delete();5914 }5915 }5916 } catch (Exception e) {5917 System.out.println(e.getMessage());5918 }5919 }5920 /**5921 * @author Cigniti5922 * @param waitTime5923 * @param pollingCycle5924 */5925 @SuppressWarnings({ "rawtypes", "unchecked" })5926 public void fluentWait(int waitTime, int pollingCycle) {5927 try {5928 FluentWait wait = new FluentWait(this.driver);5929 wait.withTimeout(waitTime, TimeUnit.SECONDS);5930 wait.pollingEvery(pollingCycle, TimeUnit.SECONDS);5931 wait.ignoring(NoSuchElementException.class);5932 } catch (Exception e) {5933 System.out.println("unable to perform an action for fluent wait due to execption - " + e.getMessage());5934 }5935 }5936 /**5937 * Wrap the Selenium run time exception with more debug info.5938 */5939 protected String makeSeleniumExceptionMessage(Page page, Throwable e) {5940 String result = "SeleniumException found on page " + page.getClass();5941 String fullMessage = e.getMessage();5942 return result + "\n" + fullMessage.substring(0, fullMessage.indexOf("\n"));5943 }5944 /**5945 * @author Cigniti5946 * @param folderPath5947 * @return5948 */5949 public static File[] getFiles(String folderPath) {5950 File arrayFiles[] = null;5951 List<File> listFiles = new ArrayList<File>();5952 traverseFolder(new File(folderPath), listFiles);5953 // get the size of listFiles to initialize the size of array5954 arrayFiles = new File[listFiles.size()];5955 arrayFiles = listFiles.toArray(arrayFiles);5956 return arrayFiles;5957 }5958 /**5959 * @author Cigniti5960 * @param file5961 * @param listFiles5962 */5963 private static void traverseFolder(File file, List<File> listFiles) {5964 // if current file is folder, look for files inside it.5965 if (file.isDirectory()) {5966 File[] files = file.listFiles();5967 for (File aFile : files) {5968 // recursive call5969 traverseFolder(aFile, listFiles);5970 }5971 } else // add the file to list5972 {5973 listFiles.add(file);5974 }5975 }5976 /**5977 * @author Cigniti readTextFile5978 * @param filePath5979 */5980 public List<String> readTextFile(String filePath) {5981 List<String> list = new ArrayList<String>();5982 String line = null;5983 try {5984 FileReader reader = new FileReader(filePath);5985 BufferedReader bufferedReader = new BufferedReader(reader);5986 while ((line = bufferedReader.readLine()) != null) {5987 list.add(line);5988 }5989 reader.close();5990 } catch (IOException e) {5991 e.printStackTrace();5992 }5993 return list;5994 }5995 /**5996 * Robot mouse over.5997 * 5998 * @author Cigniti5999 * @param by6000 * the by6001 * @throws Exception6002 * the exception6003 */6004 public void robotMouseOver(By by) throws Exception {6005 try {6006 Point point = this.driver.findElement(by).getLocation();6007 int xcord = point.getX();6008 int ycord = point.getY();6009 Robot robot = new Robot();6010 robot.mouseMove(xcord + 30, ycord + 100); // move mouse point to6011 // specific location6012 robot.delay(1500); // delay is to make code wait for mentioned6013 // milliseconds before executing next step6014 /*6015 * robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); // press left6016 * click robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); //6017 * release left click robot.delay(1500);6018 * robot.keyPress(KeyEvent.VK_DOWN); // press keyboard arrow key to6019 * select Save radio button Thread.sleep(2000);6020 * robot.keyPress(KeyEvent.VK_ENTER); Thread.sleep(3000);6021 */6022 } catch (Exception e) {6023 throw e;6024 }6025 }6026 /**6027 * Wait for text.6028 *6029 * @param by6030 * the by6031 * @param locator6032 * the locator6033 * @param secs6034 * the secs6035 * @return true, if successful6036 * @throws Throwable6037 * the throwable6038 */6039 public boolean waitForText(By by, String locator, int secs) throws Throwable {6040 boolean status = false;6041 try {6042 WebDriverWait wait = new WebDriverWait(this.driver, 60);6043 ScrollToElementVisible(by);6044 wait.until(ExpectedConditions.textToBePresentInElementLocated(by, locator));6045 for (int i = 0; i < secs / 2; i++) {6046 List<WebElement> elements = this.driver.findElements(by);6047 if (elements.size() > 0) {6048 status = true;6049 return status;6050 } else {6051 this.driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);6052 }6053 }6054 } catch (Exception e) {6055 return status;6056 }6057 return status;6058 }6059 /**6060 * Close all other windows.6061 * 6062 * @author Cigniti6063 * @param driver6064 * the driver6065 * @param openWindowHandle6066 * the open window handle6067 * @return true, if successful6068 */6069 public static boolean closeAllOtherWindows(WebDriver driver, String openWindowHandle) {6070 Set<String> allWindowHandles = driver.getWindowHandles();6071 for (String currentWindowHandle : allWindowHandles) {6072 if (!currentWindowHandle.equals(openWindowHandle)) {6073 driver.switchTo().window(currentWindowHandle);6074 driver.close();6075 }6076 }6077 driver.switchTo().window(openWindowHandle);6078 if (driver.getWindowHandles().size() == 1)6079 return true;6080 else6081 return false;6082 }6083 /**6084 * Select value from drop down for edge browser6085 * 6086 * @param elementBy6087 * @param selectionValue6088 */6089 public void selectListValueEdge(By elementBy, String selectionValue) {6090 try {6091 WebElement webElement = this.driver.findElement(elementBy);6092 webElement.click();6093 webElement.sendKeys(selectionValue);6094 webElement.sendKeys(Keys.ENTER);6095 } catch (Exception ex) {6096 ex.printStackTrace();6097 }6098 }6099 /**6100 * @author Cigniti Browse and upload.6101 * @param filePath6102 * the file path6103 * @param locator6104 * the locator6105 * @param locatorName6106 * the locator name6107 * @return true, if successful6108 * @throws Throwable6109 * the throwable6110 */6111 public boolean browseAndUpload(String filePath, WebElement webElement) throws Throwable {6112 boolean flag = false;6113 try {6114 Click(webElement);6115 Thread.sleep(4000);6116 // Copy the file's absolute path to the clipboard6117 StringSelection ss = new StringSelection(filePath);6118 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);6119 // native key strokes for CTRL, V and ENTER keys6120 Robot robot = new Robot();6121 Thread.sleep(2000);6122 robot.keyPress(KeyEvent.VK_CONTROL);6123 Thread.sleep(2000);6124 robot.keyPress(KeyEvent.VK_V);6125 Thread.sleep(2000);6126 robot.keyRelease(KeyEvent.VK_V);6127 Thread.sleep(2000);6128 robot.keyRelease(KeyEvent.VK_CONTROL);6129 Thread.sleep(2000);6130 robot.keyPress(KeyEvent.VK_ENTER);6131 Thread.sleep(2000);6132 robot.keyRelease(KeyEvent.VK_ENTER);6133 Thread.sleep(2000);6134 flag = true;6135 } catch (NoAlertPresentException ex) {6136 ex.printStackTrace();6137 }6138 return flag;6139 }6140 /**6141 * @author Cigniti6142 * @param filePath6143 * @param element6144 * @param time6145 * @param locatorName6146 * @return6147 * @throws Throwable6148 */6149 public boolean uploadFile(String filePath, WebElement element, int time, String locatorName) throws Throwable {6150 boolean flag = false;6151 try {6152 WebDriverWait wait = new WebDriverWait(this.driver, 60);6153 ScrollToElementVisible(element);6154 wait.until(ExpectedConditions.elementToBeClickable(element));6155 Click(element, time);6156 Thread.sleep(5000);6157 Actions KeyboardEvent = new Actions(this.driver);6158 KeyboardEvent.sendKeys(filePath);6159 Thread.sleep(1000);6160 KeyboardEvent.sendKeys(Keys.ENTER);6161 flag = true;6162 } catch (NoAlertPresentException ex) {6163 ex.printStackTrace();6164 flag = false;6165 }6166 return flag;6167 }6168 /**6169 * @author Cigniti6170 */6171 public void ScrollToTop(WebDriver driver) {6172 try {6173 JavascriptExecutor js = (JavascriptExecutor) driver;6174 js.executeScript("window.scrollBy(0,-1000)", "");6175 } catch (Exception e) {6176 e.printStackTrace();6177 }6178 }6179 /**6180 * @author Cigniti6181 * @param element6182 */6183 public void SwipeRight(WebElement element) {6184 // Executing swipe on in the case of iOS simulators. Skipping it for6185 // Android Chrome as this swipe will not yet implemented on it.6186 try {6187 String driverName = GetDriverInfo().get("DriverName").toLowerCase();6188 if ((!driverName.equals("android-chrome")) && (!driverName.equals("chrome"))6189 && (!driverName.equals("chrome-mac")) && (!driverName.equals("safari"))6190 && (!driverName.equals("firefox")) && (!driverName.equals("ie")) && (!driverName.equals("edge"))6191 && (!driverName.equals("opera"))) {6192 double browser_top_offset = 0.0;6193 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("mobile")) {6194 browser_top_offset = 0;6195 } else if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("tablet")) {6196 browser_top_offset = 80;6197 }6198 /*6199 * if(ConfigManager.getProperties().getProperty("seleniumGrid").6200 * trim().equalsIgnoreCase("true")6201 * ||GetDriverInfo().get("DriverType").trim().equalsIgnoreCase(6202 * "mobile")6203 * ||GetDriverInfo().get("DriverType").trim().equalsIgnoreCase(6204 * "tablet")){ }6205 */6206 // RemoteWebElement remoteelem = ((RemoteWebElement)element);6207 WebElement remoteelem = element;6208 JavascriptExecutor js = (JavascriptExecutor) driver;6209 String script = "return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)";6210 Long pageheight1 = (Long) js.executeScript(script);6211 Long pagewidth1 = (Long) js6212 .executeScript("return Math.max(document.documentElement.clientWidth, window.innerWidth || 0)");6213 // Long pageheight2=(Long)js.executeScript("return6214 // window.innerHeight");6215 Point eloc = remoteelem.getLocation();6216 double yloc = eloc.getY();6217 double xstartloc = eloc.getX();6218 double xendloc = eloc.getX() + remoteelem.getSize().width;6219 Double swipe_startxratio = xstartloc / pagewidth1;6220 Double swipe_endxratio = xendloc / pagewidth1;6221 double elemheight = remoteelem.getSize().getHeight() / 2;6222 Double yratio = (yloc + elemheight / 2 + browser_top_offset) / pageheight1;6223 if (swipe_startxratio < 0.1) {6224 swipe_startxratio = 0.1;6225 }6226 if (swipe_endxratio > 0.9) {6227 swipe_endxratio = 0.9;6228 }6229 /*6230 * HashMap<String, Double> swipeObject = new HashMap<String,6231 * Double>(); swipeObject.put("startX", swipe_endxratio);6232 * swipeObject.put("startY", yratio); swipeObject.put("endX",6233 * swipe_startxratio); swipeObject.put("endY", yratio);6234 * swipeObject.put("duration", 0.8); // js.executeScript(6235 * "mobile: swipe", swipeObject); appiumDriver.execute(6236 * "mobile: swipe", swipeObject);6237 */6238 if (appiumDriver != null) {6239 appiumDriver.swipe(swipe_endxratio.intValue(), yratio.intValue(), swipe_startxratio.intValue(),6240 yratio.intValue(), 1);6241 }6242 }6243 if (GetDriverInfo().get("DriverName").toLowerCase().equals("chrome")6244 | GetDriverInfo().get("DriverName").toLowerCase().equals("chrome-mac")6245 | GetDriverInfo().get("DriverName").toLowerCase().equals("internet_explorer")) {6246 Actions builder = new Actions(driver);6247 // element.getSize();6248 Action dragAndDrop = builder.clickAndHold(element)6249 .moveToElement(element, element.getLocation().x + 90, element.getLocation().y).release()6250 .build();6251 dragAndDrop.perform();6252 try {6253 Thread.sleep(4000);6254 } catch (InterruptedException e) {6255 }6256 }6257 if (GetDriverInfo().get("DriverName").toLowerCase().equals("safari")6258 || GetDriverInfo().get("DriverName").toLowerCase().equals("firefox")) {6259 JavascriptExecutor js = (JavascriptExecutor) driver;6260 js.executeScript("$('.owl-wrapper').trigger('owl.next')");6261 }6262 } catch (Exception e) {6263 System.out.println(e.getMessage());6264 }6265 }6266 /**6267 * @author Cigniti6268 * @description : Swipe Bottom6269 * @param element6270 */6271 public void SwipeBottom(WebElement remoteelem) {6272 if (remoteelem != null) {6273 if (!GetDriverInfo().get("DriverName").equals("androidchrome")6274 && !GetDriverInfo().get("DriverType").toLowerCase().equals("desktop")) {6275 double browser_top_offset = 0.0;6276 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("mobile")) {6277 browser_top_offset = 0;6278 } else if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("tablet")) {6279 browser_top_offset = 240;6280 }6281 // RemoteWebElement remoteelem = ((RemoteWebElement)element);6282 // JavascriptExecutor js = (JavascriptExecutor)driver;6283 Point eloc = remoteelem.getLocation();6284 double yloc = eloc.getY();6285 double xloc = eloc.getX() + remoteelem.getSize().width / 2;6286 Double swipe_xratio = xloc;6287 double elemheight = remoteelem.getSize().getHeight();6288 Double yStartRatio = (yloc + elemheight + browser_top_offset) / 2;6289 Double yEndRatio = (eloc.getY() + browser_top_offset);6290 if (swipe_xratio < 10.0) {6291 swipe_xratio = 10.0;6292 }6293 if (yEndRatio < 50.0) {6294 yEndRatio = 50.0;6295 }6296 HashMap<String, Double> swipeObject = new HashMap<String, Double>();6297 swipeObject.put("startX", swipe_xratio);6298 swipeObject.put("startY", yStartRatio);6299 swipeObject.put("endX", swipe_xratio);6300 swipeObject.put("endY", yEndRatio);6301 swipeObject.put("duration", 1.0);6302 // js.executeScript("mobile: swipe", swipeObject);6303 if (appiumDriver != null && appiumDriver.getClass().toString().toUpperCase().contains("IOS")) {6304 appiumDriver.swipe(swipe_xratio.intValue(), yStartRatio.intValue(), swipe_xratio.intValue(),6305 yEndRatio.intValue(), 1);6306 }6307 }6308 }6309 }6310 /**6311 * @author Cigniti6312 * @description : Swipe Left6313 * @param element6314 */6315 public void SwipeLeft(WebElement element) {6316 // Executing swipe on in the case of iOS simulators. Skipping it for6317 // Android Chrome as this swipe will not yet implemented on it.6318 if ((!GetDriverInfo().get("DriverName").toLowerCase().equals("androidchrome"))6319 && (!GetDriverInfo().get("DriverName").toLowerCase().equals("chrome"))6320 && (!GetDriverInfo().get("DriverName").toLowerCase().equals("chrome-mac"))6321 && (!GetDriverInfo().get("DriverName").toLowerCase().equals("safari"))) {6322 if (appiumDriver != null) {6323 double browser_top_offset = 0.0;6324 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("mobile")) {6325 browser_top_offset = 0;6326 } else if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("tablet")) {6327 browser_top_offset = 80;6328 }6329 // RemoteWebElement remoteelem = ((RemoteWebElement)element);6330 WebElement remoteelem = element;6331 JavascriptExecutor js = (JavascriptExecutor) this.driver;6332 String script = "return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)";6333 Long pageheight1 = (Long) js.executeScript(script);6334 Long pagewidth1 = (Long) js6335 .executeScript("return Math.max(document.documentElement.clientWidth, window.innerWidth || 0)");6336 // Long pageheight2=(Long)js.executeScript("return6337 // window.innerHeight");6338 Point eloc = remoteelem.getLocation();6339 double yloc = eloc.getY();6340 double xstartloc = eloc.getX();6341 double xendloc = eloc.getX() + remoteelem.getSize().width;6342 Double swipe_startxratio = xstartloc / pagewidth1;6343 Double swipe_endxratio = xendloc / pagewidth1;6344 double elemheight = remoteelem.getSize().getHeight() / 2;6345 Double yratio = (yloc + elemheight / 2 + browser_top_offset) / pageheight1;6346 if (swipe_startxratio < 0.05) {6347 swipe_startxratio = 0.05;6348 }6349 if (swipe_endxratio > .95) {6350 swipe_endxratio = 0.95;6351 }6352 /*6353 * HashMap<String, Double> swipeObject = new HashMap<String,6354 * Double>(); swipeObject.put("startX", swipe_startxratio);6355 * swipeObject.put("startY", yratio); swipeObject.put("endX",6356 * swipe_endxratio); swipeObject.put("endY", yratio);6357 * swipeObject.put("duration", 0.8); js.executeScript(6358 * "mobile: swipe", swipeObject);6359 */6360 appiumDriver.swipe(swipe_endxratio.intValue(), yratio.intValue(), swipe_startxratio.intValue(),6361 yratio.intValue(), 1);6362 }6363 }6364 if (GetDriverInfo().get("DriverName").toLowerCase().equals("chrome")6365 | GetDriverInfo().get("DriverName").toLowerCase().equals("chrome-mac")) {6366 Actions builder = new Actions(driver);6367 Action dragAndDrop = builder.clickAndHold(element)6368 .moveToElement(element, element.getLocation().x + 800, element.getLocation().y + 10).release()6369 .build();6370 dragAndDrop.perform();6371 try {6372 Thread.sleep(4000);6373 } catch (InterruptedException e) {6374 }6375 }6376 if (GetDriverInfo().get("DriverName").toLowerCase().equals("safari")) {6377 JavascriptExecutor js = (JavascriptExecutor) driver;6378 js.executeScript("$('.owl-wrapper').trigger('owl.prev')");6379 }6380 }6381 /**6382 * @author Cigniti6383 * @description : Pinch Open6384 */6385 public void PinchOpen() {6386 JavascriptExecutor js = (JavascriptExecutor) this.driver;6387 HashMap<String, Double> swipeObject = new HashMap<String, Double>();6388 swipeObject.put("startX", (double) 114);6389 swipeObject.put("startY", (double) 198);6390 swipeObject.put("endX", (double) 257);6391 swipeObject.put("endY", (double) 256);6392 swipeObject.put("duration", 1.8);6393 js.executeScript("mobile: pinchOpen", swipeObject);6394 }6395 /**6396 * @author Cigniti6397 * @description : Pinch Close6398 */6399 public void PinchClose() {6400 JavascriptExecutor js = (JavascriptExecutor) this.driver;6401 HashMap<String, Double> swipeObject = new HashMap<String, Double>();6402 swipeObject.put("startX", (double) 150);6403 swipeObject.put("startY", (double) 230);6404 swipeObject.put("endX", (double) 200);6405 swipeObject.put("endY", (double) 260);6406 swipeObject.put("duration", 1.8);6407 js.executeScript("mobile: pinchOpen", swipeObject);6408 }6409 /**6410 * @author Cigniti6411 * @description : Change Orientation - // "LANDSCAPELEFT" , "LANDSCAPERIGHT"6412 * , "PORTRAIT"6413 * @param Orientation6414 */6415 public void ChangeOrientation(String Orientation) { // Valid values are:6416 // "LANDSCAPELEFT" ,6417 // "LANDSCAPERIGHT" ,6418 // "PORTRAIT"6419 JavascriptExecutor js = (JavascriptExecutor) this.driver;6420 js.executeScript("target.setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT);");6421 }6422 6423 public boolean mouseHoverByJavaScript(By locator, String locatorName)6424 throws Throwable {6425 boolean flag = false;6426 try {6427 WebElement mo = driver.findElement(locator);6428 /*String javaScript = "var evObj = document.createEvent('MouseEvents');"6429 + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"6430 + "arguments[0].dispatchEvent(evObj);";6431 JavascriptExecutor js = (JavascriptExecutor) driver;6432 js.executeScript(javaScript, mo); */6433 Actions a = new Actions(driver);6434 a.moveToElement(mo).build().perform();6435 flag = true;6436 return true;6437 }6438 catch (Exception e) {6439 return false;6440 } finally {6441 if (!flag) {6442 extentLogs.fail("MouseOver ",6443 "MouseOver Action was <b>NOT</b> perform on <b>" + locatorName + "</b>");6444 } else if (flag) {6445 extentLogs.pass("MouseOver ",6446 "MouserOver Action was performed on <b>" + locatorName + "</b>");6447 }6448 }6449 }6450 6451 public boolean mouseover(By locator, String locatorName)6452 throws Throwable {6453 boolean flag = false;6454 try {6455 WebElement mo = driver.findElement(locator);6456 new Actions(driver).moveToElement(mo).build().perform();6457 6458 flag = true;6459 return true;6460 } catch (Exception e) {6461 Assert.assertTrue(flag,"MouseOver action is not performed on " + locatorName);6462 return false;6463 } finally {6464 if (!flag) {6465 extentLogs.fail("MouseOver",6466 "MouseOver action is not performed on " + locatorName);6467 Assert.assertTrue(flag,"Unable find the element "+ locatorName);6468 } else if (flag) {6469 extentLogs.pass("MouseOver ",6470 "MouserOver Action is performed on <b>" + locatorName + "</b>");6471 }6472 }6473 }6474}...

Full Screen

Full Screen

Source:MobileLibrary.java Github

copy

Full Screen

1package com.mobile.automation.accelerators;2import java.awt.AWTException;3import java.awt.Robot;4import java.awt.Toolkit;5import java.awt.datatransfer.Clipboard;6import java.awt.datatransfer.DataFlavor;7import java.awt.datatransfer.StringSelection;8import java.awt.datatransfer.UnsupportedFlavorException;9import java.awt.event.KeyEvent;10import java.io.BufferedReader;11import java.io.File;12import java.io.FileInputStream;13import java.io.FileNotFoundException;14import java.io.FileOutputStream;15import java.io.FileReader;16import java.io.FileWriter;17import java.io.IOException;18import java.io.InputStream;19import java.io.InputStreamReader;20import java.io.OutputStream;21import java.io.PrintWriter;22import java.io.StringWriter;23import java.net.HttpURLConnection;24import java.net.InetAddress;25import java.net.MalformedURLException;26import java.net.NetworkInterface;27import java.net.URL;28import java.text.DateFormat;29import java.text.ParseException;30import java.text.SimpleDateFormat;31import java.util.ArrayList;32import java.util.Calendar;33import java.util.Date;34import java.util.Enumeration;35import java.util.GregorianCalendar;36import java.util.HashMap;37import java.util.Iterator;38import java.util.List;39import java.util.Map;40import java.util.Set;41import java.util.TimeZone;42import java.util.concurrent.TimeUnit;43import java.util.logging.Level;44import java.util.regex.Matcher;45import java.util.regex.Pattern;46import org.apache.commons.io.FileUtils;47import org.apache.commons.io.IOUtils;48import org.apache.http.HttpHost;49import org.apache.http.HttpResponse;50import org.apache.http.client.ClientProtocolException;51import org.apache.http.client.CookieStore;52import org.apache.http.client.HttpClient;53import org.apache.http.client.methods.HttpGet;54import org.apache.http.client.params.ClientPNames;55import org.apache.http.client.params.CookiePolicy;56import org.apache.http.client.protocol.ClientContext;57import org.apache.http.cookie.ClientCookie;58import org.apache.http.impl.client.BasicCookieStore;59import org.apache.http.impl.client.DefaultHttpClient;60import org.apache.http.impl.cookie.BasicClientCookie2;61import org.apache.http.message.BasicHttpEntityEnclosingRequest;62import org.apache.http.protocol.BasicHttpContext;63import org.apache.http.protocol.HttpContext;64import org.joda.time.LocalDate;65import org.joda.time.Years;66import org.json.JSONException;67import org.json.JSONObject;68import org.openqa.selenium.Alert;69import org.openqa.selenium.By;70import org.openqa.selenium.Cookie;71import org.openqa.selenium.Dimension;72import org.openqa.selenium.ElementNotVisibleException;73import org.openqa.selenium.JavascriptExecutor;74import org.openqa.selenium.Keys;75import org.openqa.selenium.NoAlertPresentException;76import org.openqa.selenium.NoSuchElementException;77import org.openqa.selenium.OutputType;78import org.openqa.selenium.Platform;79import org.openqa.selenium.Point;80import org.openqa.selenium.Proxy;81import org.openqa.selenium.StaleElementReferenceException;82import org.openqa.selenium.TakesScreenshot;83import org.openqa.selenium.TimeoutException;84import org.openqa.selenium.UnhandledAlertException;85import org.openqa.selenium.WebDriver;86import org.openqa.selenium.WebDriverException;87import org.openqa.selenium.WebElement;88import org.openqa.selenium.chrome.ChromeDriver;89import org.openqa.selenium.chrome.ChromeOptions;90import org.openqa.selenium.edge.EdgeDriver;91import org.openqa.selenium.firefox.FirefoxDriver;92import org.openqa.selenium.firefox.FirefoxProfile;93import org.openqa.selenium.firefox.internal.ProfilesIni;94import org.openqa.selenium.html5.Location;95import org.openqa.selenium.ie.InternetExplorerDriver;96import org.openqa.selenium.interactions.Action;97import org.openqa.selenium.interactions.Actions;98import org.openqa.selenium.logging.LogEntries;99import org.openqa.selenium.logging.LogEntry;100import org.openqa.selenium.logging.LogType;101import org.openqa.selenium.logging.LoggingPreferences;102import org.openqa.selenium.opera.OperaOptions;103import org.openqa.selenium.phantomjs.PhantomJSDriver;104import org.openqa.selenium.phantomjs.PhantomJSDriverService;105import org.openqa.selenium.remote.Augmenter;106import org.openqa.selenium.remote.CapabilityType;107import org.openqa.selenium.remote.DesiredCapabilities;108import org.openqa.selenium.remote.HttpCommandExecutor;109import org.openqa.selenium.remote.RemoteWebDriver;110import org.openqa.selenium.remote.RemoteWebElement;111import org.openqa.selenium.remote.SessionNotFoundException;112import org.openqa.selenium.safari.SafariDriver;113import org.openqa.selenium.safari.SafariOptions;114import org.openqa.selenium.support.events.EventFiringWebDriver;115import org.openqa.selenium.support.ui.ExpectedConditions;116import org.openqa.selenium.support.ui.FluentWait;117import org.openqa.selenium.support.ui.Select;118import org.openqa.selenium.support.ui.WebDriverWait;119import org.testng.Assert;120import org.testng.SkipException;121import com.google.common.base.Optional;122import com.web.automation.bmp.BMP_Proxy_Controller;123import com.web.automation.listeners.MyListener;124import com.web.automation.listeners.WebDriverListener;125import com.web.automation.logs.CustomLogName;126import com.web.automation.logs.CustomLogs;127import com.web.automation.logs.ExtentLogs;128import com.web.automation.utilities.CaptureScreenShot;129import com.web.automation.utilities.CommonVariables;130import com.web.automation.utilities.ConfigManager;131//import com.mobile.automation.accelerators.132import io.appium.java_client.AppiumDriver;133import io.appium.java_client.android.AndroidDriver;134import io.appium.java_client.ios.IOSDriver;135import io.appium.java_client.remote.MobileCapabilityType;136import net.lightbody.bmp.proxy.jetty.html.Page;137public class MobileLibrary extends MyListener {138 public static WebDriver wd;139 public static EventFiringWebDriver EventFiringWebDriver;140 private WebDriverListener eventListener;141 public static RemoteWebDriver rdriver;142 public static AppiumDriver driver;143 private WebDriverWait wait;144 public static int driverStartfailureCount = 1;145 private DesiredCapabilities objCapabilities;146 private ChromeOptions chromeoptions;147 private OperaOptions operaOptions;148 private Set<String> arrKnownBrowserHwnd; // Stores windows handle when149 // launching a new browser150 public String hwndFirstWindow; // This will store handle of original window151 public String hwndMostRecentWindow; // This will store handle of most152 // recently known window153 public Boolean locationServiceEnabled;154 private Boolean doFullReset;155 private String chromeProfile;156 private String firefoxProfilePath;157 private String safariProfilePath;158 private LoggingPreferences prefs;159 private ExtentLogs extentLogs = new ExtentLogs();160 private FileWriter fw;161 private PrintWriter pw;162 private int CurrentMonthDays;163 private static String downloadedfilepath;164 private FirefoxProfile firefoxProfile;165 public static String gStrErrMsg = " ";166 167 @SuppressWarnings("static-access")168 public MobileLibrary(WebDriver driver) {169// this.driver = (EventFiringWebDriver) driver;170 this.driver = (AppiumDriver) driver;171 initPropertiesFile();172 173 this.locationServiceEnabled = Boolean174 .parseBoolean(ConfigManager.getProperties().getProperty("locationServiceEnabled").trim().toLowerCase());175 doFullReset = true;176 if (this.locationServiceEnabled) {177 this.chromeProfile = "browser-profile-location-boston";178 this.firefoxProfilePath = "Firefox_profile_For_Location_Simulate";179 this.safariProfilePath = "Safari_Shared_Location_Profile";180 }181 }182 /**183 * @author Cigniti184 * @description: setter for EventFiringWebDriver185 * @param driver186 */187 public void setDriver(EventFiringWebDriver EventFiringWebDriver) {188 this.EventFiringWebDriver = EventFiringWebDriver;189 }190 /**191 * @author Cigniti192 * @description: setter for AppiumDriver193 * @param driver194 */195 public void setDriver(AppiumDriver AppiumDriver) {196 this.driver = AppiumDriver;197 }198 199 /**200 * @author Cigniti201 */202 public MobileLibrary() {203 initPropertiesFile();204 }205 /**206 * @author Cigniti207 * @description: Intialize config properties208 */209 private void initPropertiesFile() {210 try {211 if (!ConfigManager.ArePropertiesSet.get()) {212 ConfigManager.getProperties();213 ConfigManager.UpdateProperties();214 }215 } catch (Exception e) {216 e.getLocalizedMessage();217 }218 }219 /**220 * @author Cigniti221 * @description : Webdriver Wait For Page with time222 * @param time223 */224 @SuppressWarnings("static-access")225 public void WebdriverWaitForPage() {226 this.driver.manage().timeouts().implicitlyWait(227 Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut")), TimeUnit.SECONDS);228 }229 /**230 * @author Cigniti231 * @description : start webdriver with an instance of browser type.232 * @param browserType233 * @return234 */235 @SuppressWarnings("static-access")236 public WebDriver instantiateDriver(String browserType, String UDID, String platformVersion, String browserName, String serverURL) {237 String chromeprofilepath = null;238 Process process = null;239 DesiredCapabilities objCapabilities;240 try {241 String osname = System.getProperty("os.name");242 String DriverPath = "";243 //tearDown();244 System.out.println("************ Starting the driver: " + browserType + " ***************");245 downloadedfilepath = System.getProperty("user.dir").replace("\\", "/") + "/Tool/downloadedFiles";246 switch (browserType.trim().toLowerCase()) {247 case "windows-android-device":248 case "windows-android":249 objCapabilities = new DesiredCapabilities();250 String AppPackage = ConfigManager.getProperties().getProperty("appPackage");251 String AppActivity = ConfigManager.getProperties().getProperty("appActivity");252 System.out.println(AppActivity);253 254 objCapabilities.setCapability("deviceName","AndroidDevice");255 objCapabilities.setCapability("platformVersion", platformVersion);256 objCapabilities.setCapability("platformName", "Android");257 objCapabilities.setCapability(MobileCapabilityType.UDID, UDID);258 objCapabilities.setCapability("user", ConfigManager.getProperties().getProperty("SeeTestUserName"));259 objCapabilities.setCapability("password", ConfigManager.getProperties().getProperty("SeeTestPassword"));260 objCapabilities.setCapability("noReset", "true");261 objCapabilities.setCapability("appPackage", AppPackage);262 objCapabilities.setCapability("appActivity", AppActivity);263 264 265 File file1 = new File(System.getProperty("user.dir") + ConfigManager.getProperties().getProperty("apkPath"));266 //objCapabilities.setCapability("app", file1.getAbsolutePath());267 //objCapabilities.setCapability(MobileCapabilityType.APP, file1.getAbsolutePath() );268 /////SeeTest Reporting269 objCapabilities.setCapability("reportDirectory", "reports");270 objCapabilities.setCapability("reportFormat", "xml");271 272 try {273 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {274 rdriver = null;275 rdriver = new AndroidDriver(new URL(serverURL), objCapabilities);276 Thread.sleep(10000);277 break;278 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim().contains("true")) {279 rdriver = null;280 rdriver = new AndroidDriver(new URL(serverURL), objCapabilities);281 Thread.sleep(10000);282 break;283 } else {284 rdriver = null;285 this.driver = new AndroidDriver(new URL(serverURL), objCapabilities);286 this.rdriver = driver;287 Thread.sleep(10000);288 }289 try {290 Thread.sleep(2500);291 } catch (InterruptedException e) {292 e.printStackTrace();293 }294 suppressCredential();295 break;296 } catch (MalformedURLException e) {297 e.printStackTrace();298 break;299 }300 case "windows-android-web":301 objCapabilities = new DesiredCapabilities();302 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");303 objCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");304 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, platformVersion);305 objCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Samsung S7");306// objCapabilities.setCapability("locale", "US");307// objCapabilities.setCapability("deviceReadyTimeout", "450");308 objCapabilities.setCapability("newCommandTimeout", "1000000");309// objCapabilities.setCapability("fullReset", false);310// objCapabilities.setCapability("autoLaunch", true);311// objCapabilities.setCapability("autoAcceptAlerts", true);312 objCapabilities.setCapability(MobileCapabilityType.UDID, UDID);313 objCapabilities.setCapability("user", ConfigManager.getProperties().getProperty("SeeTestUserName"));314 objCapabilities.setCapability("password", ConfigManager.getProperties().getProperty("SeeTestPassword"));315 objCapabilities.setCapability("chromedriverExecutable", System.getProperty("user.dir").replace("\\", "/") + "//Tool//chromedrivers//windows//chromedriver.exe");316 if (locationServiceEnabled != null) {317 objCapabilities.setCapability("locationServicesEnabled", locationServiceEnabled);318 objCapabilities.setCapability("locationServicesAuthorized", true);319 objCapabilities.setCapability("useLocationServices", true);320 objCapabilities.setCapability("bundleId", "com.apple.mobilesafari.app");321 }322// objCapabilities.setCapability("orientation", ConfigManager.getProperties().getProperty("Orientation"));323 try {324 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {325 rdriver = null;326 rdriver = new AndroidDriver(new URL(serverURL), objCapabilities);327 Thread.sleep(10000);328 break;329 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim().contains("true")) {330 rdriver = null;331 rdriver = new AndroidDriver(new URL(serverURL), objCapabilities);332 Thread.sleep(10000);333 break;334 } else {335 rdriver = null;336 this.driver = new AndroidDriver(new URL(serverURL), objCapabilities);337 this.rdriver = driver;338 //Thread.sleep(10000);339 }340 try {341 //Thread.sleep(2500);342 Thread.sleep(100);343 } catch (InterruptedException e) {344 e.printStackTrace();345 }346 suppressCredential();347 break;348 } catch (MalformedURLException e) {349 e.printStackTrace();350 break;351 }352 case "windows-iphone":353 objCapabilities = new DesiredCapabilities();354 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");355 objCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "safari");356 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, ConfigManager.getProperties().getProperty("platformVersion").toUpperCase().trim());357 objCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, ConfigManager.getProperties().getProperty("iPhoneDeviceName").trim());358// objCapabilities.setCapability("locale", "US");359// objCapabilities.setCapability("deviceReadyTimeout", "450");360 objCapabilities.setCapability("newCommandTimeout", "600000");361// objCapabilities.setCapability("safariIgnoreFraudWarning", true);362// objCapabilities.setCapability("safariAllowPopups", true);363// objCapabilities.setCapability("fullReset", false);364// objCapabilities.setCapability("autoLaunch", true);365// objCapabilities.setCapability("autoAcceptAlerts", true);366 objCapabilities.setCapability(MobileCapabilityType.UDID, UDID);367 objCapabilities.setCapability("user", ConfigManager.getProperties().getProperty("SeeTestUserName"));368 objCapabilities.setCapability("password", ConfigManager.getProperties().getProperty("SeeTestPassword"));369 370 if (locationServiceEnabled != null) {371 objCapabilities.setCapability("locationServicesEnabled", locationServiceEnabled);372 objCapabilities.setCapability("locationServicesAuthorized", true);373 objCapabilities.setCapability("useLocationServices", true);374 objCapabilities.setCapability("bundleId", "com.apple.mobilesafari.app");375 }376// objCapabilities.setCapability("orientation", ConfigManager.getProperties().getProperty("Orientation"));377 try {378 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {379 rdriver = null;380 rdriver = new IOSDriver(new URL(serverURL), objCapabilities);381 Thread.sleep(20000);382 break;383 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim().contains("true")) {384 rdriver = null;385 rdriver = new IOSDriver(new URL(serverURL), objCapabilities);386 Thread.sleep(20000);387 break;388 } else {389 rdriver = null;390 this.driver = new IOSDriver(new URL(serverURL), objCapabilities);391 this.rdriver = driver;392 Thread.sleep(20000);393 }394 try {395 Thread.sleep(2500);396 } catch (InterruptedException e) {397 e.printStackTrace();398 }399 suppressCredential();400 break;401 } catch (MalformedURLException e) {402 e.printStackTrace();403 break;404 }405 case "mac-iphone-device":406 case "mac-iphone_device":407 objCapabilities = new DesiredCapabilities().iphone();408 objCapabilities.setCapability("deviceName", "iPhone");409 objCapabilities.setCapability("version", ConfigManager.getProperties().getProperty("Version"));410 objCapabilities.setCapability("launchTimeout", "300000");411 objCapabilities.setCapability("newCommandTimeout", "600");412 objCapabilities.setCapability("platformVersion", ConfigManager.getProperties().getProperty("macPlatformVersion"));413 objCapabilities.setCapability("udid", ConfigManager.getProperties().getProperty("iphoneUdId"));414 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));415 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));416 File file = new File(ConfigManager.getProperties().getProperty("safariLauncherPath"));417 objCapabilities.setCapability("app", file.getAbsolutePath());418 try {419 // this.setBrowserProxy();420 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()421 .contains("true")) {422 rdriver = null;423 rdriver = new RemoteWebDriver(new URL(424 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),425 objCapabilities);426 Thread.sleep(20000);427// for (String winHandle : this.driver.getWindowHandles()) {428// this.driver.switchTo().window(winHandle);429// }430 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);431 eventListener = null;432 eventListener = new WebDriverListener(EventFiringWebDriver);433 EventFiringWebDriver.register(eventListener);434 break;435 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()436 .contains("true")) {437 rdriver = null;438 rdriver = new RemoteWebDriver(new URL(439 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),440 objCapabilities);441 Thread.sleep(20000);442// for (String winHandle : this.driver.getWindowHandles()) {443// this.driver.switchTo().window(winHandle);444// }445 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);446 eventListener = null;447 eventListener = new WebDriverListener(EventFiringWebDriver);448 EventFiringWebDriver.register(eventListener);449 break;450 } else {451 rdriver = null;452 this.driver = new IOSDriver(453 new URL("http://" + ConfigManager.getProperties().getProperty("appiumServerIP") + ":"454 + ConfigManager.getProperties().getProperty("appiumPort") + "/wd/hub"),455 objCapabilities);456 this.rdriver = driver;457 Thread.sleep(20000);458// for (String winHandle : this.driver.getWindowHandles()) {459// this.driver.switchTo().window(winHandle);460// }461 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);462 eventListener = null;463 eventListener = new WebDriverListener(EventFiringWebDriver);464 EventFiringWebDriver.register(eventListener);465 }466 try {467 Thread.sleep(2500);468 } catch (InterruptedException e) {469 e.printStackTrace();470 }471 suppressCredential();472 break;473 } catch (MalformedURLException e) {474 e.printStackTrace();475 break;476 }477 case "mac-iphone-simulator":478 case "mac-iphone_simulator":479 objCapabilities = new DesiredCapabilities();480 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");481 objCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Safari");482 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,483 ConfigManager.getProperties().getProperty("Version").toUpperCase().trim());484 objCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME,485 ConfigManager.getProperties().getProperty("iPhoneDeviceName").trim());486 objCapabilities.setCapability("locale", "US");487 objCapabilities.setCapability("deviceReadyTimeout", "450");488 objCapabilities.setCapability("newCommandTimeout", "600000");489 objCapabilities.setCapability("safariIgnoreFraudWarning", true);490 objCapabilities.setCapability("safariAllowPopups", true);491 objCapabilities.setCapability("fullReset", false);492 objCapabilities.setCapability("autoLaunch", true);493 objCapabilities.setCapability("autoAcceptAlerts", true);494 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));495 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));496 if (locationServiceEnabled != null) {497 objCapabilities.setCapability("locationServicesEnabled", locationServiceEnabled);498 objCapabilities.setCapability("useLocationServices", true);499 objCapabilities.setCapability("bundleId", "com.apple.mobilesafari.app");500 objCapabilities.setCapability("locationServicesAuthorized", true);501 }502 objCapabilities.setCapability("orientation", ConfigManager.getProperties().getProperty("Orientation"));503 try {504 // this.setBrowserProxy();505 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {506 rdriver = null;507 rdriver = new RemoteWebDriver(new URL(508 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),509 objCapabilities);510 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);511 eventListener = null;512 eventListener = new WebDriverListener(EventFiringWebDriver);513 EventFiringWebDriver.register(eventListener);514 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim().contains("true")) {515 rdriver = null;516 rdriver = new RemoteWebDriver(new URL(517 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),518 objCapabilities);519 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);520 eventListener = null;521 eventListener = new WebDriverListener(EventFiringWebDriver);522 EventFiringWebDriver.register(eventListener);523 break;524 } else {525 rdriver = null;526 this.driver = new IOSDriver(527 new URL("http://" + ConfigManager.getProperties().getProperty("appiumServerIP") + ":"528 + ConfigManager.getProperties().getProperty("appiumPort") + "/wd/hub"),529 objCapabilities);530 this.rdriver = driver;531 Thread.sleep(20000);532// for (String winHandle : this.driver.getWindowHandles()) {533// this.driver.switchTo().window(winHandle);534// }535 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);536 eventListener = null;537 eventListener = new WebDriverListener(EventFiringWebDriver);538 EventFiringWebDriver.register(eventListener);539 }540 try {541 Thread.sleep(2500);542 } catch (InterruptedException e) {543 e.printStackTrace();544 }545 suppressCredential();546 break;547 } catch (MalformedURLException e) {548 e.printStackTrace();549 break;550 }551 case "mac-ipad_safari":552 case "mac-ipad-simulator":553 case "mac-ipad_simulator":554 // Appium iPad Driver555 objCapabilities = new DesiredCapabilities();556 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "iOS");557 objCapabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Safari");558 objCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,559 ConfigManager.getProperties().getProperty("Version").toUpperCase().trim());560 objCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME,561 ConfigManager.getProperties().getProperty("iPadDeviceName").trim());562 objCapabilities.setCapability("locale", "US");563 objCapabilities.setCapability("deviceReadyTimeout", "450"); // Timeout564 objCapabilities.setCapability("newCommandTimeout", "600000");565 objCapabilities.setCapability("safariIgnoreFraudWarning", true);566 objCapabilities.setCapability("safariAllowPopups", true);567 objCapabilities.setCapability("sendKeyStrategy", "grouped");568 objCapabilities.setCapability("fullReset", false); // for ios569 objCapabilities.setCapability("autoLaunch", true);570 objCapabilities.setCapability("autoAcceptAlerts", true);571 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));572 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));573 if (locationServiceEnabled != null) {574 objCapabilities.setCapability("locationServicesEnabled", locationServiceEnabled);575 objCapabilities.setCapability("useLocationServices", true);576 objCapabilities.setCapability("bundleId", "com.apple.mobilesafari.app");577 objCapabilities.setCapability("locationServicesAuthorized", true);578 }579 objCapabilities.setCapability("orientation", ConfigManager.getProperties().getProperty("Orientation"));580 try {581 // this.setBrowserProxy();582 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim()583 .contains("true")) {584 rdriver = null;585 rdriver = new RemoteWebDriver(new URL(586 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),587 objCapabilities);588 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);589 eventListener = null;590 eventListener = new WebDriverListener(EventFiringWebDriver);591 EventFiringWebDriver.register(eventListener);592 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()593 .contains("true")) {594 rdriver = null;595 rdriver = new RemoteWebDriver(new URL(596 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),597 objCapabilities);598 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);599 eventListener = null;600 eventListener = new WebDriverListener(EventFiringWebDriver);601 EventFiringWebDriver.register(eventListener);602 break;603 } else {604 rdriver = null;605 this.driver = new IOSDriver(606 new URL("http://" + ConfigManager.getProperties().getProperty("appiumServerIP") + ":"607 + ConfigManager.getProperties().getProperty("appiumPort") + "/wd/hub"),608 objCapabilities);609 this.rdriver = driver;610 Thread.sleep(20000);611// for (String winHandle : this.driver.getWindowHandles()) {612// this.driver.switchTo().window(winHandle);613// }614 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);615 eventListener = null;616 eventListener = new WebDriverListener(EventFiringWebDriver);617 EventFiringWebDriver.register(eventListener);618 }619 try {620 Thread.sleep(2500);621 } catch (InterruptedException e) {622 e.printStackTrace();623 }624 suppressCredential();625 break;626 } catch (MalformedURLException e) {627 e.printStackTrace();628 break;629 }630 631 case "windows-android-chrome":632 case "mac-android-chrome":633 case "mac-android_chrome":634 objCapabilities = null;635 objCapabilities = DesiredCapabilities.chrome();636 chromeoptions = new ChromeOptions();637 chromeoptions.setExperimentalOption("androidPackage", "com.android.chrome");638 objCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeoptions);639 objCapabilities.setCapability("platform", "WINDOWS");640 objCapabilities.setCapability("browserName", "chrome");641 objCapabilities.setCapability("app", "chrome");642 objCapabilities.setCapability("enableHighAccuracy", true);643 objCapabilities.setCapability("launchTimeout", "300000");644 objCapabilities.setCapability("newCommandTimeout", "300");645 objCapabilities.setCapability("version", "android");646 objCapabilities.setCapability("deviceName", ConfigManager.getProperties().getProperty("androidDeviceName"));647 //objCapabilities.setCapability("UDID", ConfigManager.getProperties().getProperty("androidDeviceId"));648 objCapabilities.setCapability("username", ConfigManager.getProperties().getProperty("sauceLabUser"));649 objCapabilities.setCapability("accessKey", ConfigManager.getProperties().getProperty("sauceLabKey"));650 if (osname.toLowerCase().contains("windows") || osname.toLowerCase().contains("android")) {651 DriverPath = System.getProperty("user.dir").replace("\\", "/")652 + "/Tool/chromedrivers/windows/chromedriver.exe";653 }654 System.setProperty("webdriver.chrome.driver", DriverPath);655 // this.setBrowserProxy();656 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {657 rdriver = null;658 rdriver = new RemoteWebDriver(new URL(659 "http://" + ConfigManager.getProperties().getProperty("gridHubIP") + ":4444/wd/hub"),660 objCapabilities);661 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);662 eventListener = null;663 eventListener = new WebDriverListener(EventFiringWebDriver);664 EventFiringWebDriver.register(eventListener);665 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()666 .contains("true")) {667 rdriver = null;668 rdriver = new RemoteWebDriver(new URL(669 "http://" + ConfigManager.getProperties().getProperty("sauceLabURL") + ":80/wd/hub"),670 objCapabilities);671 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);672 eventListener = null;673 eventListener = new WebDriverListener(EventFiringWebDriver);674 EventFiringWebDriver.register(eventListener);675 } else {676 this.wd = null;677 this.wd = new ChromeDriver(objCapabilities);678 this.EventFiringWebDriver = new EventFiringWebDriver(rdriver);679 eventListener = null;680 eventListener = new WebDriverListener(EventFiringWebDriver);681 EventFiringWebDriver.register(eventListener);682 }683 suppressCredential();684 break;685 686 default:687 return null;688 }689 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")) {690 CommonVariables.gridHubIP.set(GetIPOfSeleniumGridNode(this.driver));691 } else {692 CommonVariables.gridHubIP.set(CommonVariables.MachineHostName.get());693 }694 System.out.println("Successfully Launched the driver: " + browserType + " on the node IP: " + CommonVariables.gridHubIP.get());695 696 if (browserType.toLowerCase().contains("iphone") || browserType.toLowerCase().contains("ipad") || browserType.toLowerCase().contains("android")) {697 698 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim().contains("false")) {699// hwndFirstWindow = driver.getWindowHandle();700// arrKnownBrowserHwnd = driver.getWindowHandles();701 }702 /**703 * If the location service is enabled set the geo location codes704 * under test705 */706 if (this.locationServiceEnabled && (ConfigManager.getProperties().getProperty("deviceType").toLowerCase()707 .contains("tablet")708 || ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("iPad")709 || ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("android")710 || ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("iPhone"))) {711 setGeoLocation();712 }713 driverStartfailureCount = 1;714 CommonVariables.setDriver(this.driver);715 return driver;716 } catch (org.openqa.selenium.remote.SessionNotFoundException717 | org.openqa.selenium.remote.UnreachableBrowserException ex) {718 System.out.println(ex.getLocalizedMessage());719 System.out.println(720 "Caught SessionNotFoundException/UnreachableBrowserException/SessionNotCreatedException in Start Driver Method. Try to start one time more.");721 if (driverStartfailureCount == 1) {722 driverStartfailureCount = 2;723 try {724 Thread.sleep(50000);725 } catch (InterruptedException intr) {726 }727 this.EventFiringWebDriver = (EventFiringWebDriver) instantiateDriver(browserType, CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());728 return driver;729 } else {730 System.out.println(731 "Again Caught UnreachableBrowserException in Start Driver Method. Stopping the execution");732 Assert.fail("Browser Unreachable twice. Exception message: " + ex.getMessage());733 return driver;734 }735 } catch (Exception e) {736 e.printStackTrace();737 Assert.fail(e.getMessage());738 return driver;739 }740 }741 /**742 * @author Cigniti743 * @description : shut down driver :- This method will close all instances744 * of all drivers.745 */746 public void tearDown() {747 try {748 if (driver != null && CommonVariables.DeviceName.get().toLowerCase().contains("chrome")749 && CommonVariables.PlatformName.get().toLowerCase().contains("windows")) {750 LogEntries logEntries = null;751 try {752 logEntries = driver.manage().logs().get(LogType.BROWSER);753 } catch (Exception e) {754 }755 if (logEntries != null) {756 for (LogEntry entry : logEntries) {757 if ("SEVERE".equals(entry.getLevel().toString())) {758 writeCapturedJSErrors(759 new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());760 }761 }762 }763 }764 } catch (Exception e) {765 }766 try {767 try {768 if (rdriver != null) {769 rdriver.quit();770 try {771 Thread.sleep(5000);772 } catch (InterruptedException e1) {773 } catch (IllegalStateException e2) {774 }775 }776 } catch (Exception ex) {777 }778 try {779 if (wd != null) {780 System.out.println("Quitting the driver");781 wd.quit();782 try {783 Thread.sleep(8000);784 } catch (InterruptedException e1) {785 } catch (IllegalStateException e2) {786 }787 }788 } catch (Exception ex) {789 }790 try {791 if (driver != null) {792 driver.quit();793 try {794 Thread.sleep(8000);795 } catch (InterruptedException e1) {796 } catch (IllegalStateException e2) {797 }798 }799 } catch (Exception ex) {800 }801 try {802 CommonVariables.CommonDriver.get().quit();803 CommonVariables.CommonDriver.set(null);804 } catch (Exception e) {805 CommonVariables.CommonDriver.set(null);806 }807 if (ConfigManager.getProperties().getProperty("deviceType").trim().toLowerCase().contains("android")808 || CommonVariables.DeviceName.get().toLowerCase().contains("safari")809 || CommonVariables.DeviceName.get().toLowerCase().contains("iphone")) {810 if (driver != null || wd != null || rdriver != null) {811 try {812 Thread.sleep(20000);813 } catch (InterruptedException e1) {814 }815 ;816 rdriver = null;817 driver = null;818 wd = null;819 }820 }821 } catch (WebDriverException e) {822 CommonVariables.CommonDriver.set(null);823 try {824 Thread.sleep(2500);825 } catch (InterruptedException e1) {826 } catch (IllegalStateException e2) {827 }828 } catch (Exception e) {829 e.printStackTrace();830 }831 CommonVariables.CommonDriver.set(null);832 }833 /**834 * @author Cigniti835 * @description : In this method, it will set the proxy for BMP server836 */837 @SuppressWarnings("rawtypes")838 private void setBrowserProxy() {839 if (ConfigManager.getProperties().getProperty("IsBrowserMobProxyRequire").trim().equalsIgnoreCase("yes")) {840 System.out.println("BMP Proxy will be used for this browser session");841 Proxy proxy = null;842 try {843 // proxy = new Proxy();844 proxy = BMP_Proxy_Controller.Server.seleniumProxy();845 proxy.setAutodetect(false);846 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("true")847 || ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()848 .contains("true")) {849 String localIP = "";850 Enumeration e = NetworkInterface.getNetworkInterfaces();851 while (e.hasMoreElements()) {852 NetworkInterface n = (NetworkInterface) e.nextElement();853 Enumeration ee = n.getInetAddresses();854 while (ee.hasMoreElements()) {855 InetAddress i = (InetAddress) ee.nextElement();856 if (i.getHostAddress().toString()857 .startsWith(ConfigManager.getProperties().getProperty("proxyIPSeries"))) {858 System.out.println(i.getHostAddress());859 localIP = i.getHostAddress().toString();860 break;861 }862 }863 }864 if (localIP.equals("")) {865 InetAddress addr = InetAddress.getLocalHost();866 String ipAddress = addr.getHostAddress();867 localIP = ipAddress;868 }869 proxy.setHttpProxy(localIP + ":" + CommonVariables.portNumForBMP);870 proxy.setSslProxy(localIP + ":" + CommonVariables.portNumForBMP);871 } else if ((ConfigManager.getProperties().getProperty("isAWSExecution").trim()872 .equalsIgnoreCase("true"))) {873 String AWSBMPmachineIP = ConfigManager.getProperties().getProperty("AWSMachineIP");874 String httpProxy = AWSBMPmachineIP + ":" + CommonVariables.portNumForBMP;875 proxy = new Proxy();876 proxy.setProxyType(Proxy.ProxyType.MANUAL);877 proxy.setHttpProxy(httpProxy);878 proxy.setSslProxy(httpProxy);879 objCapabilities.setCapability(CapabilityType.PROXY, proxy);880 objCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);881 System.out.println("BMP proxy for the browser set to: " + httpProxy);882 } else {883 proxy.setHttpProxy("localhost:" + CommonVariables.portNumForBMP);884 proxy.setSslProxy("localhost:" + CommonVariables.portNumForBMP);885 }886 if (CommonVariables.DeviceName.get().toLowerCase().contains("iphone")) {887 objCapabilities.setCapability(MobileCapabilityType.PROXY, proxy);888 objCapabilities.setCapability(MobileCapabilityType.ACCEPT_SSL_CERTS, true);889 } else {890 objCapabilities.setCapability(CapabilityType.PROXY, proxy);891 objCapabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);892 }893 System.out.println("setting browser proxy on port:" + CommonVariables.portNumForBMP);894 Thread.sleep(3000);895 } catch (Exception e) {896 System.out.println("Exception while setting the proxy for browser");897 e.printStackTrace();898 }899 }900 }901 /**902 * @author Cigniti903 * @description : In this method, it will return the driver information904 * like, if android or iOS return mobile else windows on this905 * basis of browser selected by the user.906 * @return907 */908 public static Map<String, String> GetDriverInfo() {909 Map<String, String> DriverInfo = new HashMap<String, String>();910 WebDriver driver = null;911 if (wd != null) {912 driver = wd;913 } else if (rdriver != null) {914 driver = rdriver;915 } else {916 driver = MobileLibrary.EventFiringWebDriver;917 }918 try {919 String DriverType = "";920 String DriverName = "";921 String osName = "";922 if (driver == null || driver.getClass().toString().toLowerCase().contains("androiddriver")923 || driver.getClass().toString().toLowerCase().contains("iosdriver")924 || driver.getClass().toString().toLowerCase().contains("remotewebdriver")) {925 try {926 osName = CommonVariables.PlatformName.get();927 DriverName = CommonVariables.DeviceName.get();928 } catch (NullPointerException e) {929 }930 switch (osName.toUpperCase()) {931 case "WINDOWS": {932 if (DriverName.equals("android-chrome")) {933 DriverType = "mobile";934 } else {935 DriverType = "desktop";936 }937 }938 break;939 case "MAC": {940 if (DriverName.toLowerCase().contains("ipad")) {941 DriverType = "tablet";942 } else if (DriverName.toLowerCase().contains("iphone")) {943 DriverType = "mobile";944 } else {945 DriverType = "desktop";946 }947 }948 break;949 case "ANDROID": {950 DriverType = "mobile";951 }952 break;953 default: {954 }955 }956 } else if (driver.getClass().toString().toLowerCase().contains("chrome")) {957 if (driver.toString().contains("chrome on ANDROID")) {958 DriverType = "mobile";959 DriverName = CommonVariables.DeviceName.get();960 } else {961 DriverType = "Desktop";962 DriverName = "Chrome";963 }964 } else if (driver.getClass().toString().toLowerCase().contains("safari")) {965 DriverType = "Desktop";966 DriverName = "Safari";967 } else if (driver.getClass().toString().toLowerCase().contains("firefox")) {968 DriverType = "Desktop";969 DriverName = "Firefox";970 } else if (driver.getClass().toString().toLowerCase().contains("ie")971 || driver.getClass().toString().toLowerCase().contains("internet_explorer")) {972 DriverType = "Desktop";973 DriverName = "internet_explorer";974 } else if (driver.getClass().toString().toLowerCase().contains("Edge")975 || driver.getClass().toString().toLowerCase().contains("Microsoft")) {976 DriverType = "Desktop";977 DriverName = "Edge";978 } else if (driver.getClass().toString().toLowerCase().contains("Opera")) {979 DriverType = "Desktop";980 DriverName = "Opera";981 } else if (driver.getClass().toString().toLowerCase().contains("PhantomJS")) {982 DriverType = "Desktop";983 DriverName = "PhantomJS";984 }985 DriverInfo.put("DriverType", DriverType);986 // DriverInfo.put("DriverType", "tablet");987 DriverInfo.put("DriverName", DriverName);988 return DriverInfo;989 } catch (Exception e) {990 return DriverInfo;991 }992 }993 /**994 * @author Cigniti995 * @description : write JS Errors996 * @param errors997 */998 private void writeCapturedJSErrors(String errors) {999 try {1000 // archiveFile();1001 String filePath = System.getProperty("user.dir").replace("\\", "/") + "/logs/CapturedJSErrors/jsErrors.txt";1002 fw = new FileWriter(filePath, true);1003 pw = new PrintWriter(fw);1004 pw.write(errors);1005 pw.write("\n");1006 pw.close();1007 fw.close();1008 } catch (IOException e) {1009 e.printStackTrace();1010 }1011 }1012 /**1013 * @author Cigniti1014 * @description : Archive File1015 * @throws IOException1016 */1017 private void archiveFile(String srcFilePath, String destFilePath) throws IOException {1018 try {1019 File source = new File(srcFilePath);1020 File destination = new File(destFilePath);1021 FileUtils.copyFile(source, destination);1022 } catch (FileNotFoundException e) {1023 e.getLocalizedMessage();1024 }1025 }1026 /**1027 * @author Cigniti1028 * @description : Method to Find Element1029 * @param by1030 * @param timeoutInSeconds1031 * @return1032 * @throws Throwable1033 */1034 public WebElement FindElement(By by, Optional<Long> timeoutInSeconds) {1035 long timeout = timeoutInSeconds.isPresent() ? timeoutInSeconds.get() : -1;1036 if (timeout == -1) {1037 timeout = Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut"));1038 }1039 WebElement webElement = null;1040 try {1041 AcceptAlert();1042 webElement = (new WebDriverWait(driver, timeout)).until(ExpectedConditions.presenceOfElementLocated(by));1043 try {1044 if (webElement != null || CommonVariables.TestCaseLog.get() != null) {1045 extentLogs.pass("Find Element",1046 "Successfully find an element on '" + driver.getTitle() + "' page.");1047 CommonVariables.TestCaseLog.get()1048 .info("Successfully find '" + by + "' element on '" + driver.getTitle() + "' page");1049 } else {1050 extentLogs.fail("Find Element", "Element not found on '" + driver.getTitle() + "' page.");1051 CommonVariables.TestClassLog.get()1052 .info("Successfully find '" + by + "' element on '" + driver.getTitle() + "' page");1053 }1054 } catch (NullPointerException e) {1055 extentLogs.error("Find Element", "Element not found on '" + driver.getTitle()1056 + "' page due to exception - " + e.getLocalizedMessage());1057 throw new NullPointerException();1058 }1059 try {1060 ScrollToElementVisible(by);1061 } catch (org.openqa.selenium.ElementNotVisibleException e) {1062 if (CommonVariables.TestCaseLog.get() != null) {1063 CommonVariables.TestCaseLog.get()1064 .info("Element (" + by + ") is not visible on '" + driver.getTitle() + "' page");1065 } else {1066 CommonVariables.TestClassLog.get()1067 .info("Element (" + by + ") is not visible on '" + driver.getTitle() + "' page");1068 }1069 extentLogs.error("Find Element", "Element not visible on '" + driver.getTitle()1070 + "' page due to exception - " + e.getLocalizedMessage());1071 throw new ElementNotVisibleException("Element not visible.");1072 } catch (org.openqa.selenium.WebDriverException e) {1073 if (CommonVariables.TestCaseLog.get() != null) {1074 CommonVariables.TestCaseLog.get()1075 .info("Failed to move Element (" + by + ") on the running driver type.");1076 } else {1077 CommonVariables.TestClassLog.get()1078 .info("Failed to move Element (" + by + ") on the running driver type.");1079 }1080 extentLogs.error("Find Element",1081 "Failed to move to an Element due to exception - " + e.getLocalizedMessage());1082 throw new WebDriverException();1083 } catch (NullPointerException ex) {1084 System.out.println("Getting exception when movetoElement under FindElement method in" + getClass()1085 + " class. Driver info under CommonVariable :" + CommonVariables.getDriver());1086 throw new NullPointerException();1087 }1088 return webElement;1089 } catch (Exception ex) {1090 if (ex.getCause().toString().contains("SessionNotFoundException")) {1091 throw new SessionNotFoundException();1092 } else if (ex.getCause().toString().contains("UnhandledAlertException")) {1093 if (AcceptAlert()) {1094 return driver.findElement(by);1095 }1096 if (CommonVariables.TestCaseLog.get() != null) {1097 CommonVariables.TestCaseLog.get().info("caught 'UnhandledAlertException' exception while finding '"1098 + by + "' element on '" + driver.getTitle() + "' page");1099 } else {1100 CommonVariables.TestClassLog.get().info("caught 'UnhandledAlertException' exception while finding '"1101 + by + "' element on '" + driver.getTitle() + "' page");1102 }1103 extentLogs.error("Find Element",1104 "caught 'UnhandledAlertException' exception while finding an element on '" + driver.getTitle()1105 + "' page");1106 throw new UnhandledAlertException("");1107 } else if (ex.getCause().toString().contains("NoSuchElementException")) {1108 if (AcceptAlert()) {1109 return driver.findElement(by);1110 }1111 if (CommonVariables.TestCaseLog.get() != null) {1112 CommonVariables.TestCaseLog.get().info("No such element(" + by + ") found on '" + driver.getTitle()1113 + "' page at " + driver.getCurrentUrl() + "' url.");1114 } else {1115 CommonVariables.TestClassLog.get().info("No such element(" + by + ") found on '" + driver.getTitle()1116 + "' page at " + driver.getCurrentUrl() + "' url.");1117 }1118 extentLogs.error("Find Element", "No such element éxception found on '" + driver.getTitle()1119 + "' page at " + driver.getCurrentUrl() + "' url.");1120 throw new NoSuchElementException("No such Element");1121 } else if (ex.getCause().toString().contains("TimeoutException")) {1122 if (AcceptAlert()) {1123 return driver.findElement(by);1124 } else {1125 if (CommonVariables.TestCaseLog.get() != null) {1126 CommonVariables.TestCaseLog.get()1127 .info("No such element(" + by + ") found on '" + driver.getTitle() + "' page at "1128 + driver.getCurrentUrl() + "' url within timelimit (" + timeout + ").");1129 } else {1130 CommonVariables.TestClassLog.get()1131 .info("No such element(" + by + ") found on '" + driver.getTitle() + "' page at "1132 + driver.getCurrentUrl() + "' url within timelimit (" + timeout + ").");1133 }1134 extentLogs.error("Find Element", "No such element exception found on '" + driver.getTitle()1135 + "' page at " + driver.getCurrentUrl() + "' url within timelimit (" + timeout + ").");1136 }1137 throw new TimeoutException();1138 } else if (ex.getCause().toString().contains("StaleElementReferenceException")) {1139 if (CommonVariables.TestCaseLog.get() != null) {1140 CommonVariables.TestCaseLog.get()1141 .info("Info. Caught 'StaleElementReferenceException' exception while finding (" + by1142 + ") element. Class: " + ex.getClass());1143 } else {1144 CommonVariables.TestClassLog.get()1145 .info("Info. Caught 'StaleElementReferenceException' exception while finding (" + by1146 + ") element. Class: " + ex.getClass());1147 }1148 extentLogs.error("Find Element",1149 "Caught 'StaleElementReferenceException' exception while finding an element. Class: "1150 + ex.getClass());1151 }1152 AcceptAlert();1153 try {1154 webElement = driver.findElement(by);1155 ScrollToElementVisible(by);1156 return webElement;1157 } catch (Exception e) {1158 if (CommonVariables.TestCaseLog.get() != null) {1159 CommonVariables.TestCaseLog.get()1160 .info("Error. Caught 'StaleElementReferenceException' exception while finding (" + by1161 + ") element. Exception Type: " + e.getClass());1162 } else {1163 CommonVariables.TestClassLog.get()1164 .info("Error. Caught 'StaleElementReferenceException' exception while finding (" + by1165 + ") element. Exception Type: " + e.getClass());1166 }1167 throw new StaleElementReferenceException("Stale Exception while finding an element.");1168 }1169 }1170 }1171 /**1172 * @author Cigniti1173 * @description: click on webElement1174 * @param webElement1175 * @return1176 */1177 public boolean Click(WebElement webElement) {1178 return Click(webElement, 4);1179 }1180 /**1181 * @author Cigniti1182 * @description: click on webElement1183 * @param webElement1184 * @return1185 */1186 public boolean Click(WebElement webElement, String str) {1187 return Click(webElement, 4, str);1188 }1189 /**1190 * @author Cigniti1191 * @description: click on webElement1192 * @param webElement1193 * @return1194 */1195 public boolean Click(By locators, String str) {1196 WebElement webElement=driver.findElement(locators);1197 //return Click(webElement, 4, str);1198 return Click(webElement, 1, str);1199 }1200 1201 public boolean Click1(By locators, String str) throws InterruptedException {1202 WebElement webElement=driver.findElement(locators);1203 //return Click(webElement, 4, str);1204 return Click2(webElement, 1, str);1205 }1206 1207 /**1208 * @author Cigniti1209 * @description: click on webElement1210 * @param webElement1211 * @return1212 */1213 public boolean AppClick(By locator, String str) {1214 WebElement webElement=driver.findElement(locator);1215 return Click(webElement, 4, str);1216 }1217 /**1218 * @author Cigniti1219 * @description : Webdriver and Java Script Click. Wait time in seconds i.e.1220 * 8 for 8 seconds1221 * @param webElement1222 * and wait time in seconds1223 * @return1224 */1225 public boolean Click(WebElement webElement, Integer waitTime) {1226 boolean state = false;1227 try {1228 Thread.sleep(500);1229 webElement.click();1230 try {1231 Thread.sleep(waitTime * 1000);1232 extentLogs.pass("Click", "Successfully clicked.");1233 if (CommonVariables.TestCaseLog.get() != null) {1234 CustomLogs.addToLog("CurrentTestCaseLog", "info", "Passed. Successfully clicked.");1235 } else {1236 CustomLogs.addToLog("CurrentTestClassLog", "info", "Passed. Successfully clicked.");1237 }1238 state = true;1239 } catch (InterruptedException e) {1240 e.printStackTrace();1241 }1242 } catch (ElementNotVisibleException e1) {1243 extentLogs.error("Click", "Element is not visible.");1244 if (CommonVariables.TestCaseLog.get() != null) {1245 CommonVariables.TestCaseLog.get().debug("Error: Element (" + webElement + ") is not visible.");1246 } else {1247 CommonVariables.TestClassLog.get().debug("Error: Element (" + webElement + ") is not visible.");1248 }1249 } catch (StaleElementReferenceException e2) {1250 extentLogs.error("Click", "Caught 'StaleElementReferenceException' exception while clicking on element.");1251 if (CommonVariables.TestCaseLog.get() != null) {1252 CommonVariables.TestCaseLog.get()1253 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"1254 + webElement + "' element.");1255 } else {1256 CommonVariables.TestClassLog.get()1257 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"1258 + webElement + "' element.");1259 }1260 AcceptAlert();1261 // driver.navigate().refresh();1262 try {1263 if (webElement.isEnabled()) {1264 webElement.click();1265 }1266 } catch (Exception e) {1267 }1268 } catch (org.openqa.selenium.UnhandledAlertException e3) {1269 extentLogs.error("Click", "Error. Caught 'UnhandledAlertException' exception while clicking on element.");1270 AcceptAlert();1271 try {1272 if (webElement.isDisplayed()) {1273 webElement.click();1274 }1275 } catch (Exception e) {1276 if (CommonVariables.TestCaseLog.get() != null) {1277 CommonVariables.TestCaseLog.get()1278 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement1279 + "' element.");1280 } else {1281 CommonVariables.TestClassLog.get()1282 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement1283 + "' element.");1284 }1285 e.printStackTrace();1286 }1287 } catch (NullPointerException e5) {1288 extentLogs.error("Click", "Error. Caught 'NullPointerException' exception while clicking element on '"1289 + driver.getTitle() + "'.");1290 if (CommonVariables.TestCaseLog.get() != null) {1291 CommonVariables.TestCaseLog.get()1292 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"1293 + driver.getTitle() + "'.");1294 } else {1295 CommonVariables.TestClassLog.get()1296 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"1297 + driver.getTitle() + "'.");1298 }1299 } catch (org.openqa.selenium.WebDriverException e6) {1300 if (e6.getMessage().toString().toLowerCase().contains("user supplied")) {1301 try {1302 JavascriptExecutor js = (JavascriptExecutor) (driver);1303 js.executeScript("arguments[0].click();", webElement);1304 Thread.sleep(8000);1305 state = true;1306 } catch (Exception e) {1307 if (!state) {1308 try {1309 JavascriptExecutor js = (JavascriptExecutor) (driver);1310 js.executeScript("$(arguments[0]).focusin();", webElement);1311 Thread.sleep(8000);1312 state = true;1313 } catch (Exception e1) {1314 state = false;1315 }1316 }1317 }1318 }1319 if (e6.getMessage().toString().toLowerCase().contains("Element is not clickable")) {1320 extentLogs.error("Click",1321 "Caught exception about 'Element is not clickable' while clicking element on '"1322 + driver.getTitle()1323 + "'. So Scroll Top/Bottom and wait for sometime to make clickable");1324 if (CommonVariables.TestCaseLog.get() != null) {1325 CommonVariables.TestCaseLog.get()1326 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"1327 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"1328 + webElement + "' clickable");1329 } else {1330 CommonVariables.TestClassLog.get()1331 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"1332 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"1333 + webElement + "' clickable");1334 }1335 }1336 try {1337 try {1338 if (ScrollToElementVisible(webElement)) {1339 try {1340 new WebDriverWait(driver, Long.parseLong("2"))1341 .until(ExpectedConditions.elementToBeClickable(webElement)).click();1342 Thread.sleep(8000);1343 return true;1344 } catch (Exception ex) {1345 try {1346 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1347 js.executeScript("arguments[0].click();", webElement);1348 } catch (Exception e) {1349 return false;1350 }1351 }1352 }1353 } catch (Exception e) {1354 return false;1355 }1356 try {1357 ScrollToTop();1358 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1359 js.executeScript("arguments[0].focusin();", webElement);1360 new WebDriverWait(driver, Long.parseLong("10"))1361 .until(ExpectedConditions.elementToBeClickable(webElement)).click();1362 Thread.sleep(8000);1363 state = true;1364 } catch (Exception e1) {1365 if (e6.getMessage().toString().toLowerCase().contains("element is not clickable")) {1366 try {1367 ScrollToBottom();1368 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1369 js.executeScript("arguments[0].focusin();", webElement);1370 new WebDriverWait(driver, Long.parseLong("10"))1371 .until(ExpectedConditions.elementToBeClickable(webElement)).click();1372 state = true;1373 } catch (Exception e) {1374 return false;1375 }1376 } else {1377 state = false;1378 }1379 }1380 } catch (Exception e) {1381 try {1382 Actions clicker = new Actions(CommonVariables.CommonDriver.get());1383 clicker.moveToElement(webElement).click().perform();1384 } catch (Exception e7) {1385 state = false;1386 extentLogs.error("Click", "Element is not clickable.");1387 if (CommonVariables.TestCaseLog.get() != null) {1388 CommonVariables.TestCaseLog.get().error("Error: element is not clickable.");1389 } else {1390 CommonVariables.TestClassLog.get().error("Error: element is not clickable.");1391 }1392 }1393 }1394 } catch (Exception e4) {1395 state = false;1396 }1397 return state;1398 }1399 1400 1401 public boolean Click(WebElement webElement, Integer waitTime, String str) {1402 boolean state = false;1403 try {1404 Thread.sleep(500);1405 webElement.click();1406 try {1407 Thread.sleep(waitTime * 1000);1408 extentLogs.pass("Click", "Successfully clicked '" + str + "'");1409 if (CommonVariables.TestCaseLog.get() != null) {1410 CustomLogs.addToLog("CurrentTestCaseLog", "info", "Passed. Successfully clicked.");1411 } else {1412 CustomLogs.addToLog("CurrentTestClassLog", "info", "Passed. Successfully clicked.");1413 }1414 state = true;1415 } catch (InterruptedException e) {1416 e.printStackTrace();1417 }1418 } catch (ElementNotVisibleException e1) {1419 extentLogs.error("Click", "Element is not visible.");1420 if (CommonVariables.TestCaseLog.get() != null) {1421 CommonVariables.TestCaseLog.get().debug("Error: Element (" + webElement + ") is not visible.");1422 } else {1423 CommonVariables.TestClassLog.get().debug("Error: Element (" + webElement + ") is not visible.");1424 }1425 } catch (StaleElementReferenceException e2) {1426 extentLogs.error("Click", "Caught 'StaleElementReferenceException' exception while clicking on element.");1427 if (CommonVariables.TestCaseLog.get() != null) {1428 CommonVariables.TestCaseLog.get()1429 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"1430 + webElement + "' element.");1431 } else {1432 CommonVariables.TestClassLog.get()1433 .debug("Error. Caught 'StaleElementReferenceException' exception while clicking on '"1434 + webElement + "' element.");1435 }1436 AcceptAlert();1437 // driver.navigate().refresh();1438 try {1439 if (webElement.isEnabled()) {1440 webElement.click();1441 }1442 } catch (Exception e) {1443 }1444 } catch (org.openqa.selenium.UnhandledAlertException e3) {1445 extentLogs.error("Click", "Error. Caught 'UnhandledAlertException' exception while clicking on element.");1446 AcceptAlert();1447 try {1448 if (webElement.isDisplayed()) {1449 webElement.click();1450 }1451 } catch (Exception e) {1452 if (CommonVariables.TestCaseLog.get() != null) {1453 CommonVariables.TestCaseLog.get()1454 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement1455 + "' element.");1456 } else {1457 CommonVariables.TestClassLog.get()1458 .info("Info. Caught 'UnhandledAlertException' exception while clicking on '" + webElement1459 + "' element.");1460 }1461 e.printStackTrace();1462 }1463 } catch (NullPointerException e5) {1464 extentLogs.error("Click", "Error. Caught 'NullPointerException' exception while clicking element on '"1465 + driver.getTitle() + "'.");1466 if (CommonVariables.TestCaseLog.get() != null) {1467 CommonVariables.TestCaseLog.get()1468 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"1469 + driver.getTitle() + "'.");1470 } else {1471 CommonVariables.TestClassLog.get()1472 .debug("Info. Caught 'NullPointerException' exception while clicking element on '"1473 + driver.getTitle() + "'.");1474 }1475 } catch (org.openqa.selenium.WebDriverException e6) {1476 if (e6.getMessage().toString().toLowerCase().contains("user supplied")) {1477 try {1478 JavascriptExecutor js = (JavascriptExecutor) (driver);1479 js.executeScript("arguments[0].click();", webElement);1480 Thread.sleep(8000);1481 state = true;1482 } catch (Exception e) {1483 if (!state) {1484 try {1485 JavascriptExecutor js = (JavascriptExecutor) (driver);1486 js.executeScript("$(arguments[0]).focusin();", webElement);1487 Thread.sleep(8000);1488 state = true;1489 } catch (Exception e1) {1490 state = false;1491 }1492 }1493 }1494 }1495 if (e6.getMessage().toString().toLowerCase().contains("Element is not clickable")) {1496 extentLogs.error("Click",1497 "Caught exception about 'Element is not clickable' while clicking element on '"1498 + driver.getTitle()1499 + "'. So Scroll Top/Bottom and wait for sometime to make clickable");1500 if (CommonVariables.TestCaseLog.get() != null) {1501 CommonVariables.TestCaseLog.get()1502 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"1503 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"1504 + webElement + "' clickable");1505 } else {1506 CommonVariables.TestClassLog.get()1507 .info("Info: Caught exception about 'Element is not clickable' while clicking element on '"1508 + driver.getTitle() + "'. So Scroll Top/Bottom and wait for sometime to make '"1509 + webElement + "' clickable");1510 }1511 }1512 try {1513 try {1514 if (ScrollToElementVisible(webElement)) {1515 try {1516 new WebDriverWait(driver, Long.parseLong("2"))1517 .until(ExpectedConditions.elementToBeClickable(webElement)).click();1518 Thread.sleep(8000);1519 return true;1520 } catch (Exception ex) {1521 try {1522 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1523 js.executeScript("arguments[0].click();", webElement);1524 } catch (Exception e) {1525 return false;1526 }1527 }1528 }1529 } catch (Exception e) {1530 return false;1531 }1532 try {1533 ScrollToTop();1534 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1535 js.executeScript("arguments[0].focusin();", webElement);1536 new WebDriverWait(driver, Long.parseLong("10"))1537 .until(ExpectedConditions.elementToBeClickable(webElement)).click();1538 Thread.sleep(8000);1539 state = true;1540 } catch (Exception e1) {1541 if (e6.getMessage().toString().toLowerCase().contains("element is not clickable")) {1542 try {1543 ScrollToBottom();1544 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1545 js.executeScript("arguments[0].focusin();", webElement);1546 new WebDriverWait(driver, Long.parseLong("10"))1547 .until(ExpectedConditions.elementToBeClickable(webElement)).click();1548 state = true;1549 } catch (Exception e) {1550 return false;1551 }1552 } else {1553 state = false;1554 }1555 }1556 } catch (Exception e) {1557 try {1558 Actions clicker = new Actions(CommonVariables.CommonDriver.get());1559 clicker.moveToElement(webElement).click().perform();1560 } catch (Exception e7) {1561 state = false;1562 extentLogs.error("Click", "Element is not clickable.");1563 if (CommonVariables.TestCaseLog.get() != null) {1564 CommonVariables.TestCaseLog.get().error("Error: element is not clickable.");1565 } else {1566 CommonVariables.TestClassLog.get().error("Error: element is not clickable.");1567 }1568 }1569 }1570 } catch (Exception e4) {1571 state = false;1572 }1573 return state;1574 }1575 1576 public boolean Click2(WebElement webElement, Integer waitTime, String str) throws InterruptedException {1577 boolean state = false;1578 try {1579 Thread.sleep(500);1580 webElement.click();1581 1582 } catch (ElementNotVisibleException e4) {1583 state = false;1584 }1585 return state;1586 }1587 1588 1589 /**1590 * @author Cigniti1591 * @description : javascript Click1592 * @param webElement1593 * @return1594 */1595 public boolean JSClick(By loc)1596 {1597 WebElement elem=driver.findElement(loc);1598 return javascriptClick(elem);1599 }1600 1601 /**1602 * @author Cigniti1603 * @description : javascript Click1604 * @param webElement1605 * @return1606 */1607 public boolean javascriptClick(WebElement webElement) {1608 boolean state = false;1609 try {1610 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1611 js.executeScript("arguments[0].click();", webElement);1612 Thread.sleep(4000);1613 state = true;1614 return true;1615 } catch (NullPointerException ex) {1616 return false;1617 } catch (Exception e) {1618 try {1619 if (ScrollToElementVisible(By.xpath(getElementXPath(webElement)))) {1620 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1621 js.executeScript("$(arguments[0]).click();", webElement);1622 Thread.sleep(4000);1623 state = true;1624 return true;1625 } else {1626 return false;1627 }1628 } catch (Exception ex) {1629 }1630 if (!state) {1631 try {1632 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1633 js.executeScript("$(arguments[0]).focusin();", webElement);1634 Thread.sleep(8000);1635 state = true;1636 }1637 catch (Exception e1) {1638 state = false;1639 }1640 }1641 }1642 return state;1643 }1644 /**1645 * @author Cigniti1646 * @description : javascript Send Keys1647 * @param webElement1648 * @return1649 */1650 public boolean javascriptSendKeys(WebElement locator, String valueToType) {1651 boolean state = false;1652 try {1653 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());1654 js.executeScript("arguments[0].value=\"" + valueToType + "\";", locator);1655 state = true;1656 extentLogs.pass("Type", "Successfully entered text value - '" + valueToType + "'.");1657 } catch (Exception ex) {1658 extentLogs.error("Type",1659 "Failed to enter text value - '" + valueToType + "' due to execption - " + ex.getMessage() + ".");1660 state = false;1661 }1662 return state;1663 }1664 /**1665 * @author Cigniti1666 * @description: webdriver send keys1667 * @param locator1668 * the locator1669 * @param valueToType1670 * the value to type1671 * @param locatorName1672 * the locator name1673 * @return true, if successful1674 * @throws Throwable1675 * the throwable1676 */1677 public boolean type(WebElement element, String valueToType) throws Throwable {1678 boolean status = false;1679 try {1680 WebDriverWait wait = new WebDriverWait(this.driver, 60);1681 ScrollToElementVisible(element);1682 wait.until(ExpectedConditions.elementToBeClickable(element));1683 element.clear();1684 element.sendKeys(valueToType);1685 status = true;1686 extentLogs.pass("Type", "Successfully entered text value - '" + valueToType + "'.");1687 } catch (Exception e) {1688 status = false;1689 extentLogs.error("Type",1690 "Failed to enter text value - '" + valueToType + "' due to execption - " + e.getMessage() + ".");1691 if (CommonVariables.TestCaseLog.get() != null) {1692 CommonVariables.TestCaseLog.get().error("Error: Failed to enter text value - '" + valueToType1693 + "' due to execption - " + e.getMessage() + ".");1694 } else {1695 CommonVariables.TestClassLog.get().error("Error: Failed to enter text value - '" + valueToType1696 + "' due to execption - " + e.getMessage() + ".");1697 }1698 }1699 return status;1700 }1701 1702 1703 public boolean type(By locators, String valueToType,String objectName) throws Throwable1704 {1705 WebElement element = driver.findElement(locators);1706 return type(element,valueToType,objectName);1707 }1708 1709 public boolean type(WebElement element, String valueToType,String objectName) throws Throwable {1710 boolean status = false;1711 try {1712 //WebDriverWait wait = new WebDriverWait(this.driver, 60);1713// ScrollToElementVisible(element);1714// wait.until(ExpectedConditions.elementToBeClickable(element));1715 1716 element.click();1717 element.clear();1718 element.sendKeys(valueToType);1719 status = true;1720 extentLogs.pass("Type", "Successfully entered text value - '" + valueToType +" at "+objectName+ "'.");1721 } catch (Exception e) {1722 status = false;1723 extentLogs.error("Type",1724 "Failed to enter text value - '" + valueToType + "' at "+objectName+"due to execption - " + e.getMessage() + ".");1725 if (CommonVariables.TestCaseLog.get() != null) {1726 CommonVariables.TestCaseLog.get().error("Error: Failed to enter text value - '" + valueToType1727 +" at "+objectName+ "' due to execption - " + e.getMessage() + ".");1728 } else {1729 CommonVariables.TestClassLog.get().error("Error: Failed to enter text value - '" + valueToType1730 +" at "+objectName+ "' due to execption - " + e.getMessage() + ".");1731 }1732 }1733 return status;1734 }1735 /**1736 * @author Cigniti1737 * @description: browser specific send keys.1738 * @param locator1739 * @param value1740 * @param locatorName1741 * @throws Throwable1742 */1743 public void browserSpecificSendKeys(WebElement locator, String valueToType) throws Throwable {1744 String browserName = CommonVariables.DeviceName.get();1745 try {1746 switch (browserName.toLowerCase()) {1747 case "firefox":1748 case "chrome":1749 case "opera": {1750 type(locator, valueToType);1751 break;1752 }1753 case "ie":1754 case "safari":1755 case "edge":1756 case "pahntomjs": {1757 javascriptSendKeys(locator, valueToType);1758 break;1759 }1760 }1761 } catch (Exception ex) {1762 ex.printStackTrace();1763 }1764 }1765 /**1766 * Select by visible text.1767 * 1768 * @description: select a value from drop down list on the basis of visible1769 * text1770 * @param locator1771 * the locator1772 * @param value1773 * the value1774 * @param locatorName1775 * the locator name1776 * @return true, if successful1777 * @throws Throwable1778 * the throwable1779 */1780 public boolean selectByVisibleText(By locator, String value, String locatorName) throws Throwable {1781 boolean flag = false;1782 try {1783 ScrollToElementVisible(locator);1784 WebElement dropDownListBox = driver.findElement(locator);1785 Select clickThis = new Select(dropDownListBox);1786 clickThis.selectByVisibleText(value);1787 fluentWait(30, 6);1788 flag = true;1789 } catch (Exception e) {1790 extentLogs.error("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName1791 + " due to exception - " + e.getLocalizedMessage());1792 flag = false;1793 } finally {1794 if (flag == false) {1795 extentLogs.fail("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName);1796 } else if (flag == true) {1797 extentLogs.pass("Select", "'" + value + "'" + "is selected from the DropDown " + locatorName);1798 }1799 }1800 return flag;1801 }1802 public boolean asserTitle(String title) throws Throwable {1803 boolean flag = false;1804 try {1805 By windowTitle = By.xpath("//title[contains(text(),'" + title1806 + "')]");1807 if (waitForTitlePresent(windowTitle)) {1808 Assert.assertEquals(GetPageTitle(), title);1809 flag = true;1810 return true;1811 } else {1812 return false;1813 }1814 } catch (Exception ex) {1815 ex.printStackTrace();1816 return false;1817 } finally {1818 if (!flag) {1819 extentLogs.fail("AsserTitle ",1820 "Page title is not matched with " + title);1821 return false;1822 } else if (flag) {1823 extentLogs.pass("AsserTitle ",1824 " Page title is verified with " + title);1825 }1826 }1827 }1828 1829 public boolean isElementPresent(By by, String locatorName)1830 throws Throwable {1831 boolean flag = false;1832 try {1833 driver.findElement(by);1834 flag = true;1835 return true;1836 } catch (Exception e) {1837 Assert.assertTrue(flag,"Element: <b>"+ locatorName+"</b> is <b>NOT</b> present on the page ");1838 e.printStackTrace();1839 return false;1840 } finally {1841 if (!flag) {1842 extentLogs.fail("Is Element Present ", locatorName1843 + "Element: <b>"+ locatorName+"</b> is <b>NOT</b> present on the page ");1844 Assert.assertTrue(flag,"Element: <b>"+ locatorName+"</b> is <b>NOT</b> present on the page ");1845 } else if (flag) {1846 extentLogs.pass("IsElementPresent ",1847 "Able to locate element <b>" + locatorName + "</b>");1848 }1849 }1850 }1851 1852 public boolean waitForVisibilityOfElementWithOutAssertion(By by, String locator)1853 throws Throwable {1854 boolean flag = false;1855 WebDriverWait wait = new WebDriverWait(driver, 20,30);1856 try {1857 wait.until(ExpectedConditions.visibilityOfElementLocated(by));1858 flag = true;1859 return true;1860 } catch (Exception e) {1861 //Assert.assertTrue(flag," Element "1862 // + locator + " is not visible");1863 return false;1864 } finally {1865 if (!flag) {1866 extentLogs.fail("WsaitForVisibilityOfElementWithOutAssertion ", " Element "1867 + locator + " is not visible");1868 } else if ( flag) {1869 extentLogs.pass("WaitForVisibilityOfElementWithOutAssertion ", " Element "1870 + locator + " is visible");1871 }1872 }1873 }1874 1875 public boolean waitForVisibilityOfElement(By by, String locator)1876 throws Throwable {1877 boolean flag = false;1878 WebDriverWait wait = new WebDriverWait(driver, 20,30);1879 try {1880 wait.until(ExpectedConditions.visibilityOfElementLocated(by));1881 flag = true;1882 return true;1883 } catch (Exception e) {1884 Assert.assertTrue(flag," Element "1885 + locator + " is not visible");1886 return false;1887 } finally {1888 if (!flag) {1889 extentLogs.fail("WaitForVisibilityOfElement ", " Element "1890 + locator + " is not visible");1891 } else if ( flag) {1892 extentLogs.pass("WaitForVisibilityOfElement ", " Element "1893 + locator + " is visible");1894 }1895 }1896 }1897 1898 public List<String> fnGetAllList(By locator,String locatorName) throws Throwable{1899 List<String>totalContentList=new ArrayList<String>();1900 List<WebElement>contentElement =null;1901 try{1902 contentElement=driver.findElements(locator);1903 extentLogs.pass("Total List Found ", "Available list is <b>"+contentElement.size()+"</b>");1904 for(int i=0;i<contentElement.size();i++){1905 totalContentList.add(contentElement.get(i).getText());1906 1907 }1908 }catch(Exception e){1909 e.printStackTrace();1910 extentLogs.fail("Total List Not Found ", "List is not available <b>"+contentElement.size()+"</b>");1911 e.printStackTrace();1912 }1913 return totalContentList;1914 }1915 public List<WebElement> fnGetAllWebElementList(By locator,String locatorName) throws Throwable{1916 List<WebElement>totalContentWebElementList=new ArrayList<WebElement>();1917 List<WebElement>contentElement =null;1918 try{1919 contentElement=driver.findElements(locator);1920 extentLogs.pass("Total WebElement List Found ", "Available WebElement list is <b>"+contentElement.size()+"</b>");1921 for(int i=1;i<contentElement.size();i++){1922 System.out.println("contentElement.size() "+contentElement.size());1923 totalContentWebElementList.add(contentElement.get(i));1924 //System.out.println("totalContentWebElementList "+totalContentWebElementList);1925 //return totalContentWebElementList;1926 }1927 1928 }catch(Exception e){1929 e.printStackTrace();1930 extentLogs.fail("Total WebElement List Not Found ", "WebElement List is not available <b>"+contentElement.size()+"</b>");1931 1932 }1933 System.out.println("totalContentWebElementList +++"+totalContentWebElementList);1934 return totalContentWebElementList;1935 }1936 1937 1938 public List<WebElement> fnGetAllElementList(By locator,String locatorName) throws Throwable{1939 List<WebElement>totalContentWebElementList=new ArrayList<WebElement>();1940 List<WebElement>contentElement =null;1941 try{1942 contentElement=driver.findElements(locator);1943 extentLogs.pass("Total WebElement List Found ", "Available WebElement list is <b>"+contentElement.size()+"</b>");1944 for(int i=0;i<contentElement.size();i++){1945 System.out.println("contentElement.size() "+contentElement.size());1946 totalContentWebElementList.add(contentElement.get(i));1947 //System.out.println("totalContentWebElementList "+totalContentWebElementList);1948 //return totalContentWebElementList;1949 }1950 1951 }catch(Exception e){1952 e.printStackTrace();1953 extentLogs.fail("Total WebElement List Not Found ", "WebElement List is not available <b>"+contentElement.size()+"</b>");1954 1955 }1956 System.out.println("totalContentWebElementList +++"+totalContentWebElementList);1957 return totalContentWebElementList;1958 }1959 1960 public boolean mousehoverWithOutAssertion(By locator, String locatorName)1961 throws Throwable {1962 boolean flag = false;1963 try {1964 WebElement mo = driver.findElement(locator);1965 new Actions(driver).moveToElement(mo).build().perform();1966 1967 flag = true;1968 return true;1969 } catch (Exception e) {1970 //Assert.assertTrue(flag,"MouseOver action is not performed on " + locatorName);1971 return false;1972 } finally {1973 if (!flag) {1974 extentLogs.fail("MouseOver",1975 "MouseOver action is not performed on " + locatorName);1976 //Assert.assertTrue(flag,"Unable find the element "+ locatorName);1977 } else if ( flag) {1978 extentLogs.pass("MouseOver ",1979 "MouserOver Action is performed on <b>" + locatorName + "</b>");1980 }1981 }1982 }1983 1984 public boolean mouseHoverByJavaScriptByLocator(By locator, String locatorName)1985 throws Throwable {1986 boolean flag = false;1987 try {1988 WebElement mo = driver.findElement(locator);1989 String javaScript = "var evObj = document.createEvent('MouseEvents');"1990 + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"1991 + "arguments[0].dispatchEvent(evObj);";1992 JavascriptExecutor js = (JavascriptExecutor) driver;1993 js.executeScript(javaScript, mo);1994 flag = true;1995 return true;1996 }1997 catch (Exception e) {1998 return false;1999 } finally {2000 if (!flag) {2001 extentLogs.fail("MouseOver ",2002 "MouseOver Action was <b>NOT</b> perform on <b>" + locatorName + "</b>");2003 } else if ( flag) {2004 extentLogs.pass("MouseOver ",2005 "MouserOver Action was performed on <b>" + locatorName + "</b>");2006 }2007 }2008 }2009 2010 public boolean isElementDisplayed(By loc)2011 throws Throwable {2012 boolean flag = false;2013 try {2014 WebDriverWait newWait = new WebDriverWait(driver,20,30);2015 WebElement element = null;2016 element = newWait.until(ExpectedConditions.presenceOfElementLocated(loc));2017 flag = element.isDisplayed();2018 } catch (Exception e) {2019 return false;2020 }2021 return flag;2022 }2023 public boolean mouseHoverByJavaScript(WebElement we)2024 throws Throwable {2025 boolean flag = false;2026 try {2027 WebElement mo = we;2028 String javaScript = "var evObj = document.createEvent('MouseEvents');"2029 + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"2030 + "arguments[0].dispatchEvent(evObj);";2031 JavascriptExecutor js = (JavascriptExecutor) driver;2032 js.executeScript(javaScript, mo);2033 flag = true;2034 return true;2035 }2036 catch (Exception e) {2037 return false;2038 } /*finally {2039 if (!flag) {2040 Reporter.failureReport("MouseOver ",2041 " MouseOver action is not perform on " + locatorName);2042 } else if (b && flag) {2043 Reporter.SuccessReport("MouseOver ",2044 " MouserOver Action is Done on " + locatorName);2045 }2046 }*/2047 }2048 2049 public boolean waitForTitlePresent(By locator) throws Throwable {2050 boolean flag = false;2051 boolean bValue = false;2052 try {2053 for (int i = 0; i < 200; i++) {2054 if (driver.findElements(locator).size() > 0) {2055 flag = true;2056 bValue = true;2057 break;2058 } else {2059 driver.wait(50);2060 }2061 }2062 } catch (Exception e) {2063 e.printStackTrace();2064 } finally {2065 if (!flag) {2066 extentLogs.fail("WaitForTitlePresent ", "Title is wrong");2067 } else if (flag) {2068 extentLogs.pass("WaitForTitlePresent ",2069 "Launched successfully expected Title ");2070 }2071 }2072 return bValue;2073 }2074 2075 2076 /**2077 * @author Cigniti Select a value from Dropdown using send keys.2078 *2079 * @param locator2080 * : Action to be performed on element (Get it from Object2081 * repository)2082 * @param value2083 * : Value wish type in dropdown list2084 * @param locatorName2085 * : Meaningful name to the element (Ex:Year Dropdown, items2086 * Listbox etc..)2087 * @return true, if successful2088 * @throws Throwable2089 * the throwable2090 */2091 public boolean selectBySendkeys(By locator, String value, String locatorName) throws Throwable {2092 boolean flag = false;2093 try {2094 WebDriverWait wait = new WebDriverWait(this.driver, 60);2095 ScrollToElementVisible(locator);2096 wait.until(ExpectedConditions.elementToBeClickable(locator));2097 if (CommonVariables.DeviceName.get().equalsIgnoreCase("ie")2098 || CommonVariables.DeviceName.get().equalsIgnoreCase("safari")) {2099 this.driver.findElement(locator).click();2100 Select drp = new Select(this.driver.findElement(locator));2101 drp.selectByVisibleText(value);2102 } else {2103 this.driver.findElement(locator).sendKeys(value);2104 }2105 fluentWait(30, 6);2106 flag = true;2107 } catch (Exception e) {2108 extentLogs.error("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName2109 + " due to exception - " + e.getLocalizedMessage());2110 flag = false;2111 } finally {2112 if (flag == false) {2113 extentLogs.fail("Select", "'" + value + "'" + "is not selected from the DropDown " + locatorName);2114 } else if (flag == true) {2115 extentLogs.pass("Select", "'" + value + "'" + "is selected from the DropDown " + locatorName);2116 }2117 }2118 return flag;2119 }2120 /**2121 * @author Cigniti select value from DropDown by using selectByIndex.2122 * @param locator:2123 * Action to be performed on element (Get it from Object2124 * repository)2125 * @param index:2126 * Index of value wish to select from dropdown list.2127 * @param locatorName:2128 * Meaningful name to the element (Ex:Year Dropdown, items2129 * Listbox etc..)2130 * @return true, if successful2131 * @throws Throwable2132 * the throwable2133 */2134 public boolean selectByIndex(By locator, int index, String locatorName) throws Throwable {2135 boolean flag = false;2136 try {2137 WebDriverWait wait = new WebDriverWait(this.driver, 60);2138 ScrollToElementVisible(locator);2139 wait.until(ExpectedConditions.elementToBeClickable(locator));2140 Select s = new Select(this.driver.findElement(locator));2141 s.selectByIndex(index);2142 flag = true;2143 } catch (Exception e) {2144 extentLogs.error("Select", " Option at index " + index + " is Not selected from the DropDown" + locatorName2145 + " due to exception - " + e.getLocalizedMessage());2146 flag = false;2147 } finally {2148 if (flag == false) {2149 extentLogs.fail("Select",2150 " Option at index " + index + " is not Selected from the DropDown" + locatorName);2151 } else if (flag == true) {2152 extentLogs.pass("Select", " Option at index " + index + " is Selected from the DropDown" + locatorName);2153 }2154 }2155 return flag;2156 }2157 /**2158 * @description: waitForVisibilityOfElement2159 * @param locator2160 * @param locatorName2161 * @param timeOutInSeconds2162 * @return2163 * @throws Throwable2164 */2165 public boolean waitForVisibilityOfElement(By locator, String locatorName, long timeOutInSeconds) throws Throwable {2166 try {2167 WebDriverWait wait = new WebDriverWait(this.driver, timeOutInSeconds);2168 wait.until(ExpectedConditions.visibilityOfElementLocated(locator));2169 this.driver.findElement(locator);2170 return true;2171 } catch (Exception e) {2172 e.printStackTrace();2173 return false;2174 }2175 }2176 /**2177 * @author Cigniti2178 * @description: Get all the options from drop down list2179 * @param locator2180 * @param value2181 * @param locatorName2182 * @return2183 * @throws Throwable2184 */2185 public List<String> getAllOptionsFromDropdown(By locator, String locatorName) throws Throwable {2186 try {2187 Select dropdown = new Select(this.driver.findElement(locator));2188 List<WebElement> optionsList = dropdown.getOptions();2189 List<String> optionNamesList = new ArrayList<String>();2190 for (WebElement option : optionsList) {2191 optionNamesList.add(option.getText());2192 }2193 return optionNamesList;2194 } catch (Exception e) {2195 return null;2196 }2197 }2198 /**2199 * @author Cigniti2200 * @description: Verify alert present or not2201 * @return true, if successful2202 * @throws Throwable2203 * the throwable2204 * @return: Boolean (True: If alert preset, False: If no alert)2205 */2206 public boolean JSAcceptAlert() throws Throwable {2207 boolean flag = false;2208 try {2209 JavascriptExecutor executor = (JavascriptExecutor) this.driver;2210 executor.executeScript("confirm = function(message){return true;};");2211 executor.executeScript("alert = function(message){return true;};");2212 executor.executeScript("prompt = function(message){return true;}");2213 flag = true;2214 } catch (Exception e) {2215 extentLogs.fail("Accept Alert", "Failed to accept alert due to execption - " + e.getLocalizedMessage());2216 } finally {2217 if (flag == false) {2218 extentLogs.fail("Accept Alert", "Failed to accept alert.");2219 return flag;2220 } else if (flag == true) {2221 extentLogs.fail("Accept Alert", "Alert accepted successfully.");2222 return flag;2223 }2224 }2225 return flag;2226 }2227 public boolean selectByValue(By locator, String value,2228 String locatorName) throws Throwable {2229 boolean flag = false;2230 try {2231 Select s = new Select(driver.findElement(locator));2232 s.selectByValue(value);2233 flag = true;2234 return true;2235 } catch (Exception e) {2236 Assert.assertTrue(flag,"Option with value attribute " + value2237 + " is Not Selected from the DropDown "2238 + locatorName);2239 e.printStackTrace();2240 return false;2241 } finally {2242 if (!flag) {2243 extentLogs.fail("Select",2244 "Option with value attribute " + value2245 + " is Not Select from the DropDown "2246 + locatorName);2247 } else if ( flag) {2248 extentLogs.pass("Select ",2249 "Option with value attribute " + value2250 + " is Selected from the DropDown "2251 + locatorName);2252 }2253 }2254 }2255 2256 public String getSelectedOption(By locator,2257 String locatorName) throws Throwable {2258 String strSelectdOption="";2259 boolean flag = false;2260 try {2261 Select s = new Select(driver.findElement(locator));2262 strSelectdOption=s.getFirstSelectedOption().getText();2263 flag = true;2264 return strSelectdOption;2265 } catch (Exception e) {2266 return strSelectdOption;2267 } finally {2268 if (!flag) {2269 extentLogs.fail("Get Selected Value","Not Able to Get Selected Value from the DropDown " + locatorName);2270 } else if (flag) {2271 extentLogs.pass("Get Selected Value ",strSelectdOption + "is Selected from the DropDown " + locatorName);2272 }2273 }2274 }2275 2276 2277 /**2278 * @author Cigniti2279 * @description : Set Window Handles2280 */2281 public void SetWindowHandles() {2282 try {2283 Thread.sleep(2000);2284 } catch (InterruptedException e1) {2285 }2286 try {2287 // Retrieve handles for all opened browser windows2288 if (driver != null && this.driver != null) {2289 /*2290 * arrKnownBrowserHwnd= appiumDriver.getContextHandles();2291 */} else {2292// arrKnownBrowserHwnd = driver.getWindowHandles();2293 }2294 if (driver == null) {2295 if (arrKnownBrowserHwnd.size() >= 1) {2296 for (String winHandle : arrKnownBrowserHwnd) {2297 hwndMostRecentWindow = winHandle; // Set variable value2298 // to the newly2299 // opened window2300 }2301 } else if (arrKnownBrowserHwnd.size() == 0) {2302 // No window appeared2303 hwndMostRecentWindow = null;2304 }2305 }2306 } catch (Exception e) {2307 System.out.println(e.getMessage());2308 }2309 }2310 /**2311 * @author Cigniti2312 * @description : Switch to most recent browser2313 * @return2314 */2315 public String switchToMostRecentBrowser() {2316 return switchToMostRecentBrowser("");2317 }2318 /**2319 * @author Cigniti2320 * @description : Switch to most recent browser with title2321 * @param windowTitle2322 * @return2323 */2324 public String switchToMostRecentBrowser(String windowTitle) {2325 try {2326 try {2327 Thread.sleep(1000);2328 } catch (InterruptedException excep) {2329 }2330 ;2331 SetWindowHandles();2332 if (windowTitle.isEmpty()) {2333 if (driver != null && this.EventFiringWebDriver != null) {2334 /*2335 * appiumDriver.context(hwndMostRecentWindow); this.driver =2336 * appiumDriver; driver = new2337 * EventFiringWebDriver(this.driver); eventListener = null;2338 * eventListener = new WebDriverListeners(driver);2339 * driver.register(eventListener);2340 */} else {2341 EventFiringWebDriver.getWrappedDriver().switchTo().window(hwndMostRecentWindow);2342 }2343 // If its IE browser and locally running, set focus as well2344 if (ConfigManager.getProperties().getProperty("seleniumGrid").toLowerCase().trim().contains("false")) {2345 activateCurrentBrowserWindow();2346 } else if (ConfigManager.getProperties().getProperty("cloudExecution").toLowerCase().trim()2347 .contains("false")) {2348 activateCurrentBrowserWindow();2349 }2350 } else {2351 if (driver != null && this.EventFiringWebDriver != null) {2352 /*2353 * appiumDriver.context(windowTitle.trim()); this.driver =2354 * appiumDriver; driver = new2355 * EventFiringWebDriver(this.driver); eventListener = null;2356 * eventListener = new WebDriverListeners(driver);2357 * driver.register(eventListener);2358 */} else {2359 windowTitle.trim().toLowerCase();2360 for (String winHandle : arrKnownBrowserHwnd) {2361 if (EventFiringWebDriver.switchTo().window(winHandle).getTitle().trim().toLowerCase().contains(windowTitle)) {2362 WebdriverWaitForPage();2363 break;2364 }2365 }2366 }2367 }2368 } catch (Exception e) {2369 return null;2370 }2371 return hwndMostRecentWindow;2372 }2373 /**2374 * @author Cigniti2375 * @description : Activate current browser window2376 * @return2377 */2378 public String activateCurrentBrowserWindow() {2379 // Try to switch to most recent browser window, if require2380 return hwndMostRecentWindow;2381 }2382 /**2383 * @author Cigniti2384 * @description : open application using url2385 * @param url2386 */2387 public void OpenApplication(String url) {2388 OpenUrl(url);2389 }2390 /**2391 * @author Cigniti2392 * @description : Open url2393 * @param url2394 * @return2395 */2396 public boolean OpenUrl(String url) {2397 try {2398 driverStartfailureCount = 1;2399 if (CommonVariables.TestCaseLog.get() != null) {2400 CommonVariables.TestClassLog.get().info("Info: navigating URL : '" + url + "'");2401 } else {2402 CommonVariables.TestClassLog.get().info("Info: navigating URL : '" + url + "'");2403 }2404 driver.navigate().to(url);2405 return true;2406 } catch (org.openqa.selenium.NoSuchElementException e) {2407 if (AcceptAlert()) {2408 driver.navigate().to(url);2409 try {2410 Thread.sleep(15000);2411 } catch (InterruptedException e1) {2412 }2413 return true;2414 } else {2415 extentLogs.info("Open URL",2416 "caught 'NoSuchElementException' exception while try to open '" + url + "'.");2417 if (CommonVariables.TestCaseLog.get() != null) {2418 CommonVariables.TestClassLog.get()2419 .info("Info: caught 'NoSuchElementException' exception while try to open '" + url + "'.");2420 } else {2421 CommonVariables.TestClassLog.get()2422 .info("Info: caught 'NoSuchElementException' exception while try to open '" + url + "'.");2423 }2424 }2425 throw new NoSuchElementException("");2426 } catch (org.openqa.selenium.UnhandledAlertException e) {2427 if (AcceptAlert()) {2428 driver.navigate().to(url);2429 try {2430 Thread.sleep(15000);2431 } catch (InterruptedException e1) {2432 }2433 return true;2434 }2435 extentLogs.info("Open URL", "caught 'UnhandledAlertException' exception while try to open '" + url + "'.");2436 throw new UnhandledAlertException("");2437 } catch (TimeoutException e1) {2438 extentLogs.info("Open URL", "Timed out receiving message from renderer.");2439 this.RefreshBrowser();2440 throw new TimeoutException();2441 } catch (Exception e) {2442 AcceptAlert();2443 extentLogs.info("Open URL",2444 "Failed to open Url. Err : " + e.getMessage() + "Stace track" + e.getStackTrace());2445 return false;2446 }2447 }2448 /**2449 * @author Cigniti2450 * @description : open url using SupressCredential for BMP2451 */2452 public void suppressCredential() {2453 if (ConfigManager.getProperties().getProperty("IsBrowserMobProxyRequire").trim().equalsIgnoreCase("yes")) {2454 Boolean credentials = false;2455 if (ConfigManager.getProperties().getProperty("isBMPAuthenticationRequired").trim()2456 .equalsIgnoreCase("yes")) {2457 credentials = ConfigManager.getProperties().getProperty("urlSuppressCredential").trim().contains("@");2458 }2459 if (credentials) {2460 String url = ConfigManager.getProperties().getProperty("urlSuppressCredential");2461 url = url.replace("https://", "http://");2462 OpenUrl(url);2463 url = url.replace("http://", "https://");2464 OpenUrl(url);2465 }2466 } else {2467 ConfigManager.getProperties().setProperty("urlSuppressCredential",2468 ConfigManager.getProperties().getProperty("urlSuppressCredential"));2469 }2470 }2471 /**2472 * @author Cigniti2473 * @description: Get WebElement attribute value2474 * @param objWebElement2475 * @param attribute2476 * @return2477 */2478 public boolean checkRegularExpression(String pattern, String actual)2479 throws Throwable {2480 boolean flag = false;2481 try {2482 Pattern patternRegex;2483 Matcher matcher;2484 patternRegex = Pattern.compile(pattern);2485 matcher = patternRegex.matcher(actual);2486 flag = matcher.matches();2487 } catch (Exception e) {2488 return false;2489 }2490 return flag;2491 }2492 2493 /**2494 * @author Cigniti2495 * @description: Get WebElement attribute value2496 * @param objWebElement2497 * @param attribute2498 * @return2499 */2500 public boolean verifyElementAbsent(By by, String locatorName)2501 throws Throwable {2502 boolean flag = true;2503 try {2504 driver.findElement(by);2505 flag = false;2506 return false;2507 } catch (Exception e) {2508 extentLogs.pass("Verify Element is NOT displayed",2509 "Element: <b>" + locatorName + " </b> is <b> NOT </b> displayed");2510 return true;2511 } finally {2512 if (!flag) {2513 extentLogs.fail("Verify Element is NOT displayed",2514 "Element: <b>" + locatorName + " </b> is <b> displayed</b>");2515 Assert.assertTrue(flag,"Failed to Assert Element is absent"+ locatorName);2516 } else if (flag) {2517 extentLogs.pass("Verify Element is NOT displayed",2518 "Element: <b>" + locatorName + " </b> is <b> NOT </b> displayed");2519 return flag;2520 }2521 }2522 }2523 /**2524 * @author Cigniti2525 * @description: Get switchToFrameByIndex2526 * @param objWebElement2527 * @param attribute2528 * @return2529 */2530 public boolean switchToFrameByIndex(int index) throws Throwable {2531 boolean flag = false;2532 try {2533 driver.switchTo().frame(index);2534 flag = true;2535 return true;2536 } catch (Exception e) {2537 return false;2538 } finally {2539 if (!flag) {2540 extentLogs.fail("SelectFrame ", " Frame with index "2541 + index + " is not selected");2542 } else if ( flag) {2543 extentLogs.pass("SelectFrame ", " Frame with index "2544 + index + " is selected");2545 }2546 }2547 }2548 2549 /**2550 * @author Cigniti2551 * @description: Get WebElement attribute value2552 * @param objWebElement2553 * @param attribute2554 * @return2555 */2556 public boolean assertText(By by, String text) throws Throwable {2557 boolean flag = false;2558 try {2559 Assert.assertEquals(getElementText(by, text).trim(), text.trim());2560 flag = true;2561 return true;2562 } catch (Exception e) {2563 e.printStackTrace();2564 return false;2565 } finally {2566 if (!flag) {2567 extentLogs.fail("AssertText ", text2568 + " is not present in the element ");2569 return false;2570 } else if (flag) {2571 extentLogs.pass("AssertText ", text2572 + " is present in the element ");2573 }2574 }2575 }2576 2577 2578 /**2579 * @author Cigniti2580 * @description: Get WebElement attribute value2581 * @param objWebElement2582 * @param attribute2583 * @return2584 */2585 public boolean switchToDefaultFrame() throws Throwable {2586 boolean flag = false;2587 try {2588 driver.switchTo().defaultContent();2589 flag = true;2590 return true;2591 } catch (Exception e) {2592 e.printStackTrace();2593 return false;2594 } finally {2595 if (!flag) {2596 extentLogs.fail("SelectFrame ",2597 " The Frame is not selected");2598 } else if (flag) {2599 extentLogs.pass("SelectFrame ",2600 " Frame with Name is selected");2601 }2602 }2603 }2604 2605 /**2606 * @author Cigniti2607 * @description: Get WebElement attribute value2608 * @param objWebElement2609 * @param attribute2610 * @return2611 */2612 public String GetElementAttributeValue(WebElement objWebElement, String attribute) {2613 try {2614 return objWebElement.getAttribute(attribute);2615 } catch (org.openqa.selenium.NoSuchElementException e) {2616 extentLogs.error("Attribute Value",2617 "caught 'ElementNotFoundException' exception. Failed to get attribute - '" + attribute + "' on "2618 + driver.getTitle() + "' page.");2619 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2620 "Error: caught 'ElementNotFoundException' exception. Failed to get '" + attribute + "' value for '"2621 + objWebElement + "' on '" + driver.getTitle() + "' page");2622 return "";2623 } catch (ElementNotVisibleException e) {2624 extentLogs.error("Attribute Value",2625 "caught 'ElementNotVisibleException' exception. Failed to get attribute - '" + attribute + "' on "2626 + driver.getTitle() + "' page.");2627 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2628 "Error: caught 'ElementNotVisibleException' exception. Failed to get '" + attribute2629 + "' value for '" + objWebElement + "' on '" + driver.getTitle() + "' page");2630 return "";2631 } catch (WebDriverException e) {2632 extentLogs.error("Attribute Value", "caught 'WebDriverException' exception. Failed to attribute - '"2633 + attribute + "' on " + driver.getTitle() + "' page.");2634 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2635 "Error: caught 'WebDriverException' exception. Failed to get '" + attribute + "' value for '"2636 + objWebElement + "' on '" + driver.getTitle() + "' page");2637 return "";2638 } catch (NullPointerException e5) {2639 extentLogs.error("Attribute Value", "Caught 'NullPointerException' exception while try to get attribute - '"2640 + attribute + "' on " + driver.getTitle() + "' page.");2641 CommonVariables.TestCaseLog.get()2642 .info("Info. Caught 'NullPointerException' exception while try to get Element Attribute ("2643 + attribute + ") value on '" + driver.getTitle() + "'.");2644 return "";2645 } catch (Exception e) {2646 extentLogs.error("Attribute Value", "Failed to attribute - '" + attribute + "' on " + driver.getTitle()2647 + "' page due to exception - " + e.getMessage());2648 CommonVariables.TestCaseLog.get()2649 .error("Failed to get '" + attribute + "' value. Error Message: " + e.getMessage());2650 return "";2651 }2652 }2653 /**2654 * @author Cigniti2655 * @description: check the existence of an element in DOM2656 * @param by2657 * @param timeoutInSeconds2658 * @return2659 */2660 public boolean IsElementExist(By by, Optional<Long> timeoutInSeconds) {2661 long timeout = timeoutInSeconds.isPresent() ? timeoutInSeconds.get() : 999999;2662 if (timeout == 999999) {2663 timeout = Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut"));2664 }2665 try {2666 AcceptAlert();2667 if (FindElement(by, Optional.of(timeout)) != null) {2668 extentLogs.pass("Presence of Element", "Element exists on '" + driver.getTitle() + "' page.");2669 if (CommonVariables.TestCaseLog.get() != null) {2670 CommonVariables.TestCaseLog.get()2671 .info("Info. Element '" + by + "' exists on '" + driver.getTitle() + "' page.");2672 } else {2673 CommonVariables.TestClassLog.get()2674 .info("Info. Element '" + by + "' exists on '" + driver.getTitle() + "' page.");2675 }2676 return true;2677 } else {2678 extentLogs.fail("Presence of Element", "Element does not exist on '" + driver.getTitle() + "' page.");2679 if (CommonVariables.TestCaseLog.get() != null) {2680 CommonVariables.TestCaseLog.get()2681 .info("Info. Element '" + by + "' deos not exist on '" + driver.getTitle() + "' page.");2682 } else {2683 CommonVariables.TestClassLog.get()2684 .info("Info. Element '" + by + "' deos not exist on '" + driver.getTitle() + "' page.");2685 }2686 return false;2687 }2688 } catch (NullPointerException e) {2689 extentLogs.error("Presence of Element",2690 "Element not exist on " + driver.getTitle() + "' page due to exception - " + e.getMessage());2691 throw e;2692 } catch (NoSuchElementException e) {2693 extentLogs.error("Presence of Element",2694 "Element not exist on " + driver.getTitle() + "' page due to exception - " + e.getMessage());2695 throw e;2696 } catch (Exception e) {2697 extentLogs.error("Presence of Element",2698 "Element not exist on " + driver.getTitle() + "' page due to exception - " + e.getMessage());2699 throw e;2700 }2701 }2702 /**2703 * @author Cigniti2704 * @description : Get URL2705 * @return2706 */2707 public String GetURl() {2708 try {2709 extentLogs.pass("Get URL", "Successfully navigate to url - '" + driver.getCurrentUrl() + "'.");2710 return driver.getCurrentUrl();2711 } catch (StaleElementReferenceException e2) {2712 extentLogs.error("Get URL", "caught 'StaleElementReferenceException' exception while getting '"2713 + driver.getTitle() + "' page.");2714 CommonVariables.TestCaseLog.get()2715 .error("Info: caught 'StaleElementReferenceException' exception while getting '" + driver.getTitle()2716 + "' page title");2717 return "";2718 } catch (org.openqa.selenium.UnhandledAlertException e) {2719 extentLogs.error("Get URL",2720 "caught 'UnhandledAlertException' exception while getting '" + driver.getTitle() + "' page.");2721 CommonVariables.TestCaseLog.get().error("Info: caught 'UnhandledAlertException' exception while getting '"2722 + driver.getTitle() + "' page title");2723 return "";2724 }2725 }2726 /**2727 * @author Cigniti2728 * @description : Navigate Back2729 */2730 public void NavigateBack() {2731 try {2732 driver.navigate().back();2733 extentLogs.pass("Navigate Back", "Successfully navigate back to page - '" + driver.getTitle() + "' page.");2734 try {2735 Thread.sleep(2000);2736 } catch (InterruptedException e) {2737 }2738 } catch (org.openqa.selenium.UnhandledAlertException e) {2739 extentLogs.error("Navigate Back", "caught 'UnhandledAlertException' exception while navigating back from '"2740 + driver.getTitle() + "' page.");2741 CommonVariables.TestCaseLog.get()2742 .info("Info: caught 'UnhandledAlertException' exception while navigating back from '"2743 + driver.getTitle() + "' page");2744 AcceptAlert();2745 } catch (org.openqa.selenium.StaleElementReferenceException e) {2746 extentLogs.error("Navigate Back",2747 "caught 'StaleElementReferenceException' exception while navigating back from '" + driver.getTitle()2748 + "' page.");2749 CommonVariables.TestCaseLog.get()2750 .error("Info: caught 'StaleElementReferenceException' exception while navigating back from '"2751 + driver.getTitle() + "' page");2752 AcceptAlert();2753 }2754 }2755 /**2756 * @author Cigniti2757 * @description : Refresh browser2758 */2759 public void RefreshBrowser() {2760 try {2761 driver.navigate().refresh();2762 extentLogs.pass("Refresh Browser",2763 "Successfully refresh browser at page - '" + driver.getTitle() + "' page.");2764 try {2765 Thread.sleep(6000);2766 } catch (InterruptedException e) {2767 AcceptAlert();2768 }2769 } catch (org.openqa.selenium.UnhandledAlertException e) {2770 extentLogs.error("Refresh Browser",2771 "caught 'UnhandledAlertException' exception while refresh '" + driver.getTitle() + "' page");2772 if (CommonVariables.TestCaseLog.get() != null) {2773 CommonVariables.TestCaseLog.get()2774 .info("Info: caught 'UnhandledAlertException' exception while refresh '" + driver.getTitle()2775 + "' page");2776 } else {2777 CommonVariables.TestClassLog.get()2778 .info("Info: caught 'UnhandledAlertException' exception while refresh '" + driver.getTitle()2779 + "' page");2780 }2781 AcceptAlert();2782 } catch (org.openqa.selenium.StaleElementReferenceException e) {2783 extentLogs.error("Refresh Browser", "caught 'StaleElementReferenceException' exception while refresh '"2784 + driver.getTitle() + "' page.");2785 if (CommonVariables.TestCaseLog.get() != null) {2786 CommonVariables.TestCaseLog.get()2787 .info("Info: caught 'StaleElementReferenceException' exception while refresh '"2788 + driver.getTitle() + "' page");2789 } else {2790 CommonVariables.TestClassLog.get()2791 .info("Info: caught 'StaleElementReferenceException' exception while refresh '"2792 + driver.getTitle() + "' page");2793 }2794 AcceptAlert();2795 } catch (org.openqa.selenium.UnsupportedCommandException e) {2796 extentLogs.error("Refresh Browser",2797 "caught 'UnsupportedCommandException' exception while refresh '" + driver.getTitle() + "' page.");2798 if (CommonVariables.TestCaseLog.get() != null) {2799 CommonVariables.TestCaseLog.get()2800 .info("Info: caught 'UnsupportedCommandException' exception while refresh '" + driver.getTitle()2801 + "' page");2802 } else {2803 CommonVariables.TestClassLog.get()2804 .info("Info: caught 'UnsupportedCommandException' exception while refresh '" + driver.getTitle()2805 + "' page");2806 }2807 try {2808 EventFiringWebDriver.getWrappedDriver().navigate().refresh();2809 } catch (Exception e2) {2810 extentLogs.error("Refresh Browser",2811 "caught 'Exception' exception while refresh '" + driver.getTitle() + "' page.");2812 if (CommonVariables.TestCaseLog.get() != null) {2813 CommonVariables.TestCaseLog.get()2814 .info("Info: caught 'Exception' exception while refresh '" + driver.getTitle() + "' page");2815 } else {2816 CommonVariables.TestClassLog.get()2817 .info("Info: caught 'Exception' exception while refresh '" + driver.getTitle() + "' page");2818 }2819 EventFiringWebDriver.navigate().to(driver.getCurrentUrl());2820 try {2821 Thread.sleep(6000);2822 } catch (InterruptedException e1) {2823 AcceptAlert();2824 }2825 }2826 try {2827 Thread.sleep(6000);2828 } catch (InterruptedException e1) {2829 AcceptAlert();2830 }2831 }2832 }2833 /**2834 * @author Cigniti2835 * @description : get Page Title2836 * @return2837 */2838 public String GetPageTitle() {2839 try {2840 return driver.getTitle();2841 } catch (org.openqa.selenium.UnhandledAlertException e) {2842 extentLogs.error("Page Title",2843 "caught 'UnhandledAlertException' exception while getting '" + driver.getTitle() + "' page.");2844 CommonVariables.TestCaseLog.get().info("Info: caught 'UnhandledAlertException' exception while getting '"2845 + driver.getTitle() + "' page title");2846 if (AcceptAlert()) {2847 return driver.getTitle();2848 }2849 return null;2850 } catch (org.openqa.selenium.StaleElementReferenceException e) {2851 extentLogs.error("Page Title", "caught 'StaleElementReferenceException' exception while getting '"2852 + driver.getTitle() + "' page.");2853 CommonVariables.TestCaseLog.get()2854 .info("Info: caught 'StaleElementReferenceException' exception while getting '" + driver.getTitle()2855 + "' page title");2856 try {2857 if (AcceptAlert()) {2858 return driver.getTitle();2859 } else {2860 return null;2861 }2862 } catch (WebDriverException ex) {2863 return null;2864 }2865 } catch (org.openqa.selenium.TimeoutException e) {2866 extentLogs.error("Page Title",2867 "caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page.");2868 CommonVariables.TestCaseLog.get().info(2869 "Info: caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page title");2870 return null;2871 }2872 }2873 /**2874 * @author Cigniti2875 * @description : Get collection webelements using Find Elements2876 * @param by2877 * @param timeoutInSeconds2878 * @return2879 */2880 public List<WebElement> FindElements(By by, Optional<Long> timeoutInSeconds) {2881 long timeout = timeoutInSeconds.isPresent() ? timeoutInSeconds.get() : -1;2882 if (timeout == -1) {2883 timeout = Long.parseLong(ConfigManager.getProperties().getProperty("globalTimeOut"));2884 }2885 List<WebElement> webElement;2886 try {2887 webElement = (new WebDriverWait(driver, timeout))2888 .until(ExpectedConditions.presenceOfAllElementsLocatedBy(by));2889 extentLogs.pass("Find Elements", "Successfully find matched elements on '" + driver.getTitle() + "' page.");2890 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2891 "Info: Successfully find matched elements by '" + by + "' on '" + driver.getTitle() + "' page.");2892 return webElement;2893 } catch (org.openqa.selenium.UnhandledAlertException e) {2894 if (AcceptAlert()) {2895 return FindElements(by, timeoutInSeconds);2896 }2897 extentLogs.error("Find Elements",2898 "caught 'UnhandledAlertException' exception while finding an elements on '" + driver.getTitle()2899 + "' page.");2900 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2901 "Info: caught 'UnhandledAlertException' exception while finding '" + by + "' element on '"2902 + driver.getTitle() + "' page");2903 throw new UnhandledAlertException("");2904 } catch (StaleElementReferenceException e2) {2905 if (AcceptAlert()) {2906 return FindElements(by, timeoutInSeconds);2907 }2908 extentLogs.error("Find Elements", "caught 'StaleElementReferenceException' exception while getting '"2909 + driver.getTitle() + "' page title.");2910 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2911 "Info: caught 'StaleElementReferenceException' exception while getting '" + driver.getTitle()2912 + "' page title");2913 throw new StaleElementReferenceException("");2914 } catch (TimeoutException e3) {2915 if (AcceptAlert()) {2916 return FindElements(by, timeoutInSeconds);2917 }2918 extentLogs.error("Find Elements",2919 "caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page title.");2920 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2921 "Info: caught 'TimeoutException' exception while getting '" + driver.getTitle() + "' page title");2922 throw new TimeoutException();2923 } catch (NoSuchElementException e4) {2924 if (AcceptAlert()) {2925 return FindElements(by, timeoutInSeconds);2926 }2927 extentLogs.error("Find Elements",2928 "caught 'NoSuchElement' exception while getting '" + driver.getTitle() + "' page title.");2929 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2930 "Info: caught 'NoSuchElement' exception while getting '" + driver.getTitle() + "' page title");2931 throw new NoSuchElementException("No such Element");2932 }2933 }2934 /**2935 * @author Cigniti2936 * @Description: Accept alert pop-ups2937 * @return2938 */2939 public boolean AcceptAlert() {2940 try {2941 Alert alert = driver.switchTo().alert();2942 alert.accept();2943 return true;2944 } catch (Exception e) {2945 return false;2946 }2947 }2948 /**2949 * @author Cigniti2950 * @description : Decline Alert2951 * @return2952 */2953 public boolean declineAlert() {2954 try {2955 Alert alert = driver.switchTo().alert();2956 alert.dismiss();2957 return true;2958 } catch (Exception e) {2959 return false;2960 }2961 }2962 /**2963 * @author Cigniti2964 * @description : Wait for Element Visible2965 * @param by2966 * @param waitTime2967 */2968 public void WaitForElementVisible(final By by, int waitTime) {2969 wait = new WebDriverWait(driver, waitTime);2970 try {2971 wait.until(ExpectedConditions.visibilityOfElementLocated(by));2972 extentLogs.pass("Element Visible", "Element visibile at '" + driver.getTitle() + "' page.");2973 } catch (TimeoutException e) {2974 extentLogs.error("Element Visible",2975 "caught 'TimeoutException' exception while wait for element visibility at '" + driver.getTitle()2976 + "' page.");2977 if (CommonVariables.TestCaseLog.get() != null) {2978 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",2979 "Info: caught 'TimeoutException' exception while wait for element ( " + by.toString()2980 + " ) visibility at '" + driver.getTitle() + "' page");2981 } else {2982 CommonVariables.TestClassLog.get()2983 .info("Info: caught 'TimeoutException' exception while wait for element ( " + by.toString()2984 + " ) visibility at '" + driver.getTitle() + "' page");2985 }2986 }2987 }2988 /**2989 * @author Cigniti Description: capture screenshot2990 * @param driver2991 * @param fileName2992 */2993 private void takesScreenShot(WebDriver driver, String fileName) {2994 WebDriver driverScreenShot = new Augmenter().augment(driver);2995 File scrFile = ((TakesScreenshot) driverScreenShot).getScreenshotAs(OutputType.FILE);2996 try {2997 FileUtils.copyFile(scrFile, new File(fileName));2998 } catch (IOException e) {2999 e.printStackTrace();3000 }3001 }3002 /**3003 * @author Cigniti3004 * @description : Save Screenshot3005 * @param ImgPath3006 * @return3007 */3008 public static boolean saveScreenshot(String ImgPath) {3009 try {3010 // This is the ultimate implementation. Right now, we are able to3011 // get the joined images in chrome ONLY.3012 if (GetDriverInfo().get("DriverName").contains("Chrome")) {3013 try {3014 saveFullScreenShot(ImgPath);3015 return true;3016 } catch (Exception e) {3017 System.out.println(3018 "Getting exception while taking full screenshot. Exception message:" + e.getStackTrace());3019 }3020 }3021 3022 if (GetDriverInfo().get("DriverName").contains("android-web")) {3023 try {3024 File scrFile = ((TakesScreenshot) driver)3025 .getScreenshotAs(OutputType.FILE);3026 3027 // Now you can do whatever you need to do with it, for example copy3028 // somewhere3029 FileUtils.copyFile(scrFile, new File(ImgPath));3030 return true;3031 } catch (Exception e) {3032 System.out.println(3033 "Getting exception while taking full screenshot. Exception message:" + e.getStackTrace());3034 }3035 }3036 3037 // This needs to be removed if we are able to get the joined images3038 // in other browsers3039// if (CommonVariables.getDriver() != null && ! EventFiringWebDriver.getWrappedDriver().getWindowHandle().isEmpty()) {3040 if (CommonVariables.getDriver() != null) {3041 File screenshot = null;3042 if (ConfigManager.getProperties().getProperty("seleniumGrid").trim().equalsIgnoreCase("true")) {3043 org.openqa.selenium.WebDriver augmentedDriver = new Augmenter()3044 .augment(CommonVariables.getDriver());3045 try {3046 screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);3047 } catch (WebDriverException e) {3048 e.printStackTrace();3049 }3050 } else if (ConfigManager.getProperties().getProperty("cloudExecution").trim()3051 .equalsIgnoreCase("true")) {3052 org.openqa.selenium.WebDriver augmentedDriver = new Augmenter().augment(EventFiringWebDriver.getWrappedDriver());3053 try {3054 screenshot = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);3055 } catch (WebDriverException e) {3056 e.printStackTrace();3057 }3058 } else if (EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("chromedriver")3059 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("safari")3060 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("firefox")3061 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("internet")3062 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("ie")3063 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("edge")3064 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("Microsoft")3065 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("opera")3066 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("PhantomJS")3067 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("remotewebdriver")) {3068 screenshot = ((TakesScreenshot) EventFiringWebDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);3069 }3070 File screenshotfile = new File(ImgPath);3071 try {3072 FileUtils.copyFile(screenshot, screenshotfile);3073 if (EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("internet")3074 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("ie")) {3075 Thread.sleep(1500);3076 }3077 return true;3078 } catch (IOException e) {3079 e.printStackTrace();3080 }3081 }3082 } catch (Exception e) {3083 System.out.println();3084 e.printStackTrace();3085 return false;3086 }3087 return false;3088 }3089 /**3090 * @author Cigniti3091 * @description : Capture Full Screenshot3092 * @param ImgPath3093 */3094 public static void saveFullScreenShot(String ImgPath) {3095 CaptureScreenShot fullscreenshot = new CaptureScreenShot();3096 try {3097 fullscreenshot.seleniumCaptureBrowserScreenShot(EventFiringWebDriver, ImgPath);3098 } catch (InterruptedException | IOException e) {3099 e.printStackTrace();3100 }3101 }3102 /****************************************************************************************************************************3103 * Function Name : isElementEnabled() Description : Element is disabled or not3104 * 3105 * @param objLocator3106 * : Action to be performed on element (Get it from Object3107 * repository)3108 * @param strLocatorName3109 * : Meaningful name to the element (Ex:Login Button, UserName3110 * Textbox etc..)3111 * @return: boolean value (True: if the element is enabled, false: if it not3112 * enabled).3113 ****************************************************************************************************************************/3114 public boolean isElementEnabled(WebElement objLocator, String strLocatorName) throws Throwable {3115 Boolean blnFlag = false;3116 try {3117 if ((objLocator).isEnabled()) {3118 blnFlag = true;3119 extentLogs.pass("Web Locator Status", "Web locator is enabled for - '" + strLocatorName + "'.");3120 }3121 return blnFlag;3122 } catch (NoSuchElementException e) {3123 gStrErrMsg = e.getMessage();3124 return blnFlag;3125 } 3126 }3127 /****************************************************************************************************************************3128 * Function Name : isElementDisabled() Description : Element is disabled or not3129 * 3130 * @param objLocator3131 * : Action to be performed on element (Get it from Object3132 * repository)3133 * @param strLocatorName3134 * : Meaningful name to the element (Ex:Login Button, UserName3135 * Textbox etc..)3136 * @return: boolean value (True: if the element is enabled, false: if it not3137 * enabled).3138 ****************************************************************************************************************************/3139 public boolean isElementDisabled(WebElement objLocator, String strLocatorName) throws Throwable {3140 Boolean blnFlag = false;3141 try {3142 if (!(objLocator).isEnabled()) {3143 blnFlag = true;3144 extentLogs.pass("Web Locator Status", "Web locator is disabled for - '" + strLocatorName + "'.");3145 }3146 return blnFlag;3147 } catch (NoSuchElementException e) {3148 gStrErrMsg = e.getMessage();3149 return blnFlag;3150 } 3151 }3152 /**3153 * @author Cigniti3154 * @description : Is Element Visible in UI3155 * @param by3156 * @return3157 */3158 public boolean IsElementVisible(final By by) {3159 try {3160 wait = new WebDriverWait(driver, 1);3161 wait.until(ExpectedConditions.visibilityOfElementLocated(by));3162 if ((driver.findElement(by).getSize().height == 0) && (driver.findElement(by).getSize().width == 0)) {3163 return false;3164 } else {3165 return true;3166 }3167 } catch (Exception e) {3168 try {3169 if ((e.getClass().isInstance(new TimeoutException(""))3170 || getClass().isInstance(new ElementNotVisibleException("")))3171 || (e.getClass().isInstance(new NoSuchElementException("")))) {3172 if (ScrollToElementVisible(by)) {3173 wait.until(ExpectedConditions.visibilityOfElementLocated(by));3174 if ((driver.findElement(by).getSize().height == 0)3175 && (driver.findElement(by).getSize().width == 0)) {3176 return false;3177 } else {3178 return true;3179 }3180 } else {3181 throw e;3182 }3183 } else {3184 throw e;3185 }3186 } catch (Exception e1) {3187 if (e1.getCause().toString().contains("NoSuchElementException")) {3188 throw new NoSuchElementException("");3189 } else if (e1.getCause().toString().contains("ElementNotVisibleException")) {3190 throw new ElementNotVisibleException("");3191 } else if (e1.getCause().toString().contains("TimeoutException")) {3192 throw new TimeoutException();3193 } else {3194 throw e1;3195 }3196 }3197 }3198 }3199 /**3200 * @author Cigniti3201 * @description : Is Element Visible in UI3202 * @param by3203 * @return3204 */3205 public boolean IsElementVisible(WebElement element) {3206 try {3207 wait = new WebDriverWait(driver, 1);3208 wait.until(ExpectedConditions.visibilityOf(element));3209 if ((element.getSize().height == 0) && (element.getSize().width == 0)) {3210 return false;3211 } else {3212 return true;3213 }3214 } catch (Exception e) {3215 try {3216 if ((e.getClass().isInstance(new TimeoutException(""))3217 || getClass().isInstance(new ElementNotVisibleException("")))3218 || (e.getClass().isInstance(new NoSuchElementException("")))) {3219 if (ScrollToElementVisible(element)) {3220 wait.until(ExpectedConditions.visibilityOf(element));3221 if ((element.getSize().height == 0) && (element.getSize().width == 0)) {3222 return false;3223 } else {3224 return true;3225 }3226 } else {3227 throw e;3228 }3229 } else {3230 throw e;3231 }3232 } catch (Exception e1) {3233 if (e1.getCause().toString().contains("NoSuchElementException")) {3234 throw new NoSuchElementException("");3235 } else if (e1.getCause().toString().contains("ElementNotVisibleException")) {3236 throw new ElementNotVisibleException("");3237 } else if (e1.getCause().toString().contains("TimeoutException")) {3238 throw new TimeoutException();3239 } else {3240 throw e1;3241 }3242 }3243 }3244 }3245 /**3246 * @author Cigniti3247 * @description : Start Video3248 * @param element3249 */3250 public void StartVideo(WebElement element) {3251 try {3252 double browser_top_offset = 80;3253 if (GetDriverInfo().get("DriverName").contains("iphone")) {3254 browser_top_offset = 50;3255 } else if (GetDriverInfo().get("DriverName").contains("ipad")) {3256 browser_top_offset = 80;3257 }3258 RemoteWebElement remoteelem = ((RemoteWebElement) element);3259 JavascriptExecutor js = (JavascriptExecutor) driver;3260 String script = "return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)";3261 Long pageheight1 = (Long) js.executeScript(script);3262 Long pageheight2 = (Long) js.executeScript("return window.innerHeight");3263 Point eloc = remoteelem.getLocation();3264 double yloc = eloc.getY();3265 double elemheight = remoteelem.getSize().getHeight() / 2;3266 double yratio = (yloc + elemheight + browser_top_offset) / pageheight1;3267 HashMap<String, Double> tapObject = new HashMap<String, Double>();3268 tapObject.put("x", 0.5);3269 tapObject.put("y", yratio);3270 js.executeScript("mobile: tap", tapObject);3271 } catch (Exception e) {3272 }3273 }3274 /**3275 * @author Cigniti3276 * @description: scroll to top of the page3277 */3278 public void ScrollToTop() {3279 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("desktop")) {3280 try {3281 JavascriptExecutor js = (JavascriptExecutor) driver;3282 js.executeScript("window.scrollTo(0,0);");3283 } catch (Exception e) {3284 }3285 } else {3286 try {3287 JavascriptExecutor js = (JavascriptExecutor) driver;3288 js.executeScript("$('body').scrollTop(0);");3289 } catch (Exception e) {3290 System.out.println(3291 "Failed to Swipe on Top on Non-Desktop device. Check 'ScrollToTop' method under action library");3292 }3293 }3294 }3295 /**3296 * @author Cigniti3297 * @description: scroll page to bottom of the page3298 */3299 public void ScrollToBottom() {3300 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("desktop")) {3301 try {3302 JavascriptExecutor js = (JavascriptExecutor) driver;3303 js.executeScript("window.scrollTo(0,document.documentElement.scrollHeight);");3304 } catch (Exception e) {3305 }3306 } else {3307 JavascriptExecutor js = (JavascriptExecutor) driver;3308 int height_covered = 0, pageHeightLeft = 0;3309 Long pageheight1 = (Long) js.executeScript("return window.innerHeight");3310 Long maxPageHeight1 = (Long) js3311 .executeScript("return Math.max(document.documentElement.scrollHeight, document.body.scrollHeight,"3312 + "document.documentElement.clientHeight, window.innerHeight)");3313 float sections = (float) maxPageHeight1 / pageheight1;3314 int numberOfRows = (int) Math.ceil(sections);3315 int pageheight = pageheight1.intValue();3316 int maxPageHeight = maxPageHeight1.intValue();3317 for (int row = 0; row < numberOfRows; row++) {3318 pageHeightLeft = maxPageHeight - height_covered;3319 if ((pageHeightLeft < pageheight)) {3320 } else {3321 height_covered = height_covered + pageheight;3322 js.executeScript("window.scrollTo(0," + height_covered + ")");3323 }3324 }3325 }3326 }3327 /**3328 * @author Cigniti3329 * @description : Set GeoLocation with latitide and longitude3330 * @param latitude3331 * @param longitude3332 */3333 public void setGeoLocation(double latitude, double longitude) {3334 try {3335 if (GetDriverInfo().toString().toLowerCase().contains("ipad")3336 || GetDriverInfo().toString().toLowerCase().contains("iphone")3337 || GetDriverInfo().toString().toLowerCase().contains("android")) {3338 JavascriptExecutor js = (JavascriptExecutor) driver;3339 // AppiumDriver dr = (AppiumDriver) this.driver;3340 Location loc = new Location(latitude, longitude, 10);3341 driver.setLocation(loc);3342 try {3343 Thread.sleep(2000);3344 } catch (Exception e) {3345 }3346 } else if (ConfigManager.getProperties().getProperty("deviceType").contains("android")) {3347 System.out.println("Skipping location set..need to be impletemented on Android.");3348 }3349 } catch (Exception ex) {3350 ex.printStackTrace();3351 }3352 }3353 /**3354 * @author Cigniti3355 * @description : Set GeoLocation3356 */3357 public void setGeoLocation() {3358 setGeoLocation(Double.valueOf(ConfigManager.getProperties().getProperty("latitude").trim()),3359 Double.valueOf(ConfigManager.getProperties().getProperty("longitude").trim()));3360 }3361 /**3362 * @param driver3363 * Current driver instance, which is to be nullified.3364 * @param locationServiceEnabled.3365 * Permitted values are: true/false/ask3366 * @param latitude3367 * The latitude of the location to be mocked, if provided with 0,3368 * then this method will pick value from configuration file.3369 * @param longitude3370 * The longitude of the location to be mocked, if provided with3371 * 0, then this method will pick value from configuration file.3372 * @return driver Returns updated driver instance.3373 */3374 public WebDriver resetLocationCapability(WebDriver driver, String locationServiceEnabled, double latitude,3375 double longitude) {3376 if (ConfigManager.getProperties().getProperty("deviceType").toLowerCase().contains("safari-mac")) {3377 if (locationServiceEnabled.trim().toLowerCase().contains("false")3378 || locationServiceEnabled.trim().toLowerCase().contains("ask")) {3379 throw new SkipException(3380 "Skipping because of can't handle location Pop-up. So set-up in Safari profile to share the location always.");3381 } else3382 return driver;3383 }3384 String previousUrl = "";3385 if (GetURl().toLowerCase().contains("http://") || GetURl().toLowerCase().contains("https://")) {3386 previousUrl = GetURl();3387 }3388 tearDown();3389 driver = null;3390 if (GetDriverInfo().toString().toLowerCase().contains("ipad")3391 | GetDriverInfo().toString().toLowerCase().contains("iphone")) {3392 initPropertiesFile();3393 if (locationServiceEnabled.trim().toLowerCase().contains("false")) {3394 this.locationServiceEnabled = false;3395 } else3396 this.locationServiceEnabled = true;3397 this.doFullReset = true;3398 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"), CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());3399 this.EventFiringWebDriver = (EventFiringWebDriver) EventFiringWebDriver;3400 if (locationServiceEnabled != null && (!locationServiceEnabled.trim().toLowerCase().contains("false"))) {3401 if (locationServiceEnabled.trim().toLowerCase().contains("ask")) {3402 } else if (latitude == 0 && longitude == 0) {3403 setGeoLocation();3404 } else if (latitude != 0 && longitude != 0) {3405 setGeoLocation(latitude, longitude);3406 } else {3407 System.err.println("Invalid value under locationServiceEnabled flag. Can not start webdriver.");3408 }3409 }3410 if (previousUrl.isEmpty()) {3411 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));3412 } else {3413 if (!previousUrl.contains("@"))3414 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));3415 OpenUrl(previousUrl);3416 }3417 AcceptAlert();3418 try {3419 Thread.sleep(15000);3420 } catch (InterruptedException ex) {3421 }3422 } else if (GetDriverInfo().toString().toLowerCase().contains("chrome")) {3423 if (locationServiceEnabled.toLowerCase().contains("true")) {3424 this.chromeProfile = "browser-profile-location-boston";3425 this.locationServiceEnabled = true;3426 driver = instantiateDriver(CommonVariables.PlatformName.get() + "-" + CommonVariables.DeviceName.get(), CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());3427 } else if (locationServiceEnabled.toLowerCase().contains("false")) {3428 this.chromeProfile = "browser-profile-location-No";3429 driver = instantiateDriver(CommonVariables.PlatformName.get() + "-" + CommonVariables.DeviceName.get(), CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());3430 } else if (locationServiceEnabled.toLowerCase().contains("ask")) {3431 this.chromeProfile = "browser-profile-location-yes-ask";3432 driver = instantiateDriver(CommonVariables.PlatformName.get() + "-" + CommonVariables.DeviceName.get(), CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());3433 } else {3434 System.err.println("Invalid value under locationServiceEnabled flag. Can not start webdriver.");3435 }3436 if (driver != null) {3437 if (previousUrl.isEmpty()) {3438 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));3439 } else {3440 if (!previousUrl.contains("@"))3441 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));3442 OpenUrl(previousUrl);3443 }3444 AcceptAlert();3445 try {3446 Thread.sleep(10000);3447 } catch (InterruptedException ex) {3448 }3449 }3450 } else if (GetDriverInfo().toString().toLowerCase().contains("firefox")) {3451 if (locationServiceEnabled.toLowerCase().contains("true")) {3452 this.locationServiceEnabled = true;3453 this.firefoxProfilePath = "Firefox_profile_For_Location_Simulate";3454 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"), CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());3455 } else if (locationServiceEnabled.toLowerCase().contains("false")) {3456 this.locationServiceEnabled = false;3457 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"), CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());3458 } else if (locationServiceEnabled.toLowerCase().contains("ask")) {3459 this.locationServiceEnabled = true;3460 this.firefoxProfilePath = "Firefox_Profile__Ask_Location_To_Share";3461 driver = instantiateDriver(ConfigManager.getProperties().getProperty("deviceType"), CommonVariables.UDID.get(), CommonVariables.platformVersion.get(), CommonVariables.browserName.get(), CommonVariables.serverURL.get());3462 } else {3463 System.err.println("Invalid value under locationServiceEnabled flag. Can not start webdriver.");3464 }3465 if (driver != null) {3466 if (previousUrl.isEmpty()) {3467 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));3468 } else {3469 if (!previousUrl.contains("@"))3470 OpenUrl(ConfigManager.getProperties().getProperty("urlSuppressCredential"));3471 OpenUrl(previousUrl);3472 }3473 AcceptAlert();3474 try {3475 Thread.sleep(10000);3476 } catch (InterruptedException ex) {3477 }3478 }3479 } else if (GetDriverInfo().toString().toLowerCase().contains("android-chrome")) {3480 }3481 return driver;3482 }3483 /**3484 * @author Cigniti3485 * @description : Location Alert Present3486 * @param alertShouldBeThereOrNot3487 * @param waitingTime3488 * @return3489 */3490 public boolean assertLocationAlertPresent(boolean alertShouldBeThereOrNot, Long waitingTime) {3491 WebDriverWait wait = new WebDriverWait(EventFiringWebDriver, waitingTime);3492 Alert alert = null;3493 try {3494 alert = wait.until(ExpectedConditions.alertIsPresent());3495 } catch (TimeoutException e) {3496 }3497 Set<String> windowHandles = EventFiringWebDriver.getWindowHandles();3498 if (windowHandles.size() > 1 && alertShouldBeThereOrNot == true) {3499 alert = EventFiringWebDriver.switchTo().alert();3500 /**3501 * The alert text should be the one that is shown on IPhone/IPad. It3502 * should have Allow and Don't Allow buttons.3503 */3504 String alertText = alert.getText();3505 if (!alertText.equals("\"Safari\" Would Like to Use Your Current Location")) {3506 alert = null;3507 }3508 }3509 if (alert != null) {3510 System.out.println("alert is present");3511 } else {3512 System.out.println("alert is not present");3513 }3514 if (alertShouldBeThereOrNot == true && alert != null) {3515 return true;3516 } else if (alertShouldBeThereOrNot == true && alert == null) {3517 return false;3518 }3519 if (alertShouldBeThereOrNot == false && alert != null) {3520 return false;3521 } else if (alertShouldBeThereOrNot == false && alert == null) {3522 return true;3523 } else3524 return false;3525 }3526 public boolean isLocationServiceEnabled() {3527 boolean value = false;3528 if (locationServiceEnabled != null)3529 value = this.locationServiceEnabled.booleanValue();3530 return value;3531 }3532 /**3533 * @author Cigniti3534 * @description : Get Element Xpath3535 * @param element3536 * @return3537 */3538 public String getElementXPath(WebElement element) {3539 try {3540 String str = element.toString().split("->")[1].trim();3541 if (str.contains("xpath")) {3542 String str2 = str.split("xpath: ")[1].trim();3543 str = str2.substring(0, str2.length() - 1);3544 } else {3545 String str2 = str.split(": ")[1].trim();3546 str = str.split(": ")[0].trim() + "=" + str2.substring(0, str2.length() - 1);3547 }3548 return str;3549 } catch (Exception e) {3550 return "<failed to retrive xpath>";3551 }3552 }3553 /**3554 * @author Cigniti3555 * @description : Kill window process3556 * @param processName3557 * @throws Exception3558 */3559 public void KillWindowProcess(String processName) throws Exception {3560 Platform p = Platform.getCurrent();3561 if (!p.is(Platform.MAC)) {3562 String TASKLIST = "tasklist";3563 String KILL = "taskkill /F /IM ";3564 Process proc = Runtime.getRuntime().exec(TASKLIST);3565 BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));3566 String line;3567 while ((line = reader.readLine()) != null) {3568 if (line.contains(processName)) {3569 Runtime.getRuntime().exec(KILL + processName);3570 }3571 }3572 } else {3573 try {3574 Runtime.getRuntime().exec("killall " + processName);3575 Runtime.getRuntime().exec("taskkill /F /IM " + processName);3576 } catch (Exception e) {3577 }3578 }3579 }3580 /**3581 * @author Cigniti3582 * @description: Select values from drop down button using visible text3583 * @param ddb3584 * @param value3585 * @param index3586 */3587 public void SelectFromDropDown(WebElement ddb, String value, int index) {3588 try {3589 Select dropdown = new Select(ddb);3590 dropdown.selectByVisibleText(value);3591 } catch (Exception e) {3592 try {3593 JavascriptExecutor js = (JavascriptExecutor) driver;3594 js.executeScript("arguments[0].selectedIndex = arguments[1];", ddb, index);3595 js.executeScript("$(arguments[0]).trigger('change');", ddb);3596 } catch (Exception e5) {3597 }3598 }3599 }3600 /**3601 * @author Cigniti3602 * @description: Elements counts3603 * @param by3604 * @param timeoutInSeconds3605 * @param description3606 * @return3607 */3608 public Integer CountElement(By by, Optional<Long> timeoutInSeconds, String description) {3609 try {3610 if (!description.equals("")) {3611 extentLogs.info("Elements Count", "Get the count for " + description);3612 }3613 return FindElements(by, timeoutInSeconds).size();3614 } catch (NoSuchElementException e) {3615 extentLogs.error("Elements Count",3616 "Unable to get the count of elements due to exeception - " + e.getLocalizedMessage());3617 return 0;3618 } catch (Exception e) {3619 extentLogs.error("Elements Count",3620 "Unable to get the count of elements due to exeception - " + e.getLocalizedMessage());3621 return 0;3622 }3623 }3624 /**3625 * @author Cigniti3626 * @description: get element inner text directly using locator value3627 * @param by3628 * @param description3629 * @return3630 */3631 public String getElementInnerText(By by, String description) throws Throwable {3632 try {3633 if (!description.equals("")) {3634 extentLogs.pass("Inner Text of Element", "Get text for " + description);3635 }3636 WebElement elem = FindElement(by, Optional.of(Long.parseLong("4")));3637 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());3638 String text = (String) js.executeScript("return arguments[0].innerHTML.toString();", elem);3639 return text;3640 } catch (NoSuchElementException e) {3641 extentLogs.error("Inner Text of Element",3642 "No such element found to get inner text due to execption - " + e.getLocalizedMessage());3643 return "";3644 } catch (Exception e) {3645 driver.findElement(by).getText();3646 return "";3647 }3648 }3649 /**3650 * @author Cigniti3651 * @description: get element inner text using WebElement3652 * @param elem3653 * @param description3654 * @return3655 */3656 public String getElementInnerText(WebElement elem, String description) {3657 try {3658 if (!description.equals("")) {3659 extentLogs.pass("Inner Text of Element", "Get text for " + description);3660 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "Get text for " + description);3661 }3662 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());3663 String text = (String) js.executeScript("return arguments[0].innerHTML.toString();", elem);3664 return text;3665 } catch (NoSuchElementException e) {3666 extentLogs.error("Inner Text of Element", "No such element found to get element inner text.");3667 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "error", "No such element found");3668 return "";3669 } catch (Exception e) {3670 return "";3671 }3672 }3673 /**3674 * @author Cigniti3675 * @description: get text between open and close tag3676 * @param by3677 * @param description3678 * @return3679 */3680 public String getElementText(By by, String description) throws Throwable {3681 try {3682 if (!description.equals("")) {3683 extentLogs.pass("Element Text", "Get text for " + description);3684 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "Get text for " + description);3685 }3686 return FindElement(by, Optional.of(Long.parseLong("4"))).getText();3687 } catch (NoSuchElementException e) {3688 extentLogs.error("Element Text",3689 "No such element found to get element text due to exception - " + e.getLocalizedMessage());3690 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "No such element found XPATH: " + by);3691 return "";3692 } catch (NullPointerException e) {3693 extentLogs.error("Element Text",3694 "No such element found to get element text due to exception - " + e.getLocalizedMessage());3695 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", "No such element found XPATH: " + by);3696 return "";3697 } catch (Exception e) {3698 driver.findElement(by).getText();3699 extentLogs.error("Element Text",3700 "No such element found to get element text due to exception - " + e.getLocalizedMessage());3701 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info", e.getLocalizedMessage() + " - " + by);3702 return "";3703 }3704 }3705 /**3706 * @author Cigniti3707 * @description: compare values for validation3708 * @param actual3709 * @param expected3710 * @param errorText3711 * @return3712 */3713 public boolean verifyText(By by, String text, String locatorName)3714 throws Throwable {3715 boolean flag = false;3716 try {3717 String vtxt = getElementText(by, locatorName).trim();3718 vtxt.equals(text.trim());3719 flag = true;3720 return true;3721 } catch (Exception e) {3722 return false;3723 } finally {3724 if (!flag) {3725 extentLogs.fail("VerifyText ", "<b>" +text3726 + "</b> is <b>NOT</b> present in the location: <b>" + locatorName + "</b>");3727 flag = true;3728 } else if (flag) {3729 extentLogs.pass("VerifyText ", "<b>" +text3730 + "</b> is present in the location: <b>" + locatorName + "</b>");3731 flag = false;3732 }3733 }3734 }3735 3736 /**3737 * @author Cigniti3738 * @description: compare values for validation3739 * @param actual3740 * @param expected3741 * @param errorText3742 * @return3743 */3744 public Boolean compareValues(String actual, String expected, String errorText) {3745 boolean flag = true;3746 if (!actual.trim().equalsIgnoreCase(expected.trim())) {3747 extentLogs.fail("Compare Text Values",3748 "" + errorText + " did not match. Expected text is-" + expected + " and Actual text is-" + actual);3749 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "error",3750 errorText + " did not match. Expected text is-" + expected + " and Actual text is-" + actual);3751 flag = false;3752 } else {3753 extentLogs.pass("Compare Text Values",3754 "Actual and Expected Value are matched, expected and actual value is " + expected);3755 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "info",3756 "Actual and Expected Value are matched, expected and actual value is " + expected);3757 flag = true;3758 }3759 return flag;3760 }3761 /**3762 * @author Cigniti3763 * @description: verify string contains for validation3764 * @param actual3765 * @param expected3766 * @param errorText3767 * @return3768 */3769 public Boolean checkStringContains(String actual, String expected, String errorText) {3770 boolean flag = true;3771 if (!actual.trim().contains(expected.trim())) {3772 extentLogs.fail("Presence of Text", "" + errorText + " did not contain expected String. Expected string is-"3773 + expected + " and Actual string is-" + actual);3774 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "error",3775 errorText + " did not contain expected String. Expected string is-" + expected3776 + " and Actual string is-" + actual);3777 flag = false;3778 } else {3779 extentLogs.pass("Presence of Text",3780 "Actual string contains the expected String, expected and actual string is " + expected);3781 CustomLogs.addToLog(CustomLogName.CurrentTestCaseLog, "PASS",3782 "Actual string contains the expected String, expected and actual string is " + expected);3783 flag = true;3784 }3785 return flag;3786 }3787 /**3788 * @author Cigniti3789 * @description: get element attribute value with description.3790 * @param by3791 * @param attribute3792 * @param description3793 * @return3794 */3795 public String getElementAttribute(By by, String attribute, String description) {3796 try {3797 return driver.findElement(by).getAttribute(attribute).toString();3798 } catch (NoSuchElementException e) {3799 extentLogs.error("Attribute Value",3800 "No such element found to get attribute value due to exception - " + e.getLocalizedMessage());3801 return "";3802 } catch (Exception e) {3803 driver.findElement(by).getText();3804 extentLogs.error("Attribute Value",3805 "No such element found to get attribute value due to exception - " + e.getLocalizedMessage());3806 return "";3807 }3808 }3809 /**3810 * @author Cigniti3811 */3812 public static enum Mode {3813 ALPHA, ALPHANUMERIC, NUMERIC3814 }3815 /**3816 * @author Cigniti3817 * @description: get calendar month value in numeric format3818 * @param monthCharValue3819 * @return3820 */3821 public String getMonthNumericValue(String monthCharValue) {3822 switch (monthCharValue.trim().toUpperCase()) {3823 case "JAN":3824 case "JANUARY":3825 return "01";3826 case "FEB":3827 case "FEBRUARY":3828 return "02";3829 case "MAR":3830 case "MARCH":3831 return "03";3832 case "APR":3833 case "APRIL":3834 return "04";3835 case "MAY":3836 return "05";3837 case "JUN":3838 case "JUNE":3839 return "06";3840 case "JULY":3841 case "JUL":3842 return "07";3843 case "AUGUST":3844 case "AUG":3845 return "08";3846 case "SEP":3847 case "SEPTEMBER":3848 return "09";3849 case "OCT":3850 case "OCTOBER":3851 return "10";3852 case "NOV":3853 case "NOVEMBER":3854 return "11";3855 case "DECEMBER":3856 case "DEC":3857 return "12";3858 default:3859 extentLogs.info("Numeric value of the Month", "Incorrect value specified :" + monthCharValue);3860 return "";3861 }3862 }3863 /**3864 * Get Month Name3865 * 3866 * @param monthNumericValue3867 * @return3868 */3869 public String getMonthName(String monthNumericValue) {3870 switch (monthNumericValue.trim()) {3871 case "01":3872 return "January";3873 case "02":3874 return "February";3875 case "03":3876 return "March";3877 case "04":3878 return "April";3879 case "05":3880 return "May";3881 case "06":3882 return "June";3883 case "07":3884 return "July";3885 case "08":3886 return "August";3887 case "09":3888 return "September";3889 case "10":3890 return "October";3891 case "11":3892 return "November";3893 case "12":3894 return "December";3895 default:3896 return "";3897 }3898 }3899 /**3900 * @author Cigniti3901 * @descriton: generate random number - alpa,num,alphnum3902 * @param length3903 * @param mode3904 * @return3905 */3906 public static String generateRandomString(int length, Mode mode) {3907 StringBuffer buffer = new StringBuffer();3908 String characters = "";3909 Boolean isNumericOnly = false;3910 String automationTextPrefix = "";3911 switch (mode) {3912 case ALPHA:3913 characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";3914 break;3915 case ALPHANUMERIC:3916 characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";3917 break;3918 case NUMERIC:3919 isNumericOnly = true;3920 characters = "123456789";3921 break;3922 }3923 int charactersLength = characters.length();3924 if (length >= 3 && !isNumericOnly) {3925 length = length - 2;3926 automationTextPrefix = "AT";3927 }3928 for (int i = 0; i < length; i++) {3929 double index = Math.random() * charactersLength;3930 buffer.append(characters.charAt((int) index));3931 }3932 if (isNumericOnly) {3933 return buffer.toString();3934 } else {3935 return automationTextPrefix + buffer.toString();3936 }3937 }3938 /**3939 * @author Cigniti3940 * @description: download pdf document3941 * @param pdfPagedriver3942 * @param documentName3943 * @param filePath3944 */3945 public void DownloadPDFDocument(WebDriver pdfPagedriver, String documentName, String filePath) {3946 HttpClient httpClient = new DefaultHttpClient();3947 httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);3948 CookieStore cookieStore = new BasicCookieStore();3949 Set<org.openqa.selenium.Cookie> cookies = pdfPagedriver.manage().getCookies();3950 for (org.openqa.selenium.Cookie cookie : cookies) {3951 BasicClientCookie2 cookie2 = new BasicClientCookie2(cookie.getName(), cookie.getValue());3952 cookie2.setAttribute(ClientCookie.VERSION_ATTR, "1");3953 cookie2.setAttribute(ClientCookie.DOMAIN_ATTR, cookie.getDomain());3954 cookie2.setDomain(cookie.getDomain());3955 cookie2.setPath(cookie.getPath());3956 cookie2.setExpiryDate(cookie.getExpiry());3957 cookieStore.addCookie(cookie2);3958 }3959 HttpContext httpContext = new BasicHttpContext();3960 httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);3961 try {3962 HttpResponse httpResponse = httpClient.execute(new HttpGet(pdfPagedriver.getCurrentUrl()), httpContext);3963 InputStream inputStream = httpResponse.getEntity().getContent();3964 FileOutputStream fos = new FileOutputStream(filePath + "\\" + documentName.replaceAll("\\s+", "") + ".pdf");3965 byte[] buffer = new byte[2048];3966 int bytesRead = 0;3967 while ((bytesRead = inputStream.read(buffer)) != -1) {3968 fos.write(buffer, 0, bytesRead);3969 }3970 fos.close();3971 } catch (ClientProtocolException e) {3972 } catch (IOException e) {3973 }3974 httpClient.getConnectionManager().shutdown();3975 }3976 /**3977 * @author Cigniti3978 * @description: verify text presence in UI3979 * @param txtValue3980 * @return3981 */3982 public boolean isTextPresentOnPage(String txtValue) {3983 boolean b = false;3984 try {3985 String bodyText = driver.findElement(By.tagName("body")).getText();3986 b = bodyText.contains(txtValue.trim());3987 if (b) {3988 extentLogs.pass("Presence of Text", "Info : '" + txtValue + "' is found on Page.");3989 b = true;3990 } else {3991 extentLogs.fail("Presence of Text", "Info : '" + txtValue + "' is not found on Page ");3992 b = false;3993 }3994 } catch (Exception e) {3995 extentLogs.error("Presence of Text", "Exception in isTextPresentOnPage" + e.getMessage());3996 b = false;3997 }3998 return b;3999 }4000 /**4001 * @author Cigniti4002 * @description e.g. for Jul 16 2014 03:32:06 AM format pass 'MMM dd yyyy4003 * hh:mm:ss aa' as dateformat value.4004 * @param dateformat4005 * @return4006 */4007 public String getCurrentDataTime(String dateformat) {4008 Calendar cal = Calendar.getInstance();4009 SimpleDateFormat sdf = new SimpleDateFormat(dateformat);4010 try {4011 return sdf.format(cal.getTime());4012 } catch (Exception e) {4013 e.getMessage();4014 return "";4015 }4016 }4017 /**4018 * @author Cigniti4019 * @param -4020 * dateValue = "Jul 16 2014 03:32:06 AM" and format =4021 * "MMM dd yyyy hh:mm:ss aa"4022 * @param -4023 * dateValue = "7-Jun-2013" and format = "dd-MMM-yyyy"4024 * @param dateValue4025 * @param format4026 * @return4027 */4028 public Date getDateTimeFromProvidedString(String dateValue, String format) {4029 SimpleDateFormat formatter = new SimpleDateFormat(format);4030 try {4031 Date date = formatter.parse(dateValue);4032 return date;4033 } catch (ParseException e) {4034 e.getMessage();4035 return null;4036 }4037 }4038 /**4039 * @author Cigniti4040 * @description: get date in user's required format4041 * @param date4042 * @param dateformat4043 * @return4044 */4045 public String getDateTimeFromProvidedString(Date date, String dateformat) {4046 SimpleDateFormat sdf = new SimpleDateFormat(dateformat);4047 try {4048 return sdf.format(date);4049 } catch (Exception e) {4050 // AddToLog("CurrentTestCaseLog", "error","Failed to convert current4051 // Date and Time in the provided format ("+dateformat+")");4052 return "";4053 }4054 }4055 /**4056 * @author Cigniti4057 * @description: wait for element present4058 * @param by4059 * @param timeout4060 * @return4061 */4062 public Boolean waitForElementPresent(By by, Integer timeout) {4063 Boolean flag = false;4064 for (Integer i = 1; i <= timeout; i++) {4065 if (IsElementExist(by, Optional.of(Long.parseLong("0")))) {4066 flag = true;4067 break;4068 }4069 try {4070 Thread.sleep(1000);4071 } catch (InterruptedException e) {4072 }4073 }4074 return flag;4075 }4076 /**4077 * @author Cigniti4078 * @description: wait for element not present4079 * @param by4080 * @param timeout4081 * @return4082 */4083 public Boolean waitForElementNotPresent(By by, Integer timeout) {4084 Boolean flag = false;4085 for (Integer i = 1; i <= timeout; i++) {4086 if (!IsElementExist(by, Optional.of(Long.parseLong("0")))) {4087 flag = true;4088 break;4089 }4090 try {4091 Thread.sleep(1000);4092 } catch (InterruptedException e) {4093 }4094 }4095 return flag;4096 }4097 /**4098 * @author Cigniti4099 * @description: move to element directly using locator value4100 * @param xpath4101 */4102 public void setFocusByXpath(String xpath) {4103 try {4104 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4105 js.executeScript(4106 "$(document.evaluate(\"" + xpath + "\", document, null, 9, null).singleNodeValue).focusin();");4107 } catch (NullPointerException ex) {4108 try {4109 JavascriptExecutor js = (JavascriptExecutor) (driver);4110 js.executeScript(4111 "$(document.evaluate(\"" + xpath + "\", document, null, 9, null).singleNodeValue).focusin();");4112 } catch (Exception e) {4113 }4114 }4115 }4116 /**4117 * @author Cigniti4118 * @description: get current date and time4119 * @param format4120 * @return4121 */4122 public String getCurrentDateTime(String timeZOne, String format) {4123 SimpleDateFormat sdf = new SimpleDateFormat(format);4124 sdf.setTimeZone(TimeZone.getTimeZone(timeZOne));4125 Calendar c = Calendar.getInstance();4126 String fdate = sdf.format(c.getTime());4127 return fdate;4128 }4129 /**4130 * @author Cigniti4131 * @description: add no. of days from current date4132 * @param format4133 * @param AddNoOfDays4134 * @return4135 */4136 public String AddNoOfDaysInCurrentDate(String format, int AddNoOfDays) {4137 String Timezone = ConfigManager.getProperties().getProperty("usTimeZone".trim());4138 SimpleDateFormat sdf = new SimpleDateFormat(format);4139 sdf.setTimeZone(TimeZone.getTimeZone(Timezone));4140 Calendar c = Calendar.getInstance();4141 c.add(Calendar.DATE, AddNoOfDays);4142 String fdate = sdf.format(c.getTime());4143 return fdate;4144 }4145 /**4146 * @author Cigniti4147 * @description: change first character of string to Capital Letter4148 * @param str4149 * @return4150 */4151 public static String ChangeStringFirstCharToCapital(String str) {4152 StringBuilder b = new StringBuilder(str);4153 int i = 0;4154 do {4155 b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());4156 i = b.indexOf(" ", i) + 1;4157 } while (i > 0 && i < b.length());4158 return b.toString();4159 }4160 /**4161 * @author Cigniti4162 * @description: get first day of current week4163 * @param format4164 * @return4165 * @throws ParseException4166 */4167 public String getFirstDayOfCurrentWeek(String format) throws ParseException {4168 String fdate;4169 Calendar cal = Calendar.getInstance();4170 SimpleDateFormat sdf = new SimpleDateFormat(format);4171 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);4172 fdate = sdf.format(cal.getTime());4173 Date date1 = sdf.parse(fdate);4174 Date date = new Date();4175 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");4176 Date date2 = sdf2.parse(sdf2.format(date));4177 if (date1.after(date2)) {4178 Calendar cal1 = Calendar.getInstance();4179 SimpleDateFormat sdf1 = new SimpleDateFormat(format);4180 cal1.add(Calendar.DAY_OF_WEEK, -6);4181 fdate = sdf1.format(cal1.getTime());4182 }4183 return fdate;4184 }4185 /**4186 * @author Cigniti4187 * @description: get last day of current week4188 * @param format4189 * @return4190 */4191 public String getLastDayOfCurrentWeek(String format) {4192 String ldate;4193 Calendar cal = Calendar.getInstance();4194 SimpleDateFormat sdf = new SimpleDateFormat(format);4195 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);4196 cal.add(Calendar.DAY_OF_WEEK, 6);4197 ldate = sdf.format(cal.getTime());4198 return ldate;4199 }4200 /**4201 * @author Cigniti4202 * @description: get last day of current month in user's format4203 * @param format4204 * @return4205 */4206 public String getLastDayOfMonth(String format) {4207 Calendar cal = Calendar.getInstance();4208 SimpleDateFormat sdf = new SimpleDateFormat(format);4209 cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));4210 String ldate = sdf.format(cal.getTime());4211 return ldate;4212 }4213 /**4214 * '4215 * 4216 * @author Cigniti4217 * @description: get last day of current month and year4218 * @param month4219 * @param year4220 * @return4221 */4222 public String getLastDayOfMonth(int month, int year) {4223 Calendar calendar = Calendar.getInstance();4224 // passing month-1 because 0-->jan, 1-->feb... 11-->dec4225 calendar.set(year, month - 1, 1);4226 calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));4227 Date date = calendar.getTime();4228 DateFormat DATE_FORMAT = new SimpleDateFormat("dd");4229 SimpleDateFormat sdf = new SimpleDateFormat("dd");4230 sdf.format(date);4231 DATE_FORMAT.format(date);4232 return DATE_FORMAT.format(date);4233 }4234 /**4235 * @author Cigniti4236 * @description: get http url response code, RGV2UHJldmlldzpFcXVpbm94MSE=4237 * @param URL4238 * @return4239 */4240 public boolean GetResponseCode(String URL) {4241 boolean passflag = true;4242 try {4243 URL url = new URL(URL);4244 HttpURLConnection connection = (HttpURLConnection) url.openConnection();4245 connection.setRequestMethod("GET");4246 // connection.setDoInput(true);4247 // connection.setRequestProperty("Authorization", "Basic " + "");4248 connection.connect();4249 int code = connection.getResponseCode();4250 if (HttpURLConnection.HTTP_OK == code && code != 200) {4251 passflag = false;4252 }4253 } catch (Exception e) {4254 e.printStackTrace();4255 passflag = false;4256 }4257 return passflag;4258 }4259 /**4260 * @author Cigniti4261 * @description: get last sunday from current date/day in user's format4262 * @param format4263 * @return4264 */4265 public String getPreviousSunday(String format) {4266 SimpleDateFormat df = new SimpleDateFormat(format);4267 Calendar now = new GregorianCalendar();4268 Calendar start = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH),4269 now.get(Calendar.DAY_OF_MONTH));4270 while (start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {4271 start.add(Calendar.DAY_OF_WEEK, -1);4272 }4273 Calendar end = (Calendar) start.clone();4274 end.add(Calendar.DAY_OF_MONTH, 7);4275 return df.format(start.getTime());4276 }4277 /**4278 * @author Cigniti4279 * @description: get next sunday from current date/day in user's format4280 * @param format4281 * @return4282 */4283 public String getNextSunday(String format) {4284 SimpleDateFormat df = new SimpleDateFormat(format);4285 // DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL,4286 // DateFormat.FULL);4287 Calendar now = new GregorianCalendar();4288 Calendar start = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH),4289 now.get(Calendar.DAY_OF_MONTH));4290 while (start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {4291 start.add(Calendar.DAY_OF_WEEK, +1);4292 }4293 Calendar end = (Calendar) start.clone();4294 end.add(Calendar.DAY_OF_MONTH, 7);4295 return df.format(start.getTime());4296 }4297 /**4298 * @author Cigniti4299 * @description : get Date In Expected Format4300 * @param format4301 * @param dateInString4302 * @param returnformat4303 * @return4304 */4305 public String getDateInExpectedFormat(String format, String dateInString, String returnformat) {4306 SimpleDateFormat formatter = new SimpleDateFormat(format);4307 SimpleDateFormat returnFormatter = new SimpleDateFormat(returnformat);4308 Date date = null;4309 try {4310 date = formatter.parse(dateInString);4311 // formatter = new SimpleDateFormat(returnformat);4312 return returnFormatter.format(date);4313 } catch (ParseException e) {4314 e.printStackTrace();4315 return null;4316 }4317 }4318 /**4319 * @author Cigniti4320 * @description : Get Total Number of days in the Current Month4321 * @return4322 */4323 public int getTotalNoOfDayInMonth() {4324 try {4325 Calendar c = Calendar.getInstance();4326 int monthMaxDays = c.getActualMaximum(Calendar.DAY_OF_MONTH);4327 CurrentMonthDays = monthMaxDays;4328 } catch (Exception e) {4329 e.getMessage();4330 }4331 return CurrentMonthDays;4332 }4333 /**4334 * @author Cigniti4335 * @description : Swipe To Element Visible4336 * @param elementBy4337 * @return4338 */4339 public boolean ScrollToElementVisible(By elementBy) {4340 try {4341 WebElement elem = (new WebDriverWait(driver, 1))4342 .until(ExpectedConditions.presenceOfElementLocated(elementBy));4343 return ScrollToElementVisible(elem);4344 } catch (Exception ex) {4345 ex.getLocalizedMessage();4346 return false;4347 }4348 }4349 /**4350 * @author Cigniti4351 * @description : Scroll To Element Visible4352 * @param WebElement4353 * @return4354 */4355 public boolean ScrollToElementVisible(WebElement element) {4356 if (CommonVariables.PlatformName.get().equalsIgnoreCase("windows")) {4357 try {4358 ScrollToTop();4359 Point p = element.getLocation();4360 if (p.getX() == 0 && p.getY() == 0) {4361 return false;4362 } else {4363 ((JavascriptExecutor) EventFiringWebDriver)4364 .executeScript("window.scroll(" + p.getX() + "," + (p.getY() - 120) + ");");4365 try {4366 if (EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("internet")4367 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("ie")4368 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("edge")4369 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("safari")4370 || EventFiringWebDriver.getWrappedDriver().getClass().toString().toLowerCase().contains("opera")) {4371 Thread.sleep(800);4372 }4373 } catch (Exception e) {4374 }4375 return true;4376 }4377 } catch (Exception ex) {4378 throw ex;4379 }4380 } else {4381 try {4382 Dimension d = element.getSize();4383 if (d.height != 0 && d.width != 0) {4384 new Actions(EventFiringWebDriver.getWrappedDriver()).moveToElement(element).perform();4385 return true;4386 } else {4387 JavascriptExecutor js = (JavascriptExecutor) driver;4388 int height_covered = 0, pageHeightLeft = 0;4389 Long pageCurrentHeight = (Long) js.executeScript("return window.innerHeight");4390 ScrollToTop();4391 Long pageheight1 = (Long) js.executeScript("return window.innerHeight");4392 Long maxPageHeight1 = (Long) js.executeScript(4393 "return Math.max(document.documentElement.scrollHeight, document.body.scrollHeight,"4394 + "document.documentElement.clientHeight, window.innerHeight)");4395 float sections = (float) maxPageHeight1 / pageheight1;4396 int numberOfRows = (int) Math.ceil(sections);4397 int pageheight = pageheight1.intValue();4398 int maxPageHeight = maxPageHeight1.intValue();4399 for (int row = 0; row < numberOfRows; row++) {4400 pageHeightLeft = maxPageHeight - height_covered;4401 if ((pageHeightLeft < pageheight)) {4402 d = element.getSize();4403 if (d.height == 0 && d.width == 0) {4404 js.executeScript("window.scrollTo(0," + pageCurrentHeight + ")");4405 return false;4406 } else {4407 new Actions(EventFiringWebDriver.getWrappedDriver()).moveToElement(element).perform();4408 return true;4409 }4410 } else {4411 d = element.getSize();4412 if (!(d.height != 0 && d.width != 0)) {4413 height_covered = height_covered + pageheight;4414 js.executeScript("window.scrollTo(0," + height_covered + ")");4415 try {4416 Thread.sleep(100);4417 } catch (InterruptedException e) {4418 }4419 } else {4420 new Actions(EventFiringWebDriver.getWrappedDriver()).moveToElement(element).perform();4421 return true;4422 }4423 }4424 }4425 ScrollToTop();4426 return false;4427 }4428 } catch (org.openqa.selenium.ElementNotVisibleException e) {4429 throw new ElementNotVisibleException("");4430 } catch (Exception ex) {4431 throw ex;4432 }4433 }4434 }4435 /**4436 * @author Cigniti4437 * @description : Mouse Over4438 * @param webelement4439 */4440 public void Mouseover(WebElement webelement) {4441 try {4442 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4443 js.executeScript("$(arguments[0]).trigger('mouseover');", webelement);4444 } catch (Exception e) {4445 e.getLocalizedMessage();4446 }4447 }4448 public String GetXpathFromBy(By by) {4449 try {4450 return by.toString().split("By.xpath: ")[1].trim();4451 } catch (Exception e) {4452 return "";4453 }4454 }4455 /**4456 * @author Cigniti4457 * @description : Is Element Display In Current View4458 * @param xpath4459 * @return4460 */4461 4462 public boolean verifyElementDisplayed(By by, String elementName) throws Throwable{4463 boolean displayFlag = false;4464 try {4465 if(IsElementDisplayInCurrentView(by)){4466 displayFlag = true;4467 extentLogs.pass("Verify Element is displayed","<b>" + elementName + "</b>" + " is displayed");4468 }else{4469 4470 extentLogs.fail("Verify Element is displayed","<b>" + elementName + "</b>" + " is NOT displayed");4471 }4472 }4473 catch (Exception e) {4474 e.printStackTrace();4475 }4476 return displayFlag;4477 4478 }4479 4480 /**4481 * @author Cigniti4482 * @description : Is Element Display In Current View4483 * @param xpath4484 * @return4485 */4486 public boolean IsElementDisplayInCurrentView(By xpath) {4487 try {4488 return IsElementDisplayInCurrentView(driver.findElement(xpath));4489 } catch (Exception ex) {4490 return false;4491 }4492 }4493 /**4494 * @author Cigniti4495 * @description: verify visibility of an element in current open view in UI4496 * @param webElement4497 * @return4498 */4499 public boolean IsElementDisplayInCurrentView(WebElement webElement) {4500 double browser_top_offset = 0.0;4501 try {4502 JavascriptExecutor js = (JavascriptExecutor) driver;4503 Long pageheight = (Long) js.executeScript("return $(window).height()");4504 double elemPos = 0;4505 try {4506 Long posY = (Long) js.executeScript("return $(arguments[0]).offset().top - $(window).scrollTop()",4507 webElement);4508 elemPos = posY.doubleValue();4509 } catch (ClassCastException cc) {4510 elemPos = (Double) js.executeScript("return $(arguments[0]).offset().top - $(window).scrollTop()",4511 webElement);4512 }4513 double pageheight1 = pageheight.doubleValue();4514 if (elemPos >= browser_top_offset && elemPos < pageheight1)4515 return true;4516 else4517 return false;4518 } catch (Exception ex) {4519 System.out.println("" + ex.getMessage());4520 return false;4521 }4522 }4523 /**4524 * @author Cigniti4525 * @description : Calculate Age4526 * @param year4527 * @param month4528 * @param day4529 * @return4530 */4531 public int calculateAge(int year, int month, int day) // Enter Date of Birth4532 // //4533 {4534 try {4535 LocalDate birthdate = new LocalDate(year, month, day);4536 LocalDate now = new LocalDate();4537 Years ageInYear = Years.yearsBetween(birthdate, now);4538 return ageInYear.getYears();4539 } catch (Exception ex) {4540 throw ex;4541 }4542 }4543 /**4544 * @author Cigniti4545 * @param dob4546 * 1986-10-31, 1955-30-124547 * @param format4548 * - yyyy-mm-dd , yyyy-dd-mm4549 * @return Age as a integer4550 */4551 @SuppressWarnings("deprecation")4552 public int calculateAge(String dob, String format) throws Exception// Enter4553 // Date4554 // od4555 // Birth4556 // //4557 {4558 try {4559 Date dob_DateObj = getDateTimeFromProvidedString(dob, format);4560 long ageInMillis = new Date().getTime() - dob_DateObj.getTime();4561 return new Date(ageInMillis).getYear();4562 } catch (IllegalArgumentException ex) {4563 extentLogs.info("calculate Age",4564 "Failed to get Age from provided format (" + format + ") and date value (" + dob + ")");4565 throw ex;4566 } catch (NullPointerException ex) {4567 extentLogs.info("calculate Age",4568 "Failed to get Age from provided format (" + format + ") and dob value (" + dob + ")");4569 throw ex;4570 }4571 }4572 /**4573 * @author Cigniti4574 * @param url4575 * @param userAgent4576 * @return4577 */4578 public Map<String, String> getHTTPResponseCodeAndSize(String url, String userAgent) {4579 Map<String, String> httpResponseMetaData = new HashMap<String, String>();4580 try {4581 URL obj = new URL(url);4582 HttpURLConnection con = (HttpURLConnection) obj.openConnection();4583 con.setRequestMethod("GET");4584 con.setRequestProperty("User-Agent", userAgent);4585 httpResponseMetaData.put("code", String.valueOf(con.getResponseCode()));4586 httpResponseMetaData.put("size", String.valueOf(con.getContentLength()));4587 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));4588 String inputLine;4589 StringBuffer response = new StringBuffer();4590 while ((inputLine = in.readLine()) != null) {4591 response.append(inputLine);4592 }4593 in.close();4594 httpResponseMetaData.put("content", response.toString());4595 return httpResponseMetaData;4596 } catch (Exception e) {4597 httpResponseMetaData.put("code", "500");4598 httpResponseMetaData.put("size", "0");4599 httpResponseMetaData.put("content", e.getMessage());4600 return httpResponseMetaData;4601 }4602 }4603 /**4604 * @author Cigniti4605 * @description : get cookies4606 * @return4607 */4608 public String[] getcookies() {4609 String[] stringArray = null;4610 try {4611 Set<Cookie> cookie = CommonVariables.CommonDriver.get().manage().getCookies();4612 Object[] cookie_text = cookie.toArray();4613 stringArray = new String[cookie_text.length];4614 for (int i = 0; i < cookie_text.length; i++) {4615 stringArray[i] = cookie_text[i].toString();4616 }4617 } catch (Exception e) {4618 System.out.println("Not able to get cookies for the selected page due to error message :" + e.getMessage());4619 }4620 return stringArray;4621 }4622 /**4623 * @param upper4624 * upper limit4625 * @param lower4626 * lower limit4627 * @return4628 */4629 public Integer getRandomNumberBetween(Integer upper, Integer lower) {4630 return (int) ((Math.random() * (upper - lower)) + lower);4631 }4632 public void setDownloadPathForFile(String downloadpath) {4633 try {4634 String downloadFilepath = downloadpath;4635 File fl = new File(downloadFilepath);4636 if (!fl.exists()) {4637 fl.mkdir();4638 }4639 Map<String, Object> prefs = new HashMap<String, Object>();4640 prefs.put("profile.default_content_settings.popups", 0);4641 prefs.put("download.default_directory", downloadFilepath);4642 prefs.put("savefile.default_directory", downloadFilepath);4643 chromeoptions.setExperimentalOption("prefs", prefs);4644 } catch (Exception e) {4645 e.getMessage();4646 }4647 }4648 /**4649 * @author Cigniti4650 * @description: hightlight WebElement4651 * @param elem4652 * @param durationInSeconds4653 */4654 public void HighlightWebElement(WebElement elem, int durationInSeconds) {4655 try {4656 durationInSeconds = durationInSeconds * 1000;4657 String original_style = elem.getAttribute("style");4658 ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute(arguments[1], arguments[2])", elem,4659 "style", "border: 2px solid red; border-style: dashed;");4660 if (durationInSeconds > 0) {4661 Thread.sleep(durationInSeconds);4662 ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute(arguments[1], arguments[2])",4663 elem, "style", original_style);4664 }4665 } catch (Exception e) {4666 }4667 }4668 /**4669 * @author Cigniti4670 * @description : Switch In to iFrame4671 * @param iFrameID4672 * @return4673 */4674 public boolean SwitchIntoFrame(WebElement iFrameID) {4675 try {4676 driver.switchTo().frame(iFrameID);4677 System.out.println("switch to frame sucessfully.");4678 return true;4679 } catch (Exception e) {4680 System.out.println("Failed to switch to frame due to error :" + e.getMessage());4681 return false;4682 }4683 }4684 /**4685 * @author Cigniti4686 * @return4687 */4688 public WebDriver SwitchOutfromFrame() {4689 return driver.switchTo().defaultContent();4690 }4691 /**4692 * @author Cigniti4693 * @description : get Current Month4694 * @return4695 */4696 public String getCurrentMonth() {4697 String CurrentMonth = "";4698 try {4699 SimpleDateFormat sdf = new SimpleDateFormat("MMMM");4700 Calendar cal = Calendar.getInstance();4701 CurrentMonth = sdf.format(cal.getTime());4702 System.out.println("Current Month :" + CurrentMonth);4703 } catch (Exception e) {4704 e.getStackTrace();4705 }4706 return CurrentMonth;4707 }4708 /**4709 * @author Cigniti4710 * @description : get Next Month4711 * @return4712 */4713 public String getNextMonth() {4714 String NextMonth = "";4715 try {4716 SimpleDateFormat sdf = new SimpleDateFormat("MMMM");4717 Calendar cal = Calendar.getInstance();4718 cal.add(Calendar.MONTH, 1);4719 cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));4720 NextMonth = sdf.format(cal.getTime());4721 System.out.println("Next Month :" + NextMonth);4722 } catch (Exception e) {4723 e.getStackTrace();4724 }4725 return NextMonth;4726 }4727 /**4728 * @author Cigniti4729 * @param file4730 * @return4731 */4732 public Boolean deleteFile(File file) {4733 try {4734 if (file.isDirectory()) {4735 String fileList[] = file.list();4736 if (fileList.length == 0) {4737 extentLogs.info("Delete File", "Deleting Directory : " + file.getPath());4738 file.delete();4739 extentLogs.info("Delete File", "Deleted Directory : " + file.getPath());4740 } else {4741 int size = fileList.length;4742 for (int i = 0; i < size; i++) {4743 String fileName = fileList[i];4744 extentLogs.info("Delete File", "File path : " + file.getPath() + " and name :" + fileName);4745 String fullPath = file.getPath() + "/" + fileName;4746 File fileOrFolder = new File(fullPath);4747 extentLogs.info("Delete File", "File copied, full path is: " + fileOrFolder.getPath());4748 deleteFile(fileOrFolder);4749 }4750 }4751 return true;4752 } else {4753 extentLogs.info("Delete File", "Deleting file : " + file.getPath());4754 file.delete();4755 extentLogs.info("Delete File", "Deleted file : " + file.getPath());4756 return true;4757 }4758 } catch (Exception e) {4759 extentLogs.error("Delete File", "Deleted file : " + file.getPath());4760 return false;4761 }4762 }4763 /**4764 * @description: Verify the presence of a file at a particular location.4765 * File name is not case sensitive and can provide4766 * complete/partial name of the file.4767 * @param path4768 * - Complete Path of the folder which suppose to contain file4769 * @param fileName4770 * - Name of the file. It'll compare case4771 * @return True, if file found.4772 */4773 public Boolean verifyPresenceOfFileOrFolderAtLocation(String path, String fileName) {4774 try {4775 File file = new File(path);4776 File[] listOfFiles = file.listFiles();4777 if (listOfFiles.length != 0) {4778 for (int i = 0; i < listOfFiles.length; i++) {4779 if (listOfFiles[i].getName().toLowerCase().contains(fileName.toLowerCase())) {4780 return true;4781 }4782 }4783 }4784 return false;4785 } catch (Exception e) {4786 return false;4787 }4788 }4789 /**4790 * <b>Description:</b> Copies the entire src File to Dest4791 * 4792 * @param src4793 * @param dest4794 * @throws Exception4795 */4796 public void copyFile(File src, File dest) throws Exception {4797 if (src.isDirectory()) {4798 if (!dest.exists()) {4799 dest.mkdir();4800 System.out.println("Directory copied from " + src + " to " + dest);4801 }4802 String files[] = src.list();4803 for (String file : files) {4804 File srcFile = new File(src, file);4805 File destFile = new File(dest, file);4806 copyFile(srcFile, destFile);4807 }4808 } else {4809 InputStream in = new FileInputStream(src);4810 OutputStream out = new FileOutputStream(dest);4811 byte[] buffer = new byte[1024];4812 int length;4813 while ((length = in.read(buffer)) > 0) {4814 out.write(buffer, 0, length);4815 }4816 in.close();4817 out.close();4818 System.out.println("File copied from " + src + " to " + dest);4819 }4820 }4821 /**4822 * <b>Description:</b> Copies the entire src File to Dest4823 * 4824 * @param src4825 * @param dest4826 * @throws Exception4827 */4828 public static void staticCopyFile(File src, File dest) throws Exception {4829 if (src.isDirectory()) {4830 if (!dest.exists()) {4831 dest.mkdir();4832 System.out.println("Directory copied from " + src + " to " + dest);4833 }4834 String files[] = src.list();4835 for (String file : files) {4836 File srcFile = new File(src, file);4837 File destFile = new File(dest, file);4838 staticCopyFile(srcFile, destFile);4839 }4840 } else {4841 InputStream in = new FileInputStream(src);4842 OutputStream out = new FileOutputStream(dest);4843 byte[] buffer = new byte[1024];4844 int length;4845 while ((length = in.read(buffer)) > 0) {4846 out.write(buffer, 0, length);4847 }4848 in.close();4849 out.close();4850 }4851 }4852 /**4853 * @author Cigniti4854 * @param startTime4855 * - Start Time as a Date class object4856 * @param endTime4857 * - End Time as a Date class object4858 */4859 public long getTimeDifferenceInMin(Date startTime, Date endTime) {4860 long ageInMillis = endTime.getTime() - startTime.getTime();4861 return ageInMillis / (1000 * 60);4862 }4863 /**4864 * @author Cigniti4865 * @description: get IP of selenium grid 'node'4866 * @param remotewebdriver4867 * @return4868 */4869 public String GetIPOfSeleniumGridNode(WebDriver remotewebdriver) {4870 String hostFound = null;4871 try {4872 HttpCommandExecutor commandexecutor = (HttpCommandExecutor) ((RemoteWebDriver) remotewebdriver)4873 .getCommandExecutor();4874 String hostName = commandexecutor.getAddressOfRemoteServer().getHost();4875 int port = commandexecutor.getAddressOfRemoteServer().getPort();4876 HttpHost host = new HttpHost(hostName, port);4877 @SuppressWarnings("deprecation")4878 DefaultHttpClient client = new DefaultHttpClient();4879 URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session="4880 + ((RemoteWebDriver) remotewebdriver).getSessionId());4881 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",4882 sessionURL.toExternalForm());4883 HttpResponse response = client.execute(host, r);4884 JSONObject object = extractObject(response);4885 URL myURL = new URL(object.getString("proxyId"));4886 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {4887 hostFound = myURL.getHost();4888 }4889 } catch (Exception e) {4890 e.printStackTrace();4891 }4892 return hostFound;4893 }4894 /**4895 * @author Cigniti4896 * @param resp4897 * @return4898 * @throws IOException4899 * @throws JSONException4900 */4901 private static JSONObject extractObject(HttpResponse resp) throws IOException, JSONException {4902 InputStream contents = resp.getEntity().getContent();4903 StringWriter writer = new StringWriter();4904 IOUtils.copy(contents, writer, "UTF8");4905 JSONObject objToReturn = new JSONObject(writer.toString());4906 return objToReturn;4907 }4908 /**4909 * @author Cigniti4910 * @description: WebElement click4911 * @param webElement4912 * @param time4913 * @return4914 */4915 public boolean javascriptClick(WebElement webElement, long time) {4916 boolean state = false;4917 try {4918 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4919 js.executeScript("arguments[0].click();", webElement);4920 Thread.sleep(time);4921 state = true;4922 return true;4923 } catch (NullPointerException ex) {4924 return false;4925 } catch (Exception e) {4926 try {4927 if (ScrollToElementVisible(By.xpath(getElementXPath(webElement)))) {4928 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4929 js.executeScript("$(arguments[0]).click();", webElement);4930 Thread.sleep(time);4931 state = true;4932 return true;4933 } else {4934 return false;4935 }4936 } catch (Exception ex) {4937 }4938 if (!state) {4939 try {4940 JavascriptExecutor js = (JavascriptExecutor) (CommonVariables.CommonDriver.get());4941 js.executeScript("$(arguments[0]).focusin();", webElement);4942 Thread.sleep(time);4943 state = true;4944 }4945 catch (Exception e1) {4946 state = false;4947 }4948 }4949 }4950 return state;4951 }4952 /**4953 * @author Cigniti4954 * @description : get Last Month4955 * @return4956 */4957 public String getLastMonth() {4958 String LastMonth = "";4959 try {4960 SimpleDateFormat sdf = new SimpleDateFormat("MMMM");4961 Calendar cal = Calendar.getInstance();4962 cal.add(Calendar.MONTH, -1);4963 cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));4964 LastMonth = sdf.format(cal.getTime());4965 System.out.println("Next Month :" + LastMonth);4966 } catch (Exception e) {4967 e.getStackTrace();4968 }4969 return LastMonth;4970 }4971 /**4972 * @author Cigniti4973 * @description: get alert4974 * @return4975 */4976 public String getAlertText() {4977 try {4978 Alert alert = driver.switchTo().alert();4979 return alert.getText();4980 } catch (Exception e) {4981 return null;4982 }4983 }4984 /**4985 * @author Cigniti4986 * @param remotewebdriver4987 * @return4988 */4989 public String getIPOfSeleniumGridNode(RemoteWebDriver remotewebdriver) {4990 String hostFound = null;4991 try {4992 HttpCommandExecutor commandexecutor = (HttpCommandExecutor) remotewebdriver.getCommandExecutor();4993 String hostName = commandexecutor.getAddressOfRemoteServer().getHost();4994 int port = commandexecutor.getAddressOfRemoteServer().getPort();4995 HttpHost host = new HttpHost(hostName, port);4996 @SuppressWarnings("deprecation")4997 DefaultHttpClient client = new DefaultHttpClient();4998 URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session="4999 + remotewebdriver.getSessionId());5000 BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",5001 sessionURL.toExternalForm());5002 HttpResponse response = client.execute(host, r);5003 JSONObject object = extractObject(response);5004 URL myURL = new URL(object.getString("proxyId"));5005 if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {5006 hostFound = myURL.getHost();5007 }5008 } catch (Exception e) {5009 e.printStackTrace();5010 }5011 return hostFound;5012 }5013 /**5014 * @return Clipboard text5015 * @throws UnsupportedFlavorException5016 * @throws IOException5017 */5018 public String getTextFromClipboard() throws UnsupportedFlavorException, IOException {5019 Toolkit toolkit = Toolkit.getDefaultToolkit();5020 Clipboard clipboard = toolkit.getSystemClipboard();5021 return (String) clipboard.getData(DataFlavor.stringFlavor);5022 }5023 /**5024 * @author Cigniti5025 * @description: kill unwanted pop in web5026 */5027 public void killPopup(String textInURL) {5028 try {5029 String windowHandle = EventFiringWebDriver.getWindowHandle();5030 for (String window : EventFiringWebDriver.getWindowHandles()) {5031 WebDriver temp = EventFiringWebDriver.switchTo().window(window);5032 if (temp.getCurrentUrl().toLowerCase().contains(textInURL)) {5033 temp.close();5034 }5035 }5036 EventFiringWebDriver.switchTo().window(windowHandle);5037 } catch (Exception e) {5038 }5039 }5040 /**5041 * @author Cigniti5042 * @description: switch to iframe5043 * @param frame_element5044 * @return5045 */5046 public static WebDriver SwitchToiFrame(WebElement frame_element) {5047 CommonVariables.getDriver().switchTo().frame(frame_element);5048 CommonVariables.setDriver((EventFiringWebDriver) CommonVariables.getDriver());5049 return CommonVariables.getDriver();5050 }5051 /**5052 * @author Cigniti5053 * @description: switch back to default content from iframe5054 * @return5055 */5056 public static WebDriver SwitchBackFromiFrameToMaincontent() {5057 CommonVariables.getDriver().switchTo().defaultContent();5058 CommonVariables.setDriver((EventFiringWebDriver) CommonVariables.getDriver());5059 return CommonVariables.getDriver();5060 }5061 /**5062 * @author Cigniti5063 * @description: get current time zone5064 * @return5065 */5066 public static String getCurrentTimeZone() {5067 String timeZone = null;5068 // get Calendar instance5069 Calendar now = Calendar.getInstance();5070 // get current TimeZone using getTimeZone method of Calendar class5071 TimeZone tZone = now.getTimeZone();5072 // display current TimeZone using getDisplayName() method of TimeZone5073 // class5074 timeZone = tZone.getDisplayName();5075 return timeZone;5076 }5077 /**5078 * @author Cigniti5079 * @description: Robot class should be use only when keyboard inputs are5080 * required and all other Options like, ACtion Class,5081 * Webdriver Send Keys.. are not working.5082 * @return5083 * @throws AWTException5084 */5085 public Robot roboticMethod() throws AWTException {5086 Robot robot = new Robot();5087 return robot;5088 }5089 /**5090 * @author Cigniti5091 * @description: Maximum '6' times user can use tab click through robotium.5092 * @param numberofClick5093 * @throws AWTException5094 */5095 public void roboticTabClick(int numberofClick) throws AWTException {5096 switch (numberofClick) {5097 case 1:5098 roboticMethod().keyPress(KeyEvent.VK_TAB);5099 break;5100 case 2:5101 roboticMethod().keyPress(KeyEvent.VK_TAB);5102 roboticMethod().keyPress(KeyEvent.VK_TAB);5103 break;5104 case 3:5105 roboticMethod().keyPress(KeyEvent.VK_TAB);5106 roboticMethod().keyPress(KeyEvent.VK_TAB);5107 roboticMethod().keyPress(KeyEvent.VK_TAB);5108 break;5109 case 4:5110 roboticMethod().keyPress(KeyEvent.VK_TAB);5111 roboticMethod().keyPress(KeyEvent.VK_TAB);5112 roboticMethod().keyPress(KeyEvent.VK_TAB);5113 roboticMethod().keyPress(KeyEvent.VK_TAB);5114 break;5115 case 5:5116 roboticMethod().keyPress(KeyEvent.VK_TAB);5117 roboticMethod().keyPress(KeyEvent.VK_TAB);5118 roboticMethod().keyPress(KeyEvent.VK_TAB);5119 roboticMethod().keyPress(KeyEvent.VK_TAB);5120 roboticMethod().keyPress(KeyEvent.VK_TAB);5121 break;5122 case 6:5123 roboticMethod().keyPress(KeyEvent.VK_TAB);5124 roboticMethod().keyPress(KeyEvent.VK_TAB);5125 roboticMethod().keyPress(KeyEvent.VK_TAB);5126 roboticMethod().keyPress(KeyEvent.VK_TAB);5127 roboticMethod().keyPress(KeyEvent.VK_TAB);5128 roboticMethod().keyPress(KeyEvent.VK_TAB);5129 break;5130 default:5131 System.out.println("Tab not clicked.");5132 break;5133 }5134 }5135 /**5136 * @author Cigniti5137 * @return5138 */5139 public static Action actionMethod() {5140 Action action = (Action) new Actions(CommonVariables.CommonDriver.get());5141 return action;5142 }5143 public String GetCurrentTime() {5144 DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss a");5145 String currenttime = df.format(Calendar.getInstance().getTime());5146 return currenttime;5147 }5148 /**5149 * @author Cigniti5150 * @param filename5151 */5152 public void fileSeparator(String filename) {5153 try {5154 String workingDirectory = System.getProperty("user.dir").replace("\\", "/");5155 String absoluteFilePath = "";5156 String osname = System.getProperty("os.name");5157 String fileSeparator = File.separator;5158 if (osname.contains("windows")) {5159 fileSeparator = "/";5160 } else {5161 if (osname.contains("linux") || osname.contains("Unix") || osname.contains("Mac")) {5162 fileSeparator = "/";5163 }5164 }5165 absoluteFilePath = workingDirectory + fileSeparator + filename;5166 System.out.println("Final filepath : " + absoluteFilePath);5167 } catch (Exception e) {5168 e.printStackTrace();5169 }5170 }5171 /**5172 * @author Cigniti5173 * @param workbookName5174 * @throws IOException5175 */5176 public void DeleteFiles(String workbookName) throws IOException {5177 try {5178 System.out.println("Called deleteFiles");5179 File file = new File(System.getProperty("user.dir") + "\\TestData\\" + workbookName);5180 String[] myFiles;5181 if (file.isDirectory()) {5182 myFiles = file.list();5183 for (int i = 0; i < myFiles.length; i++) {5184 File myFile = new File(file, myFiles[i]);5185 System.out.println(myFile);5186 myFile.delete();5187 }5188 }5189 } catch (Exception e) {5190 System.out.println(e.getMessage());5191 }5192 }5193 /**5194 * @author Cigniti5195 * @param waitTime5196 * @param pollingCycle5197 */5198 @SuppressWarnings({ "rawtypes", "unchecked" })5199 public void fluentWait(int waitTime, int pollingCycle) {5200 try {5201 FluentWait wait = new FluentWait(this.driver);5202 wait.withTimeout(waitTime, TimeUnit.SECONDS);5203 wait.pollingEvery(pollingCycle, TimeUnit.SECONDS);5204 wait.ignoring(NoSuchElementException.class);5205 } catch (Exception e) {5206 System.out.println("unable to perform an action for fluent wait due to execption - " + e.getMessage());5207 }5208 }5209 /**5210 * Wrap the Selenium run time exception with more debug info.5211 */5212 protected String makeSeleniumExceptionMessage(Page page, Throwable e) {5213 String result = "SeleniumException found on page " + page.getClass();5214 String fullMessage = e.getMessage();5215 return result + "\n" + fullMessage.substring(0, fullMessage.indexOf("\n"));5216 }5217 /**5218 * @author Cigniti5219 * @param folderPath5220 * @return5221 */5222 public static File[] getFiles(String folderPath) {5223 File arrayFiles[] = null;5224 List<File> listFiles = new ArrayList<File>();5225 traverseFolder(new File(folderPath), listFiles);5226 // get the size of listFiles to initialize the size of array5227 arrayFiles = new File[listFiles.size()];5228 arrayFiles = listFiles.toArray(arrayFiles);5229 return arrayFiles;5230 }5231 /**5232 * @author Cigniti5233 * @param file5234 * @param listFiles5235 */5236 private static void traverseFolder(File file, List<File> listFiles) {5237 // if current file is folder, look for files inside it.5238 if (file.isDirectory()) {5239 File[] files = file.listFiles();5240 for (File aFile : files) {5241 // recursive call5242 traverseFolder(aFile, listFiles);5243 }5244 } else // add the file to list5245 {5246 listFiles.add(file);5247 }5248 }5249 /**5250 * @author Cigniti readTextFile5251 * @param filePath5252 */5253 public List<String> readTextFile(String filePath) {5254 List<String> list = new ArrayList<String>();5255 String line = null;5256 try {5257 FileReader reader = new FileReader(filePath);5258 BufferedReader bufferedReader = new BufferedReader(reader);5259 while ((line = bufferedReader.readLine()) != null) {5260 list.add(line);5261 }5262 reader.close();5263 } catch (IOException e) {5264 e.printStackTrace();5265 }5266 return list;5267 }5268 /**5269 * Robot mouse over.5270 * 5271 * @author Cigniti5272 * @param by5273 * the by5274 * @throws Exception5275 * the exception5276 */5277 public void robotMouseOver(By by) throws Exception {5278 try {5279 Point point = this.driver.findElement(by).getLocation();5280 int xcord = point.getX();5281 int ycord = point.getY();5282 Robot robot = new Robot();5283 robot.mouseMove(xcord + 30, ycord + 100); // move mouse point to5284 // specific location5285 robot.delay(1500); // delay is to make code wait for mentioned5286 // milliseconds before executing next step5287 /*5288 * robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); // press left5289 * click robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); //5290 * release left click robot.delay(1500);5291 * robot.keyPress(KeyEvent.VK_DOWN); // press keyboard arrow key to5292 * select Save radio button Thread.sleep(2000);5293 * robot.keyPress(KeyEvent.VK_ENTER); Thread.sleep(3000);5294 */5295 } catch (Exception e) {5296 throw e;5297 }5298 }5299 /**5300 * Wait for text.5301 *5302 * @param by5303 * the by5304 * @param locator5305 * the locator5306 * @param secs5307 * the secs5308 * @return true, if successful5309 * @throws Throwable5310 * the throwable5311 */5312 public boolean waitForText(By by, String locator, int secs) throws Throwable {5313 boolean status = false;5314 try {5315 WebDriverWait wait = new WebDriverWait(this.driver, 60);5316 ScrollToElementVisible(by);5317 wait.until(ExpectedConditions.textToBePresentInElementLocated(by, locator));5318 for (int i = 0; i < secs / 2; i++) {5319 List<WebElement> elements = this.driver.findElements(by);5320 if (elements.size() > 0) {5321 status = true;5322 return status;5323 } else {5324 this.driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);5325 }5326 }5327 } catch (Exception e) {5328 return status;5329 }5330 return status;5331 }5332 /**5333 * Close all other windows.5334 * 5335 * @author Cigniti5336 * @param driver5337 * the driver5338 * @param openWindowHandle5339 * the open window handle5340 * @return true, if successful5341 */5342 public static boolean closeAllOtherWindows(WebDriver driver, String openWindowHandle) {5343 Set<String> allWindowHandles = EventFiringWebDriver.getWindowHandles();5344 for (String currentWindowHandle : allWindowHandles) {5345 if (!currentWindowHandle.equals(openWindowHandle)) {5346 EventFiringWebDriver.switchTo().window(currentWindowHandle);5347 EventFiringWebDriver.close();5348 }5349 }5350 EventFiringWebDriver.switchTo().window(openWindowHandle);5351 if (EventFiringWebDriver.getWindowHandles().size() == 1)5352 return true;5353 else5354 return false;5355 }5356 /**5357 * Select value from drop down for edge browser5358 * 5359 * @param elementBy5360 * @param selectionValue5361 */5362 public void selectListValueEdge(By elementBy, String selectionValue) {5363 try {5364 WebElement webElement = this.EventFiringWebDriver.findElement(elementBy);5365 webElement.click();5366 webElement.sendKeys(selectionValue);5367 webElement.sendKeys(Keys.ENTER);5368 } catch (Exception ex) {5369 ex.printStackTrace();5370 }5371 }5372 /**5373 * @author Cigniti Browse and upload.5374 * @param filePath5375 * the file path5376 * @param locator5377 * the locator5378 * @param locatorName5379 * the locator name5380 * @return true, if successful5381 * @throws Throwable5382 * the throwable5383 */5384 public boolean browseAndUpload(String filePath, WebElement webElement) throws Throwable {5385 boolean flag = false;5386 try {5387 Click(webElement);5388 Thread.sleep(4000);5389 // Copy the file's absolute path to the clipboard5390 StringSelection ss = new StringSelection(filePath);5391 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);5392 // native key strokes for CTRL, V and ENTER keys5393 Robot robot = new Robot();5394 Thread.sleep(2000);5395 robot.keyPress(KeyEvent.VK_CONTROL);5396 Thread.sleep(2000);5397 robot.keyPress(KeyEvent.VK_V);5398 Thread.sleep(2000);5399 robot.keyRelease(KeyEvent.VK_V);5400 Thread.sleep(2000);5401 robot.keyRelease(KeyEvent.VK_CONTROL);5402 Thread.sleep(2000);5403 robot.keyPress(KeyEvent.VK_ENTER);5404 Thread.sleep(2000);5405 robot.keyRelease(KeyEvent.VK_ENTER);5406 Thread.sleep(2000);5407 flag = true;5408 } catch (NoAlertPresentException ex) {5409 ex.printStackTrace();5410 }5411 return flag;5412 }5413 /**5414 * @author Cigniti5415 * @param filePath5416 * @param element5417 * @param time5418 * @param locatorName5419 * @return5420 * @throws Throwable5421 */5422 public boolean uploadFile(String filePath, WebElement element, int time, String locatorName) throws Throwable {5423 boolean flag = false;5424 try {5425 WebDriverWait wait = new WebDriverWait(this.driver, 60);5426 ScrollToElementVisible(element);5427 wait.until(ExpectedConditions.elementToBeClickable(element));5428 Click(element, time);5429 Thread.sleep(5000);5430 Actions KeyboardEvent = new Actions(this.driver);5431 KeyboardEvent.sendKeys(filePath);5432 Thread.sleep(1000);5433 KeyboardEvent.sendKeys(Keys.ENTER);5434 flag = true;5435 } catch (NoAlertPresentException ex) {5436 ex.printStackTrace();5437 flag = false;5438 }5439 return flag;5440 }5441 /**5442 * @author Cigniti5443 */5444 public void ScrollToTop(WebDriver driver) {5445 try {5446 JavascriptExecutor js = (JavascriptExecutor) driver;5447 js.executeScript("window.scrollBy(0,-1000)", "");5448 } catch (Exception e) {5449 e.printStackTrace();5450 }5451 }5452 /**5453 * @author Cigniti5454 * @param element5455 */5456 public void SwipeRight(WebElement element) {5457 // Executing swipe on in the case of iOS simulators. Skipping it for5458 // Android Chrome as this swipe will not yet implemented on it.5459 try {5460 String driverName = GetDriverInfo().get("DriverName").toLowerCase();5461 if ((!driverName.equals("android-chrome")) && (!driverName.equals("chrome"))5462 && (!driverName.equals("chrome-mac")) && (!driverName.equals("safari"))5463 && (!driverName.equals("firefox")) && (!driverName.equals("ie")) && (!driverName.equals("edge"))5464 && (!driverName.equals("opera"))) {5465 double browser_top_offset = 0.0;5466 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("mobile")) {5467 browser_top_offset = 0;5468 } else if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("tablet")) {5469 browser_top_offset = 80;5470 }5471 /*5472 * if(ConfigManager.getProperties().getProperty("seleniumGrid").5473 * trim().equalsIgnoreCase("true")5474 * ||GetDriverInfo().get("DriverType").trim().equalsIgnoreCase(5475 * "mobile")5476 * ||GetDriverInfo().get("DriverType").trim().equalsIgnoreCase(5477 * "tablet")){ }5478 */5479 // RemoteWebElement remoteelem = ((RemoteWebElement)element);5480 WebElement remoteelem = element;5481 JavascriptExecutor js = (JavascriptExecutor) driver;5482 String script = "return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)";5483 Long pageheight1 = (Long) js.executeScript(script);5484 Long pagewidth1 = (Long) js5485 .executeScript("return Math.max(document.documentElement.clientWidth, window.innerWidth || 0)");5486 // Long pageheight2=(Long)js.executeScript("return5487 // window.innerHeight");5488 Point eloc = remoteelem.getLocation();5489 double yloc = eloc.getY();5490 double xstartloc = eloc.getX();5491 double xendloc = eloc.getX() + remoteelem.getSize().width;5492 Double swipe_startxratio = xstartloc / pagewidth1;5493 Double swipe_endxratio = xendloc / pagewidth1;5494 double elemheight = remoteelem.getSize().getHeight() / 2;5495 Double yratio = (yloc + elemheight / 2 + browser_top_offset) / pageheight1;5496 if (swipe_startxratio < 0.1) {5497 swipe_startxratio = 0.1;5498 }5499 if (swipe_endxratio > 0.9) {5500 swipe_endxratio = 0.9;5501 }5502 /*5503 * HashMap<String, Double> swipeObject = new HashMap<String,5504 * Double>(); swipeObject.put("startX", swipe_endxratio);5505 * swipeObject.put("startY", yratio); swipeObject.put("endX",5506 * swipe_startxratio); swipeObject.put("endY", yratio);5507 * swipeObject.put("duration", 0.8); // js.executeScript(5508 * "mobile: swipe", swipeObject); appiumDriver.execute(5509 * "mobile: swipe", swipeObject);5510 */5511 if (driver != null) {5512 driver.swipe(swipe_endxratio.intValue(), yratio.intValue(), swipe_startxratio.intValue(),5513 yratio.intValue(), 1);5514 }5515 }5516 if (GetDriverInfo().get("DriverName").toLowerCase().equals("chrome")5517 | GetDriverInfo().get("DriverName").toLowerCase().equals("chrome-mac")5518 | GetDriverInfo().get("DriverName").toLowerCase().equals("internet_explorer")) {5519 Actions builder = new Actions(EventFiringWebDriver);5520 // element.getSize();5521 Action dragAndDrop = builder.clickAndHold(element)5522 .moveToElement(element, element.getLocation().x + 90, element.getLocation().y).release()5523 .build();5524 dragAndDrop.perform();5525 try {5526 Thread.sleep(4000);5527 } catch (InterruptedException e) {5528 }5529 }5530 if (GetDriverInfo().get("DriverName").toLowerCase().equals("safari")5531 || GetDriverInfo().get("DriverName").toLowerCase().equals("firefox")) {5532 JavascriptExecutor js = (JavascriptExecutor) EventFiringWebDriver;5533 js.executeScript("$('.owl-wrapper').trigger('owl.next')");5534 }5535 } catch (Exception e) {5536 System.out.println(e.getMessage());5537 }5538 }5539 /**5540 * @author Cigniti5541 * @description : Swipe Bottom5542 * @param element5543 */5544 public void SwipeBottom(WebElement remoteelem) {5545 if (remoteelem != null) {5546 if (!GetDriverInfo().get("DriverName").equals("androidchrome")5547 && !GetDriverInfo().get("DriverType").toLowerCase().equals("desktop")) {5548 double browser_top_offset = 0.0;5549 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("mobile")) {5550 browser_top_offset = 0;5551 } else if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("tablet")) {5552 browser_top_offset = 240;5553 }5554 // RemoteWebElement remoteelem = ((RemoteWebElement)element);5555 // JavascriptExecutor js = (JavascriptExecutor)driver;5556 Point eloc = remoteelem.getLocation();5557 double yloc = eloc.getY();5558 double xloc = eloc.getX() + remoteelem.getSize().width / 2;5559 Double swipe_xratio = xloc;5560 double elemheight = remoteelem.getSize().getHeight();5561 Double yStartRatio = (yloc + elemheight + browser_top_offset) / 2;5562 Double yEndRatio = (eloc.getY() + browser_top_offset);5563 if (swipe_xratio < 10.0) {5564 swipe_xratio = 10.0;5565 }5566 if (yEndRatio < 50.0) {5567 yEndRatio = 50.0;5568 }5569 HashMap<String, Double> swipeObject = new HashMap<String, Double>();5570 swipeObject.put("startX", swipe_xratio);5571 swipeObject.put("startY", yStartRatio);5572 swipeObject.put("endX", swipe_xratio);5573 swipeObject.put("endY", yEndRatio);5574 swipeObject.put("duration", 1.0);5575 // js.executeScript("mobile: swipe", swipeObject);5576 if (driver != null && driver.getClass().toString().toUpperCase().contains("IOS")) {5577 driver.swipe(swipe_xratio.intValue(), yStartRatio.intValue(), swipe_xratio.intValue(),5578 yEndRatio.intValue(), 1);5579 }5580 }5581 }5582 }5583 /**5584 * @author Cigniti5585 * @description : Swipe Left5586 * @param element5587 */5588 public void SwipeLeft(WebElement element) {5589 // Executing swipe on in the case of iOS simulators. Skipping it for5590 // Android Chrome as this swipe will not yet implemented on it.5591 if ((!GetDriverInfo().get("DriverName").toLowerCase().equals("androidchrome"))5592 && (!GetDriverInfo().get("DriverName").toLowerCase().equals("chrome"))5593 && (!GetDriverInfo().get("DriverName").toLowerCase().equals("chrome-mac"))5594 && (!GetDriverInfo().get("DriverName").toLowerCase().equals("safari"))) {5595 if (driver != null) {5596 double browser_top_offset = 0.0;5597 if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("mobile")) {5598 browser_top_offset = 0;5599 } else if (GetDriverInfo().get("DriverType").trim().equalsIgnoreCase("tablet")) {5600 browser_top_offset = 80;5601 }5602 // RemoteWebElement remoteelem = ((RemoteWebElement)element);5603 WebElement remoteelem = element;5604 JavascriptExecutor js = (JavascriptExecutor) this.EventFiringWebDriver;5605 String script = "return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)";5606 Long pageheight1 = (Long) js.executeScript(script);5607 Long pagewidth1 = (Long) js5608 .executeScript("return Math.max(document.documentElement.clientWidth, window.innerWidth || 0)");5609 // Long pageheight2=(Long)js.executeScript("return5610 // window.innerHeight");5611 Point eloc = remoteelem.getLocation();5612 double yloc = eloc.getY();5613 double xstartloc = eloc.getX();5614 double xendloc = eloc.getX() + remoteelem.getSize().width;5615 Double swipe_startxratio = xstartloc / pagewidth1;5616 Double swipe_endxratio = xendloc / pagewidth1;5617 double elemheight = remoteelem.getSize().getHeight() / 2;5618 Double yratio = (yloc + elemheight / 2 + browser_top_offset) / pageheight1;5619 if (swipe_startxratio < 0.05) {5620 swipe_startxratio = 0.05;5621 }5622 if (swipe_endxratio > .95) {5623 swipe_endxratio = 0.95;5624 }5625 /*5626 * HashMap<String, Double> swipeObject = new HashMap<String,5627 * Double>(); swipeObject.put("startX", swipe_startxratio);5628 * swipeObject.put("startY", yratio); swipeObject.put("endX",5629 * swipe_endxratio); swipeObject.put("endY", yratio);5630 * swipeObject.put("duration", 0.8); js.executeScript(5631 * "mobile: swipe", swipeObject);5632 */5633 driver.swipe(swipe_endxratio.intValue(), yratio.intValue(), swipe_startxratio.intValue(),5634 yratio.intValue(), 1);5635 }5636 }5637 if (GetDriverInfo().get("DriverName").toLowerCase().equals("chrome")5638 | GetDriverInfo().get("DriverName").toLowerCase().equals("chrome-mac")) {5639 Actions builder = new Actions(EventFiringWebDriver);5640 Action dragAndDrop = builder.clickAndHold(element)5641 .moveToElement(element, element.getLocation().x + 800, element.getLocation().y + 10).release()5642 .build();5643 dragAndDrop.perform();5644 try {5645 Thread.sleep(4000);5646 } catch (InterruptedException e) {5647 }5648 }5649 if (GetDriverInfo().get("DriverName").toLowerCase().equals("safari")) {5650 JavascriptExecutor js = (JavascriptExecutor) EventFiringWebDriver;5651 js.executeScript("$('.owl-wrapper').trigger('owl.prev')");5652 }5653 }5654 /**5655 * @author Cigniti5656 * @description : Pinch Open5657 */5658 public void PinchOpen() {5659 JavascriptExecutor js = (JavascriptExecutor) this.EventFiringWebDriver;5660 HashMap<String, Double> swipeObject = new HashMap<String, Double>();5661 swipeObject.put("startX", (double) 114);5662 swipeObject.put("startY", (double) 198);5663 swipeObject.put("endX", (double) 257);5664 swipeObject.put("endY", (double) 256);5665 swipeObject.put("duration", 1.8);5666 js.executeScript("mobile: pinchOpen", swipeObject);5667 }5668 /**5669 * @author Cigniti5670 * @description : Pinch Close5671 */5672 public void PinchClose() {5673 JavascriptExecutor js = (JavascriptExecutor) this.EventFiringWebDriver;5674 HashMap<String, Double> swipeObject = new HashMap<String, Double>();5675 swipeObject.put("startX", (double) 150);5676 swipeObject.put("startY", (double) 230);5677 swipeObject.put("endX", (double) 200);5678 swipeObject.put("endY", (double) 260);5679 swipeObject.put("duration", 1.8);5680 js.executeScript("mobile: pinchOpen", swipeObject);5681 }5682 /**5683 * @author Cigniti5684 * @description : Change Orientation - // "LANDSCAPELEFT" , "LANDSCAPERIGHT"5685 * , "PORTRAIT"5686 * @param Orientation5687 */5688 public void ChangeOrientation(String Orientation) { // Valid values are:5689 // "LANDSCAPELEFT" ,5690 // "LANDSCAPERIGHT" ,5691 // "PORTRAIT"5692 JavascriptExecutor js = (JavascriptExecutor) this.EventFiringWebDriver;5693 js.executeScript("target.setDeviceOrientation(UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT);");5694 }5695 5696 5697 5698 }...

Full Screen

Full Screen

Source:WebDriverRunner.java Github

copy

Full Screen

1package com.codeborne.selenide;2import com.codeborne.selenide.impl.ThreadLocalSelenideDriver;3import com.codeborne.selenide.impl.WebDriverContainer;4import com.codeborne.selenide.impl.WebDriverThreadLocalContainer;5import com.codeborne.selenide.proxy.SelenideProxyServer;6import org.openqa.selenium.Proxy;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.support.events.WebDriverEventListener;9import org.openqa.selenium.support.events.WebDriverListener;10import javax.annotation.CheckReturnValue;11import javax.annotation.Nonnull;12import javax.annotation.Nullable;13import javax.annotation.ParametersAreNonnullByDefault;14import static com.codeborne.selenide.Configuration.browser;15import static com.codeborne.selenide.Configuration.headless;16/**17 * A static facade for accessing WebDriver instance for current threads18 */19@ParametersAreNonnullByDefault20public class WebDriverRunner {21 public static WebDriverContainer webdriverContainer = new WebDriverThreadLocalContainer();22 private static final SelenideDriver staticSelenideDriver = new ThreadLocalSelenideDriver();23 /**24 * @deprecated Use {@link #addListener(WebDriverListener)} instead25 */26 @Deprecated27 public static void addListener(WebDriverEventListener listener) {28 webdriverContainer.addListener(listener);29 }30 /**31 * @deprecated Use {@link #removeListener(WebDriverListener)} instead32 */33 @Deprecated34 public static void removeListener(WebDriverEventListener listener) {35 webdriverContainer.removeListener(listener);36 }37 /**38 * Use this method BEFORE opening a browser to add custom event listeners to webdriver.39 *40 * @param listener your listener of webdriver events41 * @since 6.0.042 */43 public static void addListener(WebDriverListener listener) {44 webdriverContainer.addListener(listener);45 }46 /**47 * @since 6.0.048 */49 public static void removeListener(WebDriverListener listener) {50 webdriverContainer.removeListener(listener);51 }52 /**53 * Tell Selenide use your provided WebDriver instance.54 * Use it if you need a custom logic for creating WebDriver.55 * <p>56 * It's recommended not to use implicit wait with this driver, because Selenide handles timing issues explicitly.57 *58 * <br>59 * <p>60 * NB! Be sure to call this method before calling <code>open(url)</code>.61 * Otherwise Selenide will create its own WebDriver instance and would not close it.62 *63 * <p>64 * NB! When using your custom webdriver, you are responsible for closing it.65 * Selenide will not take care of it.66 * </p>67 *68 * <p>69 * NB! Webdriver instance should be created and used in the same thread.70 * A typical error is to create webdriver instance in one thread and use it in another.71 * Selenide does not support it.72 * If you really need using multiple threads, please use #com.codeborne.selenide.WebDriverProvider73 * </p>74 *75 * <p>76 * P.S. Alternatively, you can run tests with system property77 * <pre> -Dbrowser=com.my.WebDriverFactory</pre>78 * <p>79 * which should implement interface #com.codeborne.selenide.WebDriverProvider80 * </p>81 */82 public static void setWebDriver(WebDriver webDriver) {83 webdriverContainer.setWebDriver(webDriver);84 }85 public static void setWebDriver(WebDriver webDriver, @Nullable SelenideProxyServer selenideProxy) {86 webdriverContainer.setWebDriver(webDriver, selenideProxy);87 }88 public static void setWebDriver(WebDriver webDriver,89 @Nullable SelenideProxyServer selenideProxy,90 DownloadsFolder browserDownloadsFolder) {91 webdriverContainer.setWebDriver(webDriver, selenideProxy, browserDownloadsFolder);92 }93 /**94 * Get the underlying instance of Selenium WebDriver.95 * This can be used for any operations directly with WebDriver.96 */97 @CheckReturnValue98 @Nonnull99 public static WebDriver getWebDriver() {100 return webdriverContainer.getWebDriver();101 }102 /**103 * Sets Selenium Proxy instance104 */105 public static void setProxy(@Nullable Proxy webProxy) {106 webdriverContainer.setProxy(webProxy);107 }108 /**109 * Get the underlying instance of Selenium WebDriver, and assert that it's still alive.110 *111 * @return new instance of WebDriver if the previous one has been closed meanwhile.112 */113 @CheckReturnValue114 @Nonnull115 public static WebDriver getAndCheckWebDriver() {116 return webdriverContainer.getAndCheckWebDriver();117 }118 /**119 * Get selenide proxy. It's activated only if Configuration.proxyEnabled == true120 *121 * @return null if proxy server is not started122 */123 @CheckReturnValue124 @Nullable125 public static SelenideProxyServer getSelenideProxy() {126 return webdriverContainer.getProxyServer();127 }128 @CheckReturnValue129 @Nonnull130 static SelenideDriver getSelenideDriver() {131 return staticSelenideDriver;132 }133 @CheckReturnValue134 @Nonnull135 public static Driver driver() {136 return getSelenideDriver().driver();137 }138 @CheckReturnValue139 @Nonnull140 public static DownloadsFolder getBrowserDownloadsFolder() {141 return webdriverContainer.getBrowserDownloadsFolder();142 }143 /**144 * Close the current window, quitting the browser if it's the last window currently open.145 *146 * @see WebDriver#close()147 */148 public static void closeWindow() {149 webdriverContainer.closeWindow();150 }151 /**152 * <p>Close the browser if it's open.</p>153 * <br>154 * <p>NB! Method quits this driver, closing every associated window.</p>155 *156 * @see WebDriver#quit()157 */158 public static void closeWebDriver() {159 webdriverContainer.closeWebDriver();160 }161 /**162 * @return true if instance of Selenium WebDriver is started in current thread163 */164 @CheckReturnValue165 public static boolean hasWebDriverStarted() {166 return webdriverContainer.hasWebDriverStarted();167 }168 public static void using(WebDriver driver, Runnable lambda) {169 if (hasWebDriverStarted()) {170 var previous = getWebDriver();171 try {172 lambda.run();173 }174 finally {175 setWebDriver(previous);176 }177 }178 else {179 setWebDriver(driver);180 try {181 lambda.run();182 }183 finally {184 webdriverContainer.resetWebDriver();185 }186 }187 }188 @CheckReturnValue189 @Nonnull190 private static Browser browser() {191 return new Browser(browser, headless);192 }193 /**194 * Is Selenide configured to use Firefox browser195 */196 @CheckReturnValue197 public static boolean isFirefox() {198 return browser().isFirefox();199 }200 /**201 * Is Selenide configured to use Chrome browser202 */203 @CheckReturnValue204 public static boolean isChrome() {205 return browser().isChrome();206 }207 /**208 * Is Selenide configured to use Internet Explorer browser209 */210 @CheckReturnValue211 public static boolean isIE() {212 return browser().isIE();213 }214 /**215 * Is Selenide configured to use Microsoft EDGE browser216 */217 @CheckReturnValue218 public static boolean isEdge() {219 return browser().isEdge();220 }221 /**222 * Is Selenide configured to use headless browser223 */224 @CheckReturnValue225 public static boolean isHeadless() {226 return browser().isHeadless();227 }228 /**229 * Does this browser support javascript230 */231 @CheckReturnValue232 public static boolean supportsJavascript() {233 return driver().supportsJavascript();234 }235 /**236 * Is Selenide configured to use Opera browser237 */238 @CheckReturnValue239 public static boolean isOpera() {240 return browser().isOpera();241 }242 /**243 * Delete all the browser cookies244 */245 public static void clearBrowserCache() {246 webdriverContainer.clearBrowserCache();247 }248 /**249 * @return the source (HTML) of current page250 */251 @CheckReturnValue252 @Nonnull253 public static String source() {254 return webdriverContainer.getPageSource();255 }256 /**257 * @return the URL of current page258 */259 @CheckReturnValue260 @Nonnull261 public static String url() {262 return webdriverContainer.getCurrentUrl();263 }264 /**265 * @return the URL of current frame266 */267 @CheckReturnValue268 @Nonnull269 public static String currentFrameUrl() {270 return webdriverContainer.getCurrentFrameUrl();271 }272}...

Full Screen

Full Screen

Source:WebDriverListener.java Github

copy

Full Screen

1package framework.utility;23import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.support.events.WebDriverEventListener;7import org.slf4j.Logger;89/**10 * The listener interface for receiving webDriver events.11 * The class that is interested in processing a webDriver12 * event implements this interface, and the object created13 * with that class is registered with a component using the14 * component's <code>addWebDriverListener<code> method. When15 * the webDriver event occurs, that object's appropriate16 * method is invoked.17 *18 * @see WebDriverEvent19 */20public class WebDriverListener implements WebDriverEventListener {21 22 private static final Logger LOG = LogFactory.getLogger(WebDriverListener.class);23 24 @Override25 public void beforeNavigateRefresh(WebDriver driver) {26 // TODO Auto-generated method stub27 28 }2930 @Override31 public void afterNavigateRefresh(WebDriver driver) {32 // TODO Auto-generated method stub33 34 }3536 @Override37 public void beforeChangeValueOf(WebElement element, WebDriver driver,38 CharSequence[] keysToSend) {39 // TODO Auto-generated method stub40 41 }42 43 @Override44 public void afterChangeValueOf(WebElement element, WebDriver driver,45 CharSequence[] keysToSend) {46 LOG.info("Element " + element + " value was changed");47 }48 49 @Override50 public void beforeClickOn(WebElement element, WebDriver driver) {5152 }5354 @Override55 public void afterClickOn(WebElement element, WebDriver driver) {56 LOG.info("Element " + getElementXpath(element) + " was clicked");57 }5859 @Override60 public void beforeNavigateTo(String url, WebDriver driver) {6162 }6364 @Override65 public void afterNavigateTo(String url, WebDriver driver) {66 LOG.info("Was navigated to url: " + url);67 }6869 @Override70 public void beforeNavigateBack(WebDriver driver) {7172 }7374 @Override75 public void afterNavigateBack(WebDriver driver) {7677 }7879 @Override80 public void beforeNavigateForward(WebDriver driver) {8182 }8384 @Override85 public void afterNavigateForward(WebDriver driver) {8687 }8889 @Override90 public void beforeFindBy(By by, WebElement element, WebDriver driver) {9192 }9394 @Override95 public void afterFindBy(By by, WebElement element, WebDriver driver) {9697 }9899 @Override100 public void beforeScript(String script, WebDriver driver) {101102 }103104 @Override105 public void afterScript(String script, WebDriver driver) {106 LOG.info(script + " script was executed");107 }108109 @Override110 public void onException(Throwable throwable, WebDriver driver) {111 LOG.info("WebDriver Exception thrown:", throwable.getMessage());112 }113 114 private String getElementXpath(WebElement element) {115 String elementStringRepresentation = element.toString();116 if (elementStringRepresentation.contains("xpath:")) {117 String substringElementStringRepresentation = 118 elementStringRepresentation.substring(119 elementStringRepresentation.indexOf("xpath: "), 120 elementStringRepresentation.length());121 if (substringElementStringRepresentation.contains("-> xpath:")) {122 return substringElementStringRepresentation.replaceAll(" -> xpath: ", "/");123 } else return substringElementStringRepresentation;124 }125 return "";126 }127128 @Override129 public void beforeAlertAccept(WebDriver driver) {130 // TODO Auto-generated method stub131 132 }133134 @Override135 public void afterAlertAccept(WebDriver driver) {136 // TODO Auto-generated method stub137 138 }139140 @Override141 public void afterAlertDismiss(WebDriver driver) {142 // TODO Auto-generated method stub143 144 }145146 @Override147 public void beforeAlertDismiss(WebDriver driver) {148 // TODO Auto-generated method stub149 150 }151152 @Override153 public void beforeSwitchToWindow(String windowName, WebDriver driver) {154 // TODO Auto-generated method stub155 156 }157158 @Override159 public void afterSwitchToWindow(String windowName, WebDriver driver) {160 // TODO Auto-generated method stub161 162 }163} ...

Full Screen

Full Screen

Source:WebDriverEventListener.java Github

copy

Full Screen

1package agile.utilities;23import java.io.File;4import java.io.IOException;5import java.util.Arrays;6import java.util.Map;7import java.util.concurrent.TimeUnit;89import org.apache.commons.io.FileUtils;10import org.openqa.selenium.By;11import org.openqa.selenium.Capabilities;12import org.openqa.selenium.NoAlertPresentException;13import org.openqa.selenium.NoSuchElementException;14import org.openqa.selenium.OutputType;15import org.openqa.selenium.TakesScreenshot;16import org.openqa.selenium.WebDriver;17import org.openqa.selenium.WebDriverException;18import org.openqa.selenium.WebElement;19import org.openqa.selenium.chrome.ChromeDriver;20import org.openqa.selenium.remote.RemoteWebDriver;21import org.openqa.selenium.support.events.EventFiringWebDriver;22import agile.utilities.Reporter;2324252627public interface WebDriverEventListener {2829 public void WebDriverListener();3031 public void beforeAlertAccept(WebDriver driver);3233 public void afterAlertAccept(WebDriver driver);3435 public void afterAlertDismiss(WebDriver driver);3637 public void beforeAlertDismiss(WebDriver driver);3839 public void beforeNavigateTo(String url, WebDriver driver);4041 public void afterNavigateTo(String url, WebDriver driver);4243 public void beforeNavigateBack(WebDriver driver);4445 public void afterNavigateBack(WebDriver driver);4647 public void beforeNavigateForward(WebDriver driver);4849 public void afterNavigateForward(WebDriver driver);5051 public void beforeNavigateRefresh(WebDriver driver);5253 public void afterNavigateRefresh(WebDriver driver);5455 public void beforeFindBy(By by, WebElement element, WebDriver driver);5657 public void afterFindBy(By by, WebElement element, WebDriver driver);5859 public void beforeClickOn(WebElement element, WebDriver driver);6061 public void afterClickOn(WebElement element, WebDriver driver);6263 public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend);6465 public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend);6667 public void beforeScript(String script, WebDriver driver);6869 public void afterScript(String script, WebDriver driver);7071 public void beforeSwitchToWindow(String windowName, WebDriver driver);7273 public void afterSwitchToWindow(String windowName, WebDriver driver);7475 public void onException(Throwable throwable, WebDriver driver);7677 public <X> void beforeGetScreenshotAs(OutputType<X> target);7879 public <X> void afterGetScreenshotAs(OutputType<X> target, X screenshot);8081 public long takeSnap();8283 /*@Override84 public void beforeGetText(WebElement element, WebDriver driver) {85 // TODO Auto-generated method stub86 87 }8889 @Override90 public void afterGetText(WebElement element, WebDriver driver, String text) {91 // TODO Auto-generated method stub92 93 }*/9495} ...

Full Screen

Full Screen

Source:ConfiguredDriver.java Github

copy

Full Screen

1package uk.co.evoco.webdriver.configuration.driver;2import org.apache.commons.io.FileUtils;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebDriverException;5import org.openqa.selenium.support.events.EventFiringWebDriver;6import uk.co.evoco.webdriver.WebDriverListener;7import uk.co.evoco.webdriver.configuration.TestConfigHelper;8import java.io.File;9import java.io.IOException;10public interface ConfiguredDriver {11 WebDriver getLocalDriver() throws IOException;12 WebDriver getRemoteDriver() throws IOException;13 <T> T getOptions() throws IOException;14 /**15 *ß16 * @param screenshotPath path to store screenshots17 * @return configured EventFiringWebDriver18 * @throws IOException if log directory doesn't exist19 */20 default EventFiringWebDriver getDriver(File screenshotPath) throws IOException {21 WebDriver webDriver;22 switch (TestConfigHelper.get().getRunType()) {23 case LOCAL:24 webDriver = getLocalDriver();25 break;26 case GRID:27 case SAUCELABS:28 webDriver = getRemoteDriver();29 break;30 default:31 throw new WebDriverException("Must set runType to either LOCAL or GRID in configuration file");32 }33 return configureEventFiringWebDriver(webDriver, screenshotPath);34 }35 /**36 *37 * @param webDriver active WebDriver instance38 * @param screenshotDirectory path to store screenshots39 * @return configured options object for target browser driver40 */41 default EventFiringWebDriver configureEventFiringWebDriver(42 WebDriver webDriver, File screenshotDirectory) {43 EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(webDriver);44 WebDriverListener eventListener = new WebDriverListener();45 eventListener.setScreenshotDirectory(screenshotDirectory);46 eventFiringWebDriver.register(eventListener);47 return eventFiringWebDriver;48 }49 /**50 * @throws IOException if the log directory cannot be created51 */52 default void createLogDirectory() throws IOException {53 FileUtils.forceMkdir(new File("./logs"));54 }55 /**56 *57 * @param path runtime browser files download directory path58 * @return Absolute file download path59 * @throws IOException if the required directory cannot be created60 */61 default String createFileDownloadDirectory(String path) throws IOException {62 String canonicalPath = new File(path).getCanonicalPath();63 FileUtils.forceMkdir(new File(canonicalPath));64 return canonicalPath;65 }66}...

Full Screen

Full Screen

Source:WebDriverContainer.java Github

copy

Full Screen

1package com.codeborne.selenide.impl;2import com.codeborne.selenide.DownloadsFolder;3import com.codeborne.selenide.proxy.SelenideProxyServer;4import org.openqa.selenium.Proxy;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.support.events.WebDriverEventListener;7import org.openqa.selenium.support.events.WebDriverListener;8import javax.annotation.CheckReturnValue;9import javax.annotation.Nonnull;10import javax.annotation.Nullable;11import javax.annotation.ParametersAreNonnullByDefault;12@ParametersAreNonnullByDefault13public interface WebDriverContainer {14 void addListener(WebDriverEventListener listener);15 void addListener(WebDriverListener listener);16 void removeListener(WebDriverEventListener listener);17 void removeListener(WebDriverListener listener);18 void setWebDriver(WebDriver webDriver);19 void setWebDriver(WebDriver webDriver, @Nullable SelenideProxyServer selenideProxy);20 void setWebDriver(WebDriver webDriver, @Nullable SelenideProxyServer selenideProxy, DownloadsFolder browserDownloadsFolder);21 void resetWebDriver();22 @CheckReturnValue23 @Nonnull24 WebDriver getWebDriver();25 @CheckReturnValue26 @Nullable27 SelenideProxyServer getProxyServer();28 void setProxy(@Nullable Proxy webProxy);29 @CheckReturnValue30 @Nonnull31 WebDriver getAndCheckWebDriver();32 @CheckReturnValue33 @Nonnull34 DownloadsFolder getBrowserDownloadsFolder();35 void closeWindow();36 void closeWebDriver();37 boolean hasWebDriverStarted();38 void clearBrowserCache();39 @CheckReturnValue40 @Nonnull41 String getPageSource();42 @CheckReturnValue43 @Nonnull44 String getCurrentUrl();45 @CheckReturnValue46 @Nonnull47 String getCurrentFrameUrl();48}...

Full Screen

Full Screen

Interface WebDriverListener

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.support.events.AbstractWebDriverEventListener;3public class WebDriverListener extends AbstractWebDriverEventListener {4 public void beforeNavigateTo(String url, WebDriver driver) {5 System.out.println("Before navigating to: '" + url + "'");6 }7 public void afterNavigateTo(String url, WebDriver driver) {8 System.out.println("Navigated to:'" + url + "'");9 }10 public void beforeNavigateBack(WebDriver driver) {11 System.out.println("Navigating back to previous page");12 }13 public void afterNavigateBack(WebDriver driver) {14 System.out.println("Navigated back to previous page");15 }16 public void beforeNavigateForward(WebDriver driver) {17 System.out.println("Navigating forward to next page");18 }19 public void afterNavigateForward(WebDriver driver) {20 System.out.println("Navigated forward to next page");21 }22 public void onException(Throwable error, WebDriver driver) {23 System.out.println("Exception occured: " + error);24 }25 public void beforeFindBy(By by, WebElement element, WebDriver driver) {26 System.out.println("Trying to find Element By : " + by.toString());27 }28 public void afterFindBy(By by, WebElement element, WebDriver driver) {29 System.out.println("Found Element By : " + by.toString());30 }31 public void beforeClickOn(WebElement element, WebDriver driver) {32 System.out.println("Trying to click on: " + element.toString());33 }34 public void afterClickOn(WebElement element, WebDriver driver) {35 System.out.println("Clicked on: " + element.toString());36 }37 public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {38 System.out.println("Value of the:" + element.toString() + " before any changes made");39 }40 public void afterChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) {41 System.out.println("Element value changed to: " + element.toString());42 }43 public void beforeScript(String script, WebDriver driver) {44 System.out.println("Before script");

Full Screen

Full Screen

Interface WebDriverListener

Using AI Code Generation

copy

Full Screen

1package com.java2blog;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.support.events.EventFiringWebDriver;4import org.openqa.selenium.support.events.WebDriverEventListener;5public class WebDriverListener implements WebDriverEventListener {6 public void beforeAlertAccept(WebDriver driver) {7 System.out.println("Before Alert Accept");8 }9 public void afterAlertAccept(WebDriver driver) {10 System.out.println("After Alert Accept");11 }12 public void afterAlertDismiss(WebDriver driver) {13 System.out.println("After Alert Dismiss");14 }15 public void beforeAlertDismiss(WebDriver driver) {16 System.out.println("Before Alert Dismiss");17 }18 public void beforeNavigateTo(String url, WebDriver driver) {19 System.out.println("Before Navigate To");20 }21 public void afterNavigateTo(String url, WebDriver driver) {22 System.out.println("After Navigate To");23 }24 public void beforeNavigateBack(WebDriver driver) {25 System.out.println("Before Navigate Back");26 }27 public void afterNavigateBack(WebDriver driver) {28 System.out.println("After Navigate Back");29 }30 public void beforeNavigateForward(WebDriver driver) {31 System.out.println("Before Navigate Forward");32 }33 public void afterNavigateForward(WebDriver driver) {34 System.out.println("After Navigate Forward");35 }36 public void beforeNavigateRefresh(WebDriver driver) {37 System.out.println("Before Navigate Refresh");38 }39 public void afterNavigateRefresh(WebDriver driver) {40 System.out.println("After Navigate Refresh");41 }42 public void beforeFindBy(org.openqa.selenium.By by, org.openqa.selenium.WebElement element, WebDriver driver) {43 System.out.println("Before Find By");44 }45 public void afterFindBy(org.openqa.selenium.By by, org.openqa.selenium.WebElement element, WebDriver driver) {46 System.out.println("After Find By");47 }48 public void beforeClickOn(org.openqa.selenium.WebElement element, WebDriver driver) {49 System.out.println("Before Click On");50 }51 public void afterClickOn(org.openqa.selenium.WebElement element, WebDriver driver) {52 System.out.println("After Click On");53 }54 public void beforeChangeValueOf(org.openqa.selenium.WebElement element

Full Screen

Full Screen

Interface WebDriverListener

Using AI Code Generation

copy

Full Screen

1public class WebDriverListener implements WebDriverEventListener {2 public void beforeNavigateTo(String url, WebDriver driver) {3 System.out.println("Before navigating to: '" + url + "'");4 }5 public void afterNavigateTo(String url, WebDriver driver) {6 System.out.println("Navigated to:'" + url + "'");7 }8 public void beforeChangeValueOf(WebElement element, WebDriver driver) {9 System.out.println("Value of the:" + element.toString() + " before any changes made");10 }11 public void afterChangeValueOf(WebElement element, WebDriver driver) {12 System.out.println("Element value changed to: " + element.toString());13 }14 public void beforeClickOn(WebElement element, WebDriver driver) {15 System.out.println("Trying to click on: " + element.toString());16 }17 public void afterClickOn(WebElement element, WebDriver driver) {18 System.out.println("Clicked on: " + element.toString());19 }20 public void beforeNavigateBack(WebDriver driver) {21 System.out.println("Navigating back to previous page");22 }23 public void afterNavigateBack(WebDriver driver) {24 System.out.println("Navigated back to previous page");25 }26 public void beforeNavigateForward(WebDriver driver) {27 System.out.println("Navigating forward to next page");28 }29 public void afterNavigateForward(WebDriver driver) {30 System.out.println("Navigated forward to next page");31 }32 public void onException(Throwable error, WebDriver driver) {33 System.out.println("Exception occured: " + error);34 }35 public <X> void beforeGetScreenshotAs(OutputType<X> target) {36 System.out.println("Before getting screenshot");37 }38 public <X> void afterGetScreenshotAs(OutputType<X> target, X screenshot) {39 System.out.println("After getting screenshot");40 }41 public void beforeGetText(WebElement element, WebDriver driver) {42 System.out.println("Before getting text from the element");43 }44 public void afterGetText(WebElement element, WebDriver driver, String text) {45 System.out.println("After getting text from the element");46 }47}

Full Screen

Full Screen

Interface WebDriverListener

Using AI Code Generation

copy

Full Screen

1package com.selenium.listeners;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.events.WebDriverEventListener;6public class WebDriverListener implements WebDriverEventListener {7 public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {8 System.out.println("After changing value of: " + arg0.toString());9 }10 public void afterClickOn(WebElement arg0, WebDriver arg1) {11 System.out.println("After clicking on: " + arg0.toString());12 }13 public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {14 System.out.println("After finding element by: " + arg0.toString());15 }16 public void afterNavigateBack(WebDriver arg0) {17 System.out.println("After navigating back");18 }19 public void afterNavigateForward(WebDriver arg0) {20 System.out.println("After navigating forward");21 }22 public void afterNavigateRefresh(WebDriver arg0) {23 System.out.println("After refreshing page");24 }25 public void afterNavigateTo(String arg0, WebDriver arg1) {26 System.out.println("After navigating to: " + arg0);27 }28 public void afterScript(String arg0, WebDriver arg1) {29 System.out.println("After executing script: " + arg0);30 }31 public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {32 System.out.println("Before changing value of: " + arg0.toString());33 }34 public void beforeClickOn(WebElement arg0, WebDriver arg1) {35 System.out.println("Before clicking on: " + arg0.toString());36 }37 public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {38 System.out.println("Before finding element by: " + arg0.toString());39 }40 public void beforeNavigateBack(WebDriver arg0) {41 System.out.println("Before navigating back");42 }43 public void beforeNavigateForward(WebDriver arg0) {44 System.out.println("Before navigating forward");45 }46 public void beforeNavigateRefresh(WebDriver arg0) {47 System.out.println("Before refreshing page");48 }49 public void beforeNavigateTo(String arg0

Full Screen

Full Screen

Interface WebDriverListener

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.support.events.AbstractWebDriverEventListener;4public class WebDriverListener extends AbstractWebDriverEventListener {5 public void beforeClickOn(WebElement element, WebDriver driver) {6 System.out.println("About to click on element: " + element);7 }8 public void afterClickOn(WebElement element, WebDriver driver) {9 System.out.println("Clicked on element: " + element);10 }11}12package com.seleniumeasy.tests;13import org.openqa.selenium.WebDriver;14import org.openqa.selenium.support.events.EventFiringWebDriver;15public class RegisterWebDriverListener {16 public static void main(String[] args) {17 WebDriver driver = new EventFiringWebDriver(new ChromeDriver()).register(new WebDriverListener());18 driver.findElement(By.id("user-message")).sendKeys("Hello World!");19 }20}21About to click on element: [ChromeDriver: chrome on WINDOWS (5b6a7f0d2e8d9c3a0b6c0b6a5b6a7f0d)] -> 22Clicked on element: [ChromeDriver: chrome on WINDOWS (5b6a7f0d2e8d9c3a0b6c0b6a5b6a7f0d)] -> 23We can also register this WebDriverListener with the WebDriver instance using WebDriverEventListener interface. This interface has methods that are invoked by the WebDriver at the points of interest. For example, beforeClickOn(WebElement, WebDriver) will be invoked before clicking on any element. The WebDriver

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in Interface-WebDriverListener

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful