Best Carina code snippet using com.qaprosoft.carina.core.foundation.webdriver.DriverHelper.getUrl
Source:DriverHelper.java
...92 protected static final long RETRY_TIME = Configuration.getLong(Parameter.RETRY_INTERVAL);93 protected long timer;94 protected WebDriver driver;95 96 protected String pageURL = getUrl();97 protected CryptoTool cryptoTool;98 protected static Pattern CRYPTO_PATTERN = Pattern.compile(SpecialKeywords.CRYPT);99 public DriverHelper() {100 cryptoTool = new CryptoTool(Configuration.getCryptoParams());101 }102 public DriverHelper(WebDriver driver) {103 this();104 105 this.driver = driver;106 if (driver == null) {107 throw new RuntimeException("WebDriver not initialized, check log files for details!");108 }109 }110 111 /**112 * Opens page according to specified in constructor URL.113 */114 public void open() {115 openURL(this.pageURL);116 }117 118 /**119 * Open URL.120 * 121 * @param url122 * to open.123 */124 public void openURL(String url) {125 openURL(url, Configuration.getInt(Parameter.EXPLICIT_TIMEOUT));126 }127 128 /**129 * Open URL.130 * 131 * @param url132 * to open.133 * @param timeout134 * long135 */136 public void openURL(String url, long timeout) {137 final String decryptedURL = getEnvArgURL(cryptoTool.decryptByPattern(url, CRYPTO_PATTERN));138 this.pageURL = decryptedURL;139 WebDriver drv = getDriver();140 141 setPageLoadTimeout(drv, timeout);142 DriverListener.setMessages(Messager.OPENED_URL.getMessage(url), Messager.NOT_OPENED_URL.getMessage(url));143 144 // [VD] there is no sense to use fluent wait here as selenium just don't return something until page is ready!145 // explicitly limit time for the openURL operation146 try {147 Messager.OPENING_URL.info(url);148 drv.get(decryptedURL);149 } catch (UnhandledAlertException e) {150 drv.switchTo().alert().accept();151 } catch (TimeoutException e) {152 trigger("window.stop();"); //try to cancel page loading153 Assert.fail("Unable to open url during " + timeout + "sec!");154 } catch (Exception e) {155 Assert.fail("Undefined error on open url detected: " + e.getMessage(), e);156 } finally {157 //restore default pageLoadTimeout driver timeout158 setPageLoadTimeout(drv, getPageLoadTimeout());159 LOGGER.debug("finished driver.get call.");160 }161 }162 protected void setPageURL(String relURL) {163 String baseURL;164 // if(!"NULL".equalsIgnoreCase(Configuration.get(Parameter.ENV)))165 if (!Configuration.get(Parameter.ENV).isEmpty()) {166 baseURL = Configuration.getEnvArg("base");167 } else {168 baseURL = Configuration.get(Parameter.URL);169 }170 this.pageURL = baseURL + relURL;171 }172 protected void setPageAbsoluteURL(String url) {173 this.pageURL = url;174 }175 public String getPageURL() {176 return this.pageURL;177 } 178 // --------------------------------------------------------------------------179 // Base UI interaction operations180 // --------------------------------------------------------------------------181 /**182 * Method which quickly looks for all element and check that they present183 * during EXPLICIT_TIMEOUT184 *185 * @param elements186 * ExtendedWebElement...187 * @return boolean return true only if all elements present.188 */189 public boolean allElementsPresent(ExtendedWebElement... elements) {190 return allElementsPresent(EXPLICIT_TIMEOUT, elements);191 }192 /**193 * Method which quickly looks for all element and check that they present194 * during timeout sec195 *196 * @param timeout long197 * @param elements198 * ExtendedWebElement...199 * @return boolean return true only if all elements present.200 */201 public boolean allElementsPresent(long timeout, ExtendedWebElement... elements) {202 int index = 0;203 boolean present = true;204 boolean ret = true;205 int counts = 1;206 timeout = timeout / counts;207 if (timeout < 1)208 timeout = 1;209 while (present && index++ < counts) {210 for (int i = 0; i < elements.length; i++) {211 present = elements[i].isElementPresent(timeout);212 if (!present) {213 LOGGER.error(elements[i].getNameWithLocator() + " is not present.");214 ret = false;215 }216 }217 }218 return ret;219 }220 /**221 * Method which quickly looks for all element lists and check that they222 * contain at least one element during SHORT_TIMEOUT223 *224 * @param elements225 * List<ExtendedWebElement>...226 * @return boolean227 */228 @SuppressWarnings("unchecked")229 public boolean allElementListsAreNotEmpty(List<ExtendedWebElement>... elements) {230 return allElementListsAreNotEmpty(SHORT_TIMEOUT, elements);231 }232 /**233 * Method which quickly looks for all element lists and check that they234 * contain at least one element during timeout235 *236 * @param timeout long237 * @param elements238 * List<ExtendedWebElement>...239 * @return boolean return true only if All Element lists contain at least240 * one element241 */242 @SuppressWarnings("unchecked")243 public boolean allElementListsAreNotEmpty(long timeout, List<ExtendedWebElement>... elements) {244 boolean ret;245 int counts = 3;246 timeout = timeout / counts;247 if (timeout < 1)248 timeout = 1;249 for (int i = 0; i < elements.length; i++) {250 boolean present = false;251 int index = 0;252 while (!present && index++ < counts) {253 try {254 present = elements[i].get(0).isElementPresent(timeout);255 } catch (Exception e) {256 present = false;257 }258 }259 ret = (elements[i].size() > 0);260 if (!ret) {261 LOGGER.error("List of elements[" + i + "] from elements " + Arrays.toString(elements) + " is empty.");262 return false;263 }264 }265 return true;266 }267 /**268 * Method which quickly looks for any element presence during269 * SHORT_TIMEOUT270 *271 * @param elements ExtendedWebElement...272 * @return true if any of elements was found.273 */274 public boolean isAnyElementPresent(ExtendedWebElement... elements) {275 return isAnyElementPresent(SHORT_TIMEOUT, elements);276 }277 /**278 * Method which quickly looks for any element presence during timeout sec279 *280 * @param timeout long281 * @param elements282 * ExtendedWebElement...283 * @return true if any of elements was found.284 */285 public boolean isAnyElementPresent(long timeout, ExtendedWebElement... elements) {286 int index = 0;287 int counts = 10;288 timeout = timeout / counts;289 if (timeout < 1)290 timeout = 1;291 while (index++ < counts) {292 for (int i = 0; i < elements.length; i++) {293 if (elements[i].isElementPresent(timeout)) {294 LOGGER.debug(elements[i].getNameWithLocator() + " is present");295 return true;296 }297 }298 }299 300 LOGGER.error("Unable to find any element from array: " + Arrays.toString(elements));301 return false;302 }303 /**304 * return Any Present Element from the list which present during305 * SHORT_TIMEOUT306 *307 * @param elements ExtendedWebElement...308 * @return ExtendedWebElement309 */310 public ExtendedWebElement returnAnyPresentElement(ExtendedWebElement... elements) {311 return returnAnyPresentElement(SHORT_TIMEOUT, elements);312 }313 /**314 * return Any Present Element from the list which present during timeout sec315 *316 * @param timeout long317 * @param elements318 * ExtendedWebElement...319 * @return ExtendedWebElement320 */321 public ExtendedWebElement returnAnyPresentElement(long timeout, ExtendedWebElement... elements) {322 int index = 0;323 int counts = 10;324 timeout = timeout / counts;325 if (timeout < 1)326 timeout = 1;327 while (index++ < counts) {328 for (int i = 0; i < elements.length; i++) {329 if (elements[i].isElementPresent(timeout)) {330 LOGGER.debug(elements[i].getNameWithLocator() + " is present");331 return elements[i];332 }333 }334 }335 //throw exception anyway if nothing was returned inside for cycle336 LOGGER.error("All elements are not present");337 throw new RuntimeException("Unable to find any element from array: " + Arrays.toString(elements));338 }339 /**340 * Check that element with text present.341 * 342 * @param extWebElement to check if element with text is present343 * @param text344 * of element to check.345 * @return element with text existence status.346 */347 public boolean isElementWithTextPresent(final ExtendedWebElement extWebElement, final String text) {348 return isElementWithTextPresent(extWebElement, text, EXPLICIT_TIMEOUT);349 }350 /**351 * Check that element with text present.352 * 353 * @param extWebElement to check if element with text is present354 * @param text355 * of element to check.356 * @param timeout Long357 * @return element with text existence status.358 */359 public boolean isElementWithTextPresent(final ExtendedWebElement extWebElement, final String text, long timeout) {360 return extWebElement.isElementWithTextPresent(text, timeout);361 }362 /**363 * Check that element not present on page.364 * 365 * @param extWebElement to check if element is not present366 * 367 * @return element non-existence status.368 */369 public boolean isElementNotPresent(final ExtendedWebElement extWebElement) {370 return isElementNotPresent(extWebElement, EXPLICIT_TIMEOUT);371 }372 /**373 * Check that element not present on page.374 * 375 * @param extWebElement to check if element is not present376 * @param timeout to wait377 * 378 * @return element non-existence status.379 */380 public boolean isElementNotPresent(final ExtendedWebElement extWebElement, long timeout) {381 return extWebElement.isElementNotPresent(timeout);382 }383 /**384 * Check that element not present on page.385 * 386 * @param element to check if element is not present387 * @param controlInfo String388 * 389 * @return element non-existence status.390 */391 public boolean isElementNotPresent(String controlInfo, final WebElement element) {392 return isElementNotPresent(new ExtendedWebElement(element, controlInfo));393 }394 /**395 * Clicks on element.396 * 397 * @param elements ExtendedWebElements to click398 *399 */400 public void clickAny(ExtendedWebElement... elements) {401 clickAny(EXPLICIT_TIMEOUT, elements);402 }403 /**404 * Clicks on element.405 * 406 * @param elements ExtendedWebElements to click407 * @param timeout to wait408 *409 */410 public void clickAny(long timeout, ExtendedWebElement... elements) {411 // Method which quickly looks for any element and click during timeout412 // sec413 WebDriver drv = getDriver();414 ActionPoller<WebElement> actionPoller = ActionPoller.builder();415 Optional<WebElement> searchableElement = actionPoller.task(() -> {416 WebElement possiblyFoundElement = null;417 for (ExtendedWebElement element : elements) {418 List<WebElement> foundElements = drv.findElements(element.getBy());419 if (foundElements.size() > 0) {420 possiblyFoundElement = foundElements.get(0);421 break;422 }423 }424 return possiblyFoundElement;425 })426 .until(Objects::nonNull)427 .pollEvery(0, ChronoUnit.SECONDS)428 .stopAfter(timeout, ChronoUnit.SECONDS)429 .execute();430 if (searchableElement.isEmpty()) {431 throw new RuntimeException("Unable to click onto any elements from array: " + Arrays.toString(elements));432 }433 searchableElement.get()434 .click();435 }436 437 /*438 * Get and return the source of the last loaded page.439 * @return String440 */441 public String getPageSource() {442 WebDriver drv = getDriver();443 Messager.GET_PAGE_SOURCE.info();444 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)445 .pollingEvery(Duration.ofMillis(5000)) // there is no sense to refresh url address too often446 .withTimeout(Duration.ofSeconds(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)))447 .ignoring(WebDriverException.class)448 .ignoring(JavascriptException.class); // org.openqa.selenium.JavascriptException: javascript error: Cannot read property 'outerHTML' of null449 String res = "";450 try {451 res = wait.until(new Function<WebDriver, String>() {452 public String apply(WebDriver driver) {453 return drv.getPageSource();454 }455 });456 } catch (ScriptTimeoutException | TimeoutException e) {457 Messager.FAIL_GET_PAGE_SOURCE.error();458 }459 Messager.GET_PAGE_SOURCE.info();460 return res;461 }462 463 /*464 * Add cookie object into the driver465 * @param Cookie466 */467 public void addCookie(Cookie cookie) {468 WebDriver drv = getDriver();469 DriverListener.setMessages(Messager.ADD_COOKIE.getMessage(cookie.getName()), 470 Messager.FAIL_ADD_COOKIE.getMessage(cookie.getName()));471 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)472 .pollingEvery(Duration.ofMillis(Configuration.getInt(Parameter.RETRY_INTERVAL)))473 .withTimeout(Duration.ofSeconds(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)))474 .ignoring(WebDriverException.class)475 .ignoring(JsonException.class); // org.openqa.selenium.json.JsonException: Expected to read a START_MAP but instead have: END. Last 0 characters rea476 wait.until(new Function<WebDriver, Boolean>() {477 public Boolean apply(WebDriver driver) {478 drv.manage().addCookie(cookie);479 return true;480 }481 });482 }483 484 /**485 * Get a string representing the current URL that the browser is looking at.486 * @return url.487 */488 public String getCurrentUrl() {489 return getCurrentUrl(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT));490 }491 492 /**493 * Get a string representing the current URL that the browser is looking at.494 * @param timeout long495 * @return validation result.496 */497 public String getCurrentUrl(long timeout) {498 WebDriver drv = getDriver();499 500 // explicitly limit time for the getCurrentUrl operation501 Future<?> future = Executors.newSingleThreadExecutor().submit(new Callable<String>() {502 public String call() throws Exception {503 //organize fluent waiter for getting url504 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)505 .pollingEvery(Duration.ofMillis(Configuration.getInt(Parameter.RETRY_INTERVAL)))506 .withTimeout(Duration.ofSeconds(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)))507 .ignoring(WebDriverException.class)508 .ignoring(JsonException.class); // org.openqa.selenium.json.JsonException: Expected to read a START_MAP but instead have: END. Last 0 characters rea509 return wait.until(new Function<WebDriver, String>() {510 public String apply(WebDriver driver) {511 return drv.getCurrentUrl();512 }513 });514 }515 });516 517 String url = "";518 try {519 url = (String) future.get(timeout, TimeUnit.SECONDS);520 } catch (java.util.concurrent.TimeoutException e) {521 LOGGER.debug("Unable to get driver url during " + timeout + "sec!", e);522 } catch (InterruptedException e) {523 LOGGER.debug("Unable to get driver url during " + timeout + "sec!", e);524 Thread.currentThread().interrupt();525 } catch (ExecutionException e) {526 LOGGER.error("ExecutionException error on get driver url!", e);527 } catch (Exception e) {528 LOGGER.error("Undefined error on get driver url detected!", e);529 }530 531 return url;532 } 533 /**534 * Checks that current URL is as expected.535 * 536 * @param expectedURL537 * Expected Url538 * @return validation result.539 */540 public boolean isUrlAsExpected(String expectedURL) {541 return isUrlAsExpected(expectedURL, Configuration.getInt(Parameter.EXPLICIT_TIMEOUT)); 542 }543 /**544 * Checks that current URL is as expected.545 * 546 * @param expectedURL547 * Expected Url548 * @param timeout long549 * @return validation result.550 */551 public boolean isUrlAsExpected(String expectedURL, long timeout) {552 String decryptedURL = cryptoTool.decryptByPattern(expectedURL, CRYPTO_PATTERN);553 decryptedURL = getEnvArgURL(decryptedURL);554 555 String actualUrl = getCurrentUrl(timeout);556 557 if (LogicUtils.isURLEqual(decryptedURL, actualUrl)) {558 Messager.EXPECTED_URL.info(actualUrl);559 return true;560 } else {561 Messager.UNEXPECTED_URL.error(expectedURL, actualUrl);562 return false;563 } 564 }565 566 567 /**568 * Get full or relative URL considering Env argument569 * 570 * @param decryptedURL String571 * @return url572 */573 private String getEnvArgURL(String decryptedURL) {574 if (!(decryptedURL.contains("http:") || decryptedURL.contains("https:"))) {575 if (Configuration.getEnvArg(Parameter.URL.getKey()).isEmpty()) {576 decryptedURL = Configuration.get(Parameter.URL) + decryptedURL;577 } else {578 decryptedURL = Configuration.getEnvArg(Parameter.URL.getKey()) + decryptedURL;579 }580 }581 return decryptedURL;582 }583 /**584 *585 * @return String saved in clipboard586 */587 public String getClipboardText() {588 String clipboardText = "";589 try {590 LOGGER.debug("Trying to get clipboard from remote machine with hub...");591 String url = getSelenoidClipboardUrl(driver);592 String username = getField(url, 1);593 String password = getField(url, 2);594 HttpURLConnection.setFollowRedirects(false);595 HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();596 con.setRequestMethod("GET");597 if (!username.isEmpty() && !password.isEmpty()) {598 String usernameColonPassword = username + ":" + password;599 String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());600 con.addRequestProperty("Authorization", basicAuthPayload);601 }602 int status = con.getResponseCode();603 if (200 <= status && status <= 299) {604 BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));605 String inputLine;606 StringBuffer content = new StringBuffer();607 while ((inputLine = br.readLine()) != null) {608 content.append(inputLine);609 }610 br.close();611 clipboardText = content.toString();612 } else {613 LOGGER.debug("Trying to get clipboard from local java machine...");614 clipboardText = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);615 }616 } catch (Exception ex) {617 ex.printStackTrace();618 }619 clipboardText = clipboardText.replaceAll("\n", "");620 LOGGER.info("Clipboard: " + clipboardText);621 return clipboardText;622 }623 private String getSelenoidClipboardUrl(WebDriver driver) {624 String seleniumHost = Configuration.getSeleniumUrl().replace("wd/hub", "clipboard/");625 if (seleniumHost.isEmpty()){626 seleniumHost = Configuration.getEnvArg(Parameter.URL.getKey()).replace("wd/hub", "clipboard/");627 }628 WebDriver drv = (driver instanceof EventFiringWebDriver) ? ((EventFiringWebDriver) driver).getWrappedDriver() : driver;629 String sessionId = ((RemoteWebDriver) drv).getSessionId().toString();630 String url = seleniumHost + sessionId;631 LOGGER.debug("url: " + url);632 return url;633 }634 private String getField(String url, int position) {635 Pattern pattern = Pattern.compile(".*:\\/\\/(.*):(.*)@");636 Matcher matcher = pattern.matcher(url);637 return matcher.find() ? matcher.group(position) : "";638 }639 /**640 * Pause for specified timeout.641 * 642 * @param timeout643 * in seconds.644 */645 public void pause(long timeout) {646 CommonUtils.pause(timeout);647 }648 public void pause(Double timeout) {649 CommonUtils.pause(timeout);650 }651 652 /**653 * Return page title.654 * 655 * @return title String.656 */657 public String getTitle() {658 return getTitle(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT));659 }660 661 /**662 * Return page title.663 * 664 * @param timeout long665 * @return title String.666 */667 public String getTitle(long timeout) {668 669 WebDriver drv = getDriver();670 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)671 .pollingEvery(Duration.ofMillis(RETRY_TIME))672 .withTimeout(Duration.ofSeconds(timeout))673 .ignoring(WebDriverException.class)674 .ignoring(JavascriptException.class); // org.openqa.selenium.JavascriptException: javascript error: Cannot read property 'outerHTML' of null675 String res = "";676 try {677 res = wait.until(new Function<WebDriver, String>() {678 public String apply(WebDriver driver) {679 return drv.getTitle();680 }681 });682 } catch (ScriptTimeoutException | TimeoutException e) {683 Messager.FAIL_GET_TITLE.error();684 }685 return res;686 } 687 /**688 * Checks that page title is as expected.689 * 690 * @param expectedTitle691 * Expected title692 * @return validation result.693 */694 public boolean isTitleAsExpected(final String expectedTitle) {695 final String decryptedExpectedTitle = cryptoTool.decryptByPattern(expectedTitle, CRYPTO_PATTERN);696 String title = getTitle(EXPLICIT_TIMEOUT);697 boolean result = title.contains(decryptedExpectedTitle);698 if (result) {699 Messager.TITLE_CORRECT.info(expectedTitle);700 } else {701 Messager.TITLE_NOT_CORRECT.error(expectedTitle, title);702 }703 704 return result;705 }706 /**707 * Checks that page suites to expected pattern.708 * 709 * @param expectedPattern710 * Expected Pattern711 * @return validation result.712 */713 public boolean isTitleAsExpectedPattern(String expectedPattern) {714 final String decryptedExpectedPattern = cryptoTool.decryptByPattern(expectedPattern, CRYPTO_PATTERN);715 716 String actual = getTitle(EXPLICIT_TIMEOUT);717 Pattern p = Pattern.compile(decryptedExpectedPattern);718 Matcher m = p.matcher(actual);719 boolean result = m.find();720 if (result) {721 Messager.TITLE_CORRECT.info(actual);722 } else {723 Messager.TITLE_NOT_CORRECT.error(expectedPattern, actual); 724 }725 726 return result;727 }728 /**729 * Go back in browser.730 */731 public void navigateBack() {732 getDriver().navigate().back();733 Messager.BACK.info();734 }735 /**736 * Refresh browser.737 */738 public void refresh() {739 refresh(Configuration.getInt(Parameter.EXPLICIT_TIMEOUT));740 }741 /**742 * Refresh browser.743 * 744 * @param timeout long745 */746 public void refresh(long timeout) {747 WebDriver drv = getDriver();748 Wait<WebDriver> wait = new FluentWait<WebDriver>(drv)749 .pollingEvery(Duration.ofMillis(5000)) // there is no sense to refresh url address too often750 .withTimeout(Duration.ofSeconds(timeout))751 .ignoring(WebDriverException.class)752 .ignoring(JsonException.class); // org.openqa.selenium.json.JsonException: Expected to read a START_MAP but instead have: END. Last 0 characters read753 754 try {755 wait.until(new Function<WebDriver, Void>() {756 public Void apply(WebDriver driver) {757 drv.navigate().refresh();758 return null;759 }760 });761 } catch (ScriptTimeoutException | TimeoutException e) {762 Messager.FAIL_REFRESH.error();763 }764 Messager.REFRESH.info();765 }766 public void pressTab() {767 Actions builder = new Actions(getDriver());768 builder.sendKeys(Keys.TAB).perform();769 }770 /**771 * Drags and drops element to specified place.772 * 773 * @param from774 * - element to drag.775 * @param to776 * - element to drop to.777 */778 public void dragAndDrop(final ExtendedWebElement from, final ExtendedWebElement to) {779 if (from.isElementPresent() && to.isElementPresent()) {780 WebDriver drv = getDriver();781 if (!drv.toString().contains("safari")) {782 Actions builder = new Actions(drv);783 Action dragAndDrop = builder.clickAndHold(from.getElement()).moveToElement(to.getElement())784 .release(to.getElement()).build();785 dragAndDrop.perform();786 } else {787 WebElement LocatorFrom = from.getElement();788 WebElement LocatorTo = to.getElement();789 String xto = Integer.toString(LocatorTo.getLocation().x);790 String yto = Integer.toString(LocatorTo.getLocation().y);791 ((JavascriptExecutor) driver)792 .executeScript(793 "function simulate(f,c,d,e){var b,a=null;for(b in eventMatchers)if(eventMatchers[b].test(c)){a=b;break}if(!a)return!1;document.createEvent?(b=document.createEvent(a),a==\"HTMLEvents\"?b.initEvent(c,!0,!0):b.initMouseEvent(c,!0,!0,document.defaultView,0,d,e,d,e,!1,!1,!1,!1,0,null),f.dispatchEvent(b)):(a=document.createEventObject(),a.detail=0,a.screenX=d,a.screenY=e,a.clientX=d,a.clientY=e,a.ctrlKey=!1,a.altKey=!1,a.shiftKey=!1,a.metaKey=!1,a.button=1,f.fireEvent(\"on\"+c,a));return!0} var eventMatchers={HTMLEvents:/^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,MouseEvents:/^(?:click|dblclick|mouse(?:down|up|over|move|out))$/}; "794 + "simulate(arguments[0],\"mousedown\",0,0); simulate(arguments[0],\"mousemove\",arguments[1],arguments[2]); simulate(arguments[0],\"mouseup\",arguments[1],arguments[2]); ",795 LocatorFrom, xto, yto);796 }797 Messager.ELEMENTS_DRAGGED_AND_DROPPED.info(from.getName(), to.getName());798 } else {799 Messager.ELEMENTS_NOT_DRAGGED_AND_DROPPED.error(from.getNameWithLocator(), to.getNameWithLocator());800 }801 }802 /**803 * Drags and drops element to specified place. Elements Need To have an id.804 *805 * @param from806 * - the element to drag.807 * @param to808 * - the element to drop to.809 */810 public void dragAndDropHtml5(final ExtendedWebElement from, final ExtendedWebElement to) {811 String source = "#" + from.getAttribute("id");812 String target = "#" + to.getAttribute("id");813 if (source.isEmpty() || target.isEmpty()) {814 Messager.ELEMENTS_NOT_DRAGGED_AND_DROPPED.error(from.getNameWithLocator(), to.getNameWithLocator());815 } else {816 jQuerify(driver);817 String javaScript = "(function( $ ) { $.fn.simulateDragDrop = function(options) { return this.each(function() { new $.simulateDragDrop(this, options); }); }; $.simulateDragDrop = function(elem, options) { this.options = options; this.simulateEvent(elem, options); }; $.extend($.simulateDragDrop.prototype, { simulateEvent: function(elem, options) { /*Simulating drag start*/ var type = 'dragstart'; var event = this.createEvent(type); this.dispatchEvent(elem, type, event); /*Simulating drop*/ type = 'drop'; var dropEvent = this.createEvent(type, {}); dropEvent.dataTransfer = event.dataTransfer; this.dispatchEvent($(options.dropTarget)[0], type, dropEvent); /*Simulating drag end*/ type = 'dragend'; var dragEndEvent = this.createEvent(type, {}); dragEndEvent.dataTransfer = event.dataTransfer; this.dispatchEvent(elem, type, dragEndEvent); }, createEvent: function(type) { var event = document.createEvent(\"CustomEvent\"); event.initCustomEvent(type, true, true, null); event.dataTransfer = { data: { }, setData: function(type, val){ this.data[type] = val; }, getData: function(type){ return this.data[type]; } }; return event; }, dispatchEvent: function(elem, type, event) { if(elem.dispatchEvent) { elem.dispatchEvent(event); }else if( elem.fireEvent ) { elem.fireEvent(\"on\"+type, event); } } });})(jQuery);";;818 ((JavascriptExecutor)driver)819 .executeScript(javaScript + "$('" + source + "')" +820 ".simulateDragDrop({ dropTarget: '" + target + "'});");821 Messager.ELEMENTS_DRAGGED_AND_DROPPED.info(from.getName(), to.getName());822 }823 }824 private static void jQuerify(WebDriver driver) {825 String jQueryLoader = "(function(jqueryUrl, callback) {\n" +826 " if (typeof jqueryUrl != 'string') {\n" +827 " jqueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';\n" +828 " }\n" +829 " if (typeof jQuery == 'undefined') {\n" +830 " var script = document.createElement('script');\n" +831 " var head = document.getElementsByTagName('head')[0];\n" +832 " var done = false;\n" +833 " script.onload = script.onreadystatechange = (function() {\n" +834 " if (!done && (!this.readyState || this.readyState == 'loaded'\n" +835 " || this.readyState == 'complete')) {\n" +836 " done = true;\n" +837 " script.onload = script.onreadystatechange = null;\n" +838 " head.removeChild(script);\n" +839 " callback();\n" +840 " }\n" +841 " });\n" +842 " script.src = jqueryUrl;\n" +843 " head.appendChild(script);\n" +844 " }\n" +845 " else {\n" +846 " callback();\n" +847 " }\n" +848 "})(arguments[0], arguments[arguments.length - 1]);";849 driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);850 JavascriptExecutor js = (JavascriptExecutor) driver;851 js.executeAsyncScript(jQueryLoader);852 }853 /**854 * Performs slider move for specified offset.855 * 856 * @param slider857 * slider858 * @param moveX859 * move x860 * @param moveY861 * move y862 */863 public void slide(ExtendedWebElement slider, int moveX, int moveY) {864 //TODO: SZ migrate to FluentWaits865 if (slider.isElementPresent()) {866 WebDriver drv = getDriver();867 (new Actions(drv)).moveToElement(slider.getElement()).dragAndDropBy(slider.getElement(), moveX, moveY)868 .build().perform();869 Messager.SLIDER_MOVED.info(slider.getNameWithLocator(), String.valueOf(moveX), String.valueOf(moveY));870 } else {871 Messager.SLIDER_NOT_MOVED.error(slider.getNameWithLocator(), String.valueOf(moveX), String.valueOf(moveY));872 }873 }874 /**875 * Accepts alert modal.876 */877 public void acceptAlert() {878 WebDriver drv = getDriver();879 long retryInterval = getRetryInterval(EXPLICIT_TIMEOUT);880 Wait<WebDriver> wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, retryInterval);881 try {882 wait.until((Function<WebDriver, Object>) dr -> isAlertPresent());883 drv.switchTo().alert().accept();884 Messager.ALERT_ACCEPTED.info("");885 } catch (Exception e) {886 Messager.ALERT_NOT_ACCEPTED.error("");887 }888 }889 /**890 * Cancels alert modal.891 */892 public void cancelAlert() {893 WebDriver drv = getDriver();894 long retryInterval = getRetryInterval(EXPLICIT_TIMEOUT);895 Wait<WebDriver> wait = new WebDriverWait(drv, EXPLICIT_TIMEOUT, retryInterval);896 try {897 wait.until((Function<WebDriver, Object>) dr -> isAlertPresent());898 drv.switchTo().alert().dismiss();899 Messager.ALERT_CANCELED.info("");900 } catch (Exception e) {901 Messager.ALERT_NOT_CANCELED.error("");902 }903 }904 /**905 * Checks that alert modal is shown.906 * 907 * @return whether the alert modal present.908 */909 public boolean isAlertPresent() {910 try {911 getDriver().switchTo().alert();912 return true;913 } catch (NoAlertPresentException Ex) {914 return false;915 }916 }917 // --------------------------------------------------------------------------918 // Methods from v1.0919 // --------------------------------------------------------------------------920 public boolean isPageOpened(final AbstractPage page) {921 return isPageOpened(page, EXPLICIT_TIMEOUT);922 }923 public boolean isPageOpened(final AbstractPage page, long timeout) {924 boolean result;925 final WebDriver drv = getDriver();926 927 long retryInterval = getRetryInterval(timeout); 928 Wait<WebDriver> wait = new WebDriverWait(drv, timeout, retryInterval);929 try {930 wait.until((Function<WebDriver, Object>) dr -> LogicUtils.isURLEqual(page.getPageURL(), drv.getCurrentUrl()));931 result = true;932 } catch (Exception e) {933 result = false;934 }935 if (!result) {936 LOGGER.warn(String.format("Actual URL differs from expected one. Expected '%s' but found '%s'",937 page.getPageURL(), drv.getCurrentUrl()));938 }939 return result;940 }941 /**942 * Executes a script on an element943 * 944 * Really should only be used when the web driver is sucking at exposing945 * functionality natively946 * 947 * @param script948 * The script to execute949 * @param element950 * The target of the script, referenced as arguments[0]951 * 952 * @return Object953 */954 public Object trigger(String script, WebElement element) {955 return ((JavascriptExecutor) getDriver()).executeScript(script, element);956 }957 /**958 * Executes a script959 * 960 * Really should only be used when the web driver is sucking at exposing961 * functionality natively962 * 963 * @param script964 * The script to execute965 * 966 * @return Object967 */968 public Object trigger(String script) {969 return ((JavascriptExecutor) getDriver()).executeScript(script);970 }971 /**972 * Opens a new tab for the given URL973 * 974 * @param url975 * The URL to976 * @throws RuntimeException977 * If unable to open tab978 */979 public void openTab(String url) {980 final String decryptedURL = cryptoTool.decryptByPattern(url, CRYPTO_PATTERN);981 String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";982 Object element = trigger(String.format(script, decryptedURL));983 if (element instanceof WebElement) {984 WebElement anchor = (WebElement) element;985 anchor.click();986 trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);987 } else {988 throw new RuntimeException("Unable to open tab");989 }990 }991 public void switchWindow() throws NoSuchWindowException {992 WebDriver drv = getDriver();993 Set<String> handles = drv.getWindowHandles();994 String current = drv.getWindowHandle();995 if (handles.size() > 1) {996 handles.remove(current);997 }998 String newTab = handles.iterator().next();999 drv.switchTo().window(newTab);1000 }1001 // --------------------------------------------------------------------------1002 // Base UI validations1003 // --------------------------------------------------------------------------1004 public void assertElementPresent(final ExtendedWebElement extWebElement) {1005 assertElementPresent(extWebElement, EXPLICIT_TIMEOUT);1006 }1007 public void assertElementPresent(final ExtendedWebElement extWebElement, long timeout) {1008 extWebElement.assertElementPresent(timeout);1009 }1010 public void assertElementWithTextPresent(final ExtendedWebElement extWebElement, final String text) {1011 assertElementWithTextPresent(extWebElement, text, EXPLICIT_TIMEOUT);1012 }1013 public void assertElementWithTextPresent(final ExtendedWebElement extWebElement, final String text, long timeout) {1014 extWebElement.assertElementWithTextPresent(text, timeout);1015 }1016 // --------------------------------------------------------------------------1017 // Helpers1018 // --------------------------------------------------------------------------1019 1020 /**1021 * Find Extended Web Element on page using By.1022 * 1023 * @deprecated1024 * @param by1025 * Selenium By locator1026 * @return ExtendedWebElement if exists otherwise null.1027 */1028 @Deprecated(since = "7.4.21", forRemoval = true)1029 public ExtendedWebElement findExtendedWebElement(By by) {1030 return findExtendedWebElement(by, by.toString(), EXPLICIT_TIMEOUT);1031 }1032 /**1033 * Find Extended Web Element on page using By.1034 *1035 * @deprecated1036 * @param by1037 * Selenium By locator1038 * @param timeout to wait1039 * @return ExtendedWebElement if exists otherwise null.1040 */1041 @Deprecated(since = "7.4.21", forRemoval = true)1042 public ExtendedWebElement findExtendedWebElement(By by, long timeout) {1043 return findExtendedWebElement(by, by.toString(), timeout);1044 }1045 /**1046 * Find Extended Web Element on page using By.1047 * 1048 * @deprecated1049 * @param by1050 * Selenium By locator1051 * @param name1052 * Element name1053 * @return ExtendedWebElement if exists otherwise null.1054 */1055 @Deprecated(since = "7.4.21", forRemoval = true)1056 public ExtendedWebElement findExtendedWebElement(final By by, String name) {1057 return findExtendedWebElement(by, name, EXPLICIT_TIMEOUT);1058 }1059 /**1060 * Find Extended Web Element on page using By.1061 *1062 * @deprecated1063 * @param by1064 * Selenium By locator1065 * @param name1066 * Element name1067 * @param timeout1068 * Timeout to find1069 * @return ExtendedWebElement if exists otherwise null.1070 */1071 @Deprecated(since = "7.4.21", forRemoval = true)1072 public ExtendedWebElement findExtendedWebElement(final By by, String name, long timeout) {1073 DriverListener.setMessages(Messager.ELEMENT_FOUND.getMessage(name),1074 Messager.ELEMENT_NOT_FOUND.getMessage(name));1075 1076 if (!waitUntil(ExpectedConditions.presenceOfElementLocated(by), timeout)) {1077 Messager.ELEMENT_NOT_FOUND.error(name);1078 return null;1079 }1080 return new ExtendedWebElement(by, name, getDriver(), getDriver());1081 }1082 /**1083 * Find List of Extended Web Elements on page using By and explicit timeout.1084 *1085 * @deprecated1086 * @param by1087 * Selenium By locator1088 * @return List of ExtendedWebElement.1089 */1090 @Deprecated(since = "7.4.21", forRemoval = true)1091 public List<ExtendedWebElement> findExtendedWebElements(By by) {1092 return findExtendedWebElements(by, EXPLICIT_TIMEOUT);1093 }1094 /**1095 * Find List of Extended Web Elements on page using By.1096 *1097 * @deprecated1098 * 1099 * @param by1100 * Selenium By locator1101 * @param timeout1102 * Timeout to find1103 * @return List of ExtendedWebElement.1104 */1105 @Deprecated(since = "7.4.21", forRemoval = true)1106 public List<ExtendedWebElement> findExtendedWebElements(final By by, long timeout) {1107 List<ExtendedWebElement> extendedWebElements = new ArrayList<ExtendedWebElement>();1108 List<WebElement> webElements = new ArrayList<WebElement>();1109 String name = "undefined";1110 if (!waitUntil(ExpectedConditions.presenceOfElementLocated(by), timeout)) {1111 Messager.ELEMENT_NOT_FOUND.info(name);1112 return extendedWebElements;1113 }1114 1115 webElements = getDriver().findElements(by);1116 int i = 1;1117 for (WebElement element : webElements) {1118 try {1119 name = element.getText();1120 } catch (Exception e) {1121 /* do nothing and keep 'undefined' for control name */1122 }1123 ExtendedWebElement tempElement = new ExtendedWebElement(element, name);1124 tempElement.setBy(tempElement.generateByForList(by, i));1125 extendedWebElements.add(tempElement); 1126 i++;1127 }1128 return extendedWebElements;1129 }1130 protected void setDriver(WebDriver driver) {1131 this.driver = driver;1132 }1133 public WebDriver getDriver() {1134 if (driver == null) {1135 long currentThreadId = Thread.currentThread().getId();1136 LOGGER.error("There is no any initialized driver for thread: " + currentThreadId);1137 throw new RuntimeException("Driver isn't initialized.");1138 }1139 return driver;1140 }1141 1142 /**1143 * Wait until any condition happens.1144 *1145 * @param condition - ExpectedCondition.1146 * @param timeout - timeout.1147 * @return true if condition happen.1148 */1149 public boolean waitUntil(ExpectedCondition<?> condition, long timeout) {1150 boolean result;1151 long startMillis = 0;1152 final WebDriver drv = getDriver();1153 1154 long retryInterval = getRetryInterval(timeout);1155 Wait<WebDriver> wait = new WebDriverWait(drv, timeout, retryInterval);1156 try {1157 startMillis = System.currentTimeMillis();1158 wait.until(condition);1159 result = true;1160 LOGGER.debug("waitUntil: finished true...");1161 } catch (NoSuchElementException | TimeoutException e) {1162 // don't write exception even in debug mode1163 LOGGER.debug("waitUntil: NoSuchElementException | TimeoutException e..." + condition.toString());1164 result = false;1165 } catch (Exception e) {1166 LOGGER.error("waitUntil: " + condition.toString(), e);1167 result = false;1168 } finally {1169 long timePassed = System.currentTimeMillis() - startMillis;1170 // timePassed is time in ms timeout in sec so we have to adjust1171 if (timePassed > 2 * timeout * 1000) {1172 LOGGER.error("Your retry_interval is too low: " + RETRY_TIME + " ms! Increase it or upgrade your hardware");1173 }1174 }1175 return result;1176 }1177 1178 //TODO: uncomment javadoc when T could be described correctly1179 /*1180 * Method to handle SocketException due to okhttp factory initialization (java client 6.*).1181 * Second execution of the same function works as expected.1182 * 1183 * @param T The expected class of the supplier.1184 * @param supplier Object 1185 * @return result Object 1186 */1187 public <T> T performIgnoreException(Supplier<T> supplier) {1188 try {1189 LOGGER.debug("Command will be performed with the exception ignoring");1190 return supplier.get();1191 } catch (WebDriverException e) {1192 LOGGER.info("Webdriver exception has been fired. One more attempt to execute action.", e);1193 LOGGER.info(supplier.toString());1194 return supplier.get();1195 }1196 1197 }1198 1199 private String getUrl() {1200 String url = "";1201 if (Configuration.getEnvArg(Parameter.URL.getKey()).isEmpty()) {1202 url = Configuration.get(Parameter.URL);1203 } else {1204 url = Configuration.getEnvArg(Parameter.URL.getKey());1205 }1206 return url;1207 }1208 1209 private static void setPageLoadTimeout(WebDriver drv, long timeout) {1210 try {1211 drv.manage().timeouts().pageLoadTimeout(timeout, TimeUnit.SECONDS);1212 } catch (UnsupportedCommandException e) {1213 //TODO: review upcoming appium 2.0 changes...
getUrl
Using AI Code Generation
1String url = DriverHelper.getUrl();2String url = DriverHelper.getUrl();3String url = DriverHelper.getUrl();4String url = DriverHelper.getUrl();5String url = DriverHelper.getUrl();6String url = DriverHelper.getUrl();7String url = DriverHelper.getUrl();8String url = DriverHelper.getUrl();9String url = DriverHelper.getUrl();10String url = DriverHelper.getUrl();11String url = DriverHelper.getUrl();12String url = DriverHelper.getUrl();
getUrl
Using AI Code Generation
1String url = DriverHelper.getUrl();2System.out.println("Current URL is: " + url);3File screenshot = DriverHelper.getScreenshotAs(OutputType.FILE);4System.out.println("Screenshot path is: " + screenshot.getAbsolutePath());5File screenshot = DriverHelper.getScreenshotAs(OutputType.FILE);6System.out.println("Screenshot path is: " + screenshot.getAbsolutePath());7File screenshot = DriverHelper.getScreenshotAs(OutputType.FILE);8System.out.println("Screenshot path is: " + screenshot.getAbsolutePath());9File screenshot = DriverHelper.getScreenshotAs(OutputType.FILE);10System.out.println("Screenshot path is: " + screenshot.getAbsolutePath());11File screenshot = DriverHelper.getScreenshotAs(OutputType.FILE);12System.out.println("Screenshot path is: " + screenshot.getAbsolutePath());13File screenshot = DriverHelper.getScreenshotAs(OutputType.FILE);14System.out.println("Screenshot path is: " + screenshot.getAbsolutePath());15File screenshot = DriverHelper.getScreenshotAs(OutputType.FILE);16System.out.println("Screenshot path is
getUrl
Using AI Code Generation
1String url = DriverHelper.getUrl();2log.info("Current URL is: " + url);3WebDriver driver = DriverHelper.getDriver();4log.info("Driver instance is: " + driver);5String title = DriverHelper.getDriver().getTitle();6log.info("Current page title is: " + title);7log.info("Is page opened: " + isPageOpened);8log.info("Current URL is: " + DriverHelper.getUrl());9DriverHelper.getDriver().navigate().back();10log.info("Current URL is: " + DriverHelper.getUrl());11DriverHelper.getDriver().navigate().forward();12log.info("Current URL is: " + DriverHelper.getUrl());13DriverHelper.getDriver().navigate().refresh();14log.info("Current URL is: " + DriverHelper.getUrl());15DriverHelper.getDriver().close();16log.info("Current URL is: " + DriverHelper.getUrl());17DriverHelper.getDriver().quit();18log.info("Current URL is: " + DriverHelper.getUrl());
getUrl
Using AI Code Generation
1String url = DriverHelper.getUrl();2String title = DriverHelper.getTitle();3WebDriver driver = DriverHelper.getDriver();4WebDriver driver = DriverHelper.getDriver(1000, 800);5WebDriver driver = DriverHelper.getDriver(1000, 800, "firefox");6WebDriver driver = DriverHelper.getDriver(1000, 800, "firefox", new DesiredCapabilities());7WebDriver driver = DriverHelper.getDriver(1000, 800, "firefox", new DesiredCapabilities(), true);
getUrl
Using AI Code Generation
1String url = DriverHelper.getUrl();2System.out.println(url);3System.out.println(DriverHelper.getDriver());4System.out.println(DriverHelper.getDriver());5System.out.println(DriverHelper.getDriver());6System.out.println(DriverHelper.getDriver());7System.out.println(DriverHelper.getDriver());8System.out.println(DriverHelper.getDriver());9System.out.println(DriverHelper.getDriver());10System.out.println(DriverHelper.getDriver());11System.out.println(DriverHelper.getDriver());12System.out.println(DriverHelper.getDriver());
getUrl
Using AI Code Generation
1package com.qaprosoft.carina.demo;2import org.testng.annotations.Test;3import org.testng.Assert;4import org.testng.annotations.Test;5import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;6import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;7import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy;8import com.qaprosoft.carina.core.foundation.webdriver.decorator.PageOpeningStrategy.OpeningStrategy;9import com.qaprosoft.carina.core.foundation.webdriver.listener.DriverListener;10import com.qaprosoft.carina.core.foundation.webdriver.listener.EventFiringDecorator;11import com.qaprosoft.carina.core.foundation.webdriver.listener.EventFiringDecorator.EventHandler;12import com.qaprosoft.carina.core.foundation.webdriver.listener.EventFiringDecorator.EventType;13import com.qaprosoft.carina.core.foundation.webdriver.listener.EventFiringDecorator.PageEvent;14import com.qaprosoft.carina.core.foundation.webdriver.listener.EventFiringDecorator.WaitEvent;15import com.qaprosoft.carina.demo.gui.pages.HomePage;16public class DriverHelperTest {17 public void testDriverHelper() {18 HomePage homePage = new HomePage(getDriver());19 homePage.open();20 System.out.println("Current url: " + DriverHelper.getUrl());21 homePage.open();22 System.out.println("Current url: " + DriverHelper.getUrl());23 }24}25public static String getUrl() {
getUrl
Using AI Code Generation
1String url = DriverHelper.getUrl();2System.out.println("URL of current page: " + url);3String title = DriverHelper.getTitle();4System.out.println("Title of current page: " + title);5String browser = DriverHelper.getBrowser();6System.out.println("Browser name: " + browser);7String platform = DriverHelper.getPlatform();8System.out.println("Platform name: " + platform);9WebDriver driver = DriverHelper.getDriver();10System.out.println("Instance of WebDriver: " + driver);11String currentDate = DateUtils.getCurrentDate();12System.out.println("Current date: " + currentDate);13String currentTime = DateUtils.getCurrentTime();14System.out.println("Current time: " + currentTime);15String currentTimeInSpecificFormat = DateUtils.getCurrentTime("hh:mm:ss");16System.out.println("Current time in specific format: " + currentTimeInSpecificFormat);
getUrl
Using AI Code Generation
1import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4public class DriverHelperExample {5 public static void main(String[] args) {6 WebDriver driver = new ChromeDriver();7 DriverHelper helper = new DriverHelper(driver);8 System.out.println(helper.getUrl());9 driver.quit();10 }11}12import com.qaprosoft.carina.core.foundation.webdriver.DriverHelper;13import org.openqa.selenium.WebDriver;14import org.openqa.selenium.chrome.ChromeDriver;15public class DriverHelperExample {16 public static void main(String[] args) {17 WebDriver driver = new ChromeDriver();18 DriverHelper helper = new DriverHelper(driver);19 System.out.println(helper.getDriver());20 driver.quit();21 }22}23import com.qaprosoft.carina.core.foundation.webdriver.DriverPool;24import org.openqa.selenium.WebDriver;25import org.openqa.selenium.chrome.ChromeDriver;26import org.openqa.selenium.remote.DesiredCapabilities;27public class DriverPoolExample {28 public static void main(String[] args) {29 DesiredCapabilities capabilities = DesiredCapabilities.chrome();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!