Java tutorial
/* * BasePage.java * Copyright (c) 2014, CODEROAD, All Rights Reserved. * * This software is the confidential and proprietary information of CODEROAD * ("Confidential Information"). You shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement you entered into with * CODEROAD. */ package com.coderoad.automation.common.util.old; import java.sql.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; import org.junit.*; import org.openqa.selenium.*; import org.openqa.selenium.interactions.*; import org.openqa.selenium.support.ui.*; import com.coderoad.automation.common.enums.*; import com.coderoad.automation.common.log.*; import com.coderoad.automation.common.util.*; /** * This is the base class for all the pages in portals screens. * */ public abstract class BasePage { protected static WebDriver driver; /** * Instantiates a new base page. * * @param driver the driver */ public BasePage(WebDriver driver) { BasePage.driver = driver; BasePage.driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); //BasePage.driver.manage().timeouts().implicitlyWait(200, TimeUnit.SECONDS); } /** * this method send the click () event to the web element. * * @param elem the elem */ protected void click(WebElement elem) { JavascriptExecutor executor = (JavascriptExecutor) getDriver(); executor.executeScript("arguments[0].click();", elem); } /** * Gets the driver. * * @return the driver */ public WebDriver getDriver() { return BasePage.driver; } /** * Open page. * * @param url the url * @throws InterruptedException the interrupted exception */ public void openPage(String url) throws InterruptedException { if (url != null && !url.isEmpty()) { url = url.replace("-prod", ""); url = url.replace("prod", ""); url = url.replace("-PROD", ""); url = url.replace("PROD", ""); } LogUtil.log("Load URL:" + url, LogLevel.LOW); driver.manage().window().maximize(); driver.get(url); Thread.sleep(2000); LogUtil.log("URL Loaded", LogLevel.HIGH); } /** * this method sets the text in the webelement. * * @param fieldName the field name * @param value the value */ protected void setText(WebElement fieldName, String value) { clearText(fieldName); fieldName.clear(); if (value != null) { fieldName.sendKeys(value); } } /** * this method returns the timestamp. * * @return the time stamp */ public String getTimeStamp() { java.util.Date date = new java.util.Date(); return (new Timestamp(date.getTime()).toString()); } /** * Clear text. * * @param fieldName the field name */ protected void clearText(WebElement fieldName) { fieldName.sendKeys(Keys.SHIFT, Keys.HOME, Keys.BACK_SPACE); } /** * Check for null. * * @param el the el */ protected void checkForNull(WebElement el) { if (el == null) System.out.println(el + "is null"); else System.out.println(el + "is not null"); } /** * Wait for element. * * @param by the by * @return the web element */ protected WebElement waitForElement(final By by) { WebElement element = null; LogUtil.log("WaitForElement : + " + this.getTimeStamp(), LogLevel.HIGH); for (int i = 0; i < 3; i++) { try { element = new WebDriverWait(driver, TestUtils.timeout).until(new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver d) { return d.findElement(by); } }); } catch (Exception e) { TestLogger.logMsg("Wait waitForElement : + " + this.getTimeStamp()); } } LogUtil.log("Done waitForElement : + " + this.getTimeStamp(), LogLevel.HIGH); return element; } /** * Check the US phone Number * @param String phoneNumber * Ex. '(123) 456 7890', '123-456-7890', '1234567890' * @return "True" if the phoneNumber is U.S. Phone Formating */ public boolean checkUSphoneFormating(String number) { String regex = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(number.trim()); return matcher.matches(); } /** * Check the AUS phone Number * @param String phoneNumber * Ex. '(02) 3892 1111', '3892 1111' * @return "True" if the phoneNumber is AUS. Phone Formating */ public boolean checkAUSphoneFormating(String number) { String regex = "^\\({0,1}((0|\\+61)(2|4|3|7|8)){0,1}\\){0,1}(\\ |-){0,1}[0-9]{2}(\\ |-){0,1}[0-9]{2}(\\ |-){0,1}[0-9]{1}(\\ |-){0,1}[0-9]{3}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(number.trim()); return matcher.matches(); } /** * Check the UK phone Number * @param String phoneNumber * Ex. '5111-111111', '05111 111111' * @return "True" if the phoneNumber is UK. Phone Formating */ public boolean checkUKphoneFormating(String number) { String regex = "^\\(?(([0-9]{4})|(0?(5|8|1)([0-9]{2,3}))|(0169[-.\\s]77))\\)?[-.\\s]?([0-9]{4,6})$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(number.trim()); return matcher.matches(); } /** * Wait for visibility. * * @param element the element */ @SuppressWarnings("unused") protected void waitForVisibility(WebElement element) { LogUtil.log("Start waitForVisibility : " + this.getTimeStamp(), LogLevel.HIGH); for (int i = 0; i < 3; i++) { try { WebElement myDynamicElement = (new WebDriverWait(driver, TestUtils.timeout)) .until(ExpectedConditions.visibilityOf(element)); } catch (Exception e) { TestLogger.logMsg("Wait waitForVisibility : + " + this.getTimeStamp()); } } LogUtil.log("Done waitForVisibility : " + this.getTimeStamp(), LogLevel.HIGH); } /** * Wait for element presence. * * @param element the element */ @SuppressWarnings("unused") protected void waitForElementPresence(String element) { LogUtil.log("Start waitForElementPresence : " + this.getTimeStamp(), LogLevel.HIGH); for (int i = 0; i < 3; i++) { try { WebElement myDynamicElement = (new WebDriverWait(driver, TestUtils.timeout)) .until(ExpectedConditions.elementToBeClickable(By.id(element))); } catch (Exception e) { LogUtil.log("Wait waitForElementPresence : + " + this.getTimeStamp(), LogLevel.HIGH); } } LogUtil.log("Done waitForElementPresence : " + this.getTimeStamp(), LogLevel.HIGH); } /** * Wait for element presence. * * @param by the by */ @SuppressWarnings("unused") protected void waitForElementPresence(final By by) { LogUtil.log("Start waitForElementPresence : + " + this.getTimeStamp(), LogLevel.HIGH); for (int i = 0; i < 3; i++) { try { WebElement myDynamicElement = (new WebDriverWait(driver, TestUtils.timeout)) .until(ExpectedConditions.elementToBeClickable(by)); } catch (Exception e) { LogUtil.log("Wait waitForElementPresence : + " + this.getTimeStamp(), LogLevel.HIGH); } } LogUtil.log("Done waitForElementPresence : + " + this.getTimeStamp(), LogLevel.HIGH); } /** * this method selects the options from the combobox. * * @param dropDown the drop down * @param option the option */ protected void selectOptionIn(WebElement dropDown, String option) { String triggerId = dropDown.getAttribute("id"); dropDown.findElement(By.id(triggerId)).click(); List<WebElement> options = getDriver().findElements(By.xpath("//li[@role='option']")); for (WebElement opt : options) { if (opt.getText().equals(option)) { opt.click(); break; } } } /** * select the model from the list of vehicle models. * * @param models the models * @param modelCode the model code * @throws InterruptedException the interrupted exception */ public void selectVehicleModel(List<WebElement> models, String modelCode) throws InterruptedException { waitForVisibility(models.get(0)); for (WebElement model : models) { if (model.getText().equals(modelCode)) { model.click(); break; } } Thread.sleep(1000); } /** * Wait for page loaded. */ public void waitForPageLoaded() { ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete"); } }; Wait<WebDriver> wait = new WebDriverWait(this.getDriver(), TestUtils.timeout); try { wait.until(expectation); } catch (Throwable error) { LogUtil.log("Timeout waiting for Page Load Request to complete.", LogLevel.HIGH); } } /* * This method checks the version of the Module * @param modules , enum with the code of the module * */ public void verifyPageDisplaysVersion(Modules module) { LogUtil.log("Switch to iframe.", LogLevel.LOW); WaitUtil.waitUntil(Timeout.FIVE_SEC); getDriver().switchTo().frame(driver.findElement(By.tagName("iframe"))); LogUtil.log("Get version.", LogLevel.LOW); String version = this.getVersion(module); Assert.assertTrue("The page do not show the version.", version != null); LogUtil.log("The version is:" + version, LogLevel.LOW); } /* * This method returns the version of a page * @return the version of a page * */ public String getVersion(Enum<Modules> portal) { String response = null; try { if (portal == Modules.CONSUMER_MENU) { WebElement html = driver.findElement(By.tagName("html")); Assert.assertTrue("The page is not displayed.", html != null); String selectAll = Keys.chord(Keys.CONTROL, Keys.SHIFT, "v"); html.sendKeys(selectAll); Alert alertVersion = driver.switchTo().alert(); response = alertVersion.getText().split(":")[1]; alertVersion.accept(); } else if (portal == Modules.MOBILE_PORTAL) { WebElement element = driver.findElement(By.xpath("//div[contains(@class, 'site-version')]")); Actions actions = new Actions(driver); Action doubleClick = actions.doubleClick(element).build(); doubleClick.perform(); Alert alertVersion = driver.switchTo().alert(); response = alertVersion.getText(); alertVersion.accept(); } } catch (Exception e) { e.printStackTrace(); response = null; } return response; } /** * Switch to frame */ public void switchToFrame(String frame) { try { driver.switchTo().frame(frame); LogUtil.log("Navigated to frame with name " + frame, LogLevel.MEDIUM); } catch (NoSuchFrameException e) { LogUtil.log("Unable to locate frame with id " + frame + e.getStackTrace(), LogLevel.MEDIUM); } catch (Exception e) { LogUtil.log("Unable to navigate to frame with id " + frame + e.getStackTrace(), LogLevel.MEDIUM); } } /** * Switch to frame which has parent frame * */ public void switchToFrame(String parentFrame, String childFrame) { try { driver.switchTo().frame(parentFrame).switchTo().frame(childFrame); LogUtil.log("Navigated to innerframe with id " + childFrame + "which is present on frame with id" + parentFrame, LogLevel.MEDIUM); } catch (NoSuchFrameException e) { LogUtil.log("Unable to locate frame with id " + parentFrame + " or " + childFrame + e.getStackTrace(), LogLevel.MEDIUM); } catch (Exception e) { LogUtil.log("Unable to navigate to innerframe with id " + childFrame + "which is present on frame with id" + parentFrame + e.getStackTrace(), LogLevel.MEDIUM); } } /** * Switch to default frame * */ public void switchtoDefaultFrame() { try { driver.switchTo().defaultContent(); LogUtil.log("Navigated back to webpage from frame", LogLevel.MEDIUM); } catch (Exception e) { LogUtil.log("unable to navigate back to main webpage from frame" + e.getStackTrace(), LogLevel.MEDIUM); } } }