How to use execute method of com.qaprosoft.carina.core.foundation.retry.ActionPoller class

Best Carina code snippet using com.qaprosoft.carina.core.foundation.retry.ActionPoller.execute

Source:DriverHelper.java Github

copy

Full Screen

...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;...

Full Screen

Full Screen

Source:APIMethodPoller.java Github

copy

Full Screen

...58 this.logStrategy = logStrategy;59 return this;60 }61 /**62 * Sets an action that will be executed immediately after the api calling63 *64 * @param peekAction lambda expression65 * @return APIMethodPoller object66 */67 public APIMethodPoller peek(Consumer<Response> peekAction) {68 actionPoller.peek(peekAction);69 return this;70 }71 /**72 * Sets the condition under which the api calling is considered successfully completed and the response is returned73 *74 * @param successCondition lambda expression that that should return true if we consider the api calling completed75 * successfully, and false if not76 * @return APIMethodPoller object77 */78 public APIMethodPoller until(Predicate<Response> successCondition) {79 this.actionPoller.until(successCondition);80 return this;81 }82 /**83 * Sets an action that will be executed after an api calling84 *85 * @param afterExecuteAction lambda expression86 * @return APIMethodPoller object87 */88 APIMethodPoller doAfterExecute(Consumer<Response> afterExecuteAction) {89 this.afterExecuteAction = afterExecuteAction;90 return this;91 }92 /**93 * Starts an api calling repetition with a condition. if the condition is met, then the method returns response, otherwise, if94 * the time was elapsed, the method returns null95 *96 * @return response if condition successful, otherwise null97 */98 public Optional<Response> execute() {99 if (logStrategy == null) {100 logStrategy = LogStrategy.ALL;101 }102 Predicate<Response> logCondition = recognizeLogCondition(logStrategy);103 ConditionalLoggingOutputStream outputStream = new ConditionalLoggingOutputStream(LOGGER, Level.INFO);104 outputStream.setLogCondition(logCondition);105 Optional<Response> maybeResponse = actionPoller.task(() -> {106 method.request.noFilters();107 outputStream.setBytesOfStreamInvalid();108 return method.callAPI(outputStream);109 })110 .peek(outputStream::conditionLogging)111 .execute();112 if (LogStrategy.LAST_ONLY.equals(logStrategy) && maybeResponse.isEmpty()) {113 outputStream.flush();114 }115 outputStream.close();116 if (afterExecuteAction != null && maybeResponse.isPresent()) {117 afterExecuteAction.accept(maybeResponse.get());118 }119 return maybeResponse;120 }121 private Predicate<Response> recognizeLogCondition(LogStrategy logStrategy) {122 Predicate<Response> result;123 switch (logStrategy) {124 case ALL:125 result = rs -> true;...

Full Screen

Full Screen

Source:ActionPoller.java Github

copy

Full Screen

...47 this.timeout = Duration.of(timeout, timeUnit);48 return this;49 }50 /**51 * Adds an action that will be executed immediately after the task52 *53 * @param peekAction lambda expression54 * @return ActionPoller object55 */56 public ActionPoller<T> peek(Consumer<T> peekAction) {57 this.peekActions.add(peekAction);58 return this;59 }60 /**61 * Sets the task to repeat62 *63 * @param task lambda expression64 * @return ActionPoller object65 */66 public ActionPoller<T> task(Supplier<T> task) {67 this.task = task;68 return this;69 }70 /**71 * Sets the condition under which the task is considered successfully completed and the result is returned72 *73 * @param successCondition lambda expression that that should return true if we consider the task completed74 * successfully, and false if not75 * @return ActionPoller object76 */77 public ActionPoller<T> until(Predicate<T> successCondition) {78 this.successCondition = successCondition;79 return this;80 }81 /**82 * Starts a task repetition with a condition. if the condition is met, then the method returns result, otherwise, if83 * the time was elapsed, the method returns null84 *85 * @return result of the task method if condition successful, otherwise returns null86 */87 public Optional<T> execute() {88 validateParameters();89 AtomicBoolean stopExecution = setupTerminateTask();90 T result = null;91 while (!stopExecution.get()) {92 T tempResult = task.get();93 peekActions.forEach(peekAction -> peekAction.accept(tempResult));94 if (successCondition.test(tempResult)) {95 result = tempResult;96 break;97 }98 CommonUtils.pause(pollingInterval.getSeconds());99 }100 return Optional.ofNullable(result);101 }102 private AtomicBoolean setupTerminateTask() {103 AtomicBoolean stopExecution = new AtomicBoolean();104 Timer timer = new Timer();105 timer.schedule(new TimerTask() {106 @Override107 public void run() {108 stopExecution.set(true);109 timer.cancel();110 timer.purge();111 }112 }, timeout.toMillis());113 return stopExecution;114 }115 private void validateParameters() {116 if (task == null) {117 throw new IllegalArgumentException("Unable to execute without task.");118 }119 if (successCondition == null) {120 throw new IllegalArgumentException("Unable to execute without success condition.");121 }122 if (timeout.toMillis() < pollingInterval.toMillis()) {123 throw new IllegalArgumentException("Timeout cannot be less than polling interval");124 }125 if (timeout.isNegative() || pollingInterval.isNegative()) {126 throw new IllegalArgumentException("Timeout or polling interval can't be negative");127 }128 }129 public Predicate<T> getSuccessCondition() {130 return successCondition;131 }132}...

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.retry.ActionPoller;2import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;3import org.testng.Assert;4import org.testng.annotations.Test;5public class Test1 {6@Test(retryAnalyzer = RetryAnalyzer.class)7public void test1() {8 ActionPoller.pollAction(() -> {9 Assert.assertTrue(false);10 }, 10, 1000);11}12}13import com.qaprosoft.carina.core.foundation.retry.ActionPoller;14import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;15import org.testng.Assert;16import org.testng.annotations.Test;17public class Test2 {18@Test(retryAnalyzer = RetryAnalyzer.class)19public void test2() {20 ActionPoller.pollAction(() -> {21 Assert.assertTrue(false);22 }, 10, 1000);23}24}25import com.qaprosoft.carina.core.foundation.retry.ActionPoller;26import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;27import org.testng.Assert;28import org.testng.annotations.Test;29public class Test3 {30@Test(retryAnalyzer = RetryAnalyzer.class)31public void test3() {32 ActionPoller.pollAction(() -> {33 Assert.assertTrue(false);34 }, 10, 1000);35}36}37import com.qaprosoft.carina.core.foundation.retry.ActionPoller;38import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;39import org.testng.Assert;40import org.testng.annotations.Test;41public class Test4 {42@Test(retryAnalyzer = RetryAnalyzer.class)43public void test4() {44 ActionPoller.pollAction(() -> {45 Assert.assertTrue(false);46 }, 10, 1000);47}48}49import com.qaprosoft.carina.core.foundation.retry.ActionPoller;50import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;51import org.testng.Assert;52import org.testng.annotations.Test;53public class Test5 {54@Test(retryAnalyzer = Retry

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.retry.ActionPoller;2import com.qaprosoft.carina.core.foundation.retry.IAction;3public class 1 {4 public static void main(String[] args) {5 ActionPoller poller = new ActionPoller(10, 1000);6 poller.execute(new IAction() {7 public boolean execute() {8 System.out.println("Hello");9 return true;10 }11 });12 }13}14import com.qaprosoft.carina.core.foundation.retry.ActionPoller;15import com.qaprosoft.carina.core.foundation.retry.IAction;16public class 2 {17 public static void main(String[] args) {18 ActionPoller poller = new ActionPoller(10, 1000);19 poller.execute(new IAction() {20 public boolean execute() {21 System.out.println("Hello");22 return false;23 }24 });25 }26}27import com.qaprosoft.carina.core.foundation.retry.ActionPoller;28import com.qaprosoft.carina.core.foundation.retry.IAction;29public class 3 {30 public static void main(String[] args) {31 ActionPoller poller = new ActionPoller(10, 1000);32 poller.execute(new IAction() {33 public boolean execute() {34 System.out.println("Hello");35 return true;36 }37 });38 }39}40import com.qaprosoft.carina.core.foundation.retry.ActionPoller;41import com.qaprosoft.carina.core.foundation.retry.IAction;42public class 4 {43 public static void main(String[] args) {44 ActionPoller poller = new ActionPoller(10, 1000);45 poller.execute(new IAction() {46 public boolean execute() {47 System.out.println("Hello");48 return false;

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1package com.qaprosoft.carina.core.foundation.retry;2import java.util.concurrent.TimeUnit;3import org.testng.Assert;4public class ActionPollerTest {5public static void main(String[] args) {6ActionPoller poller = new ActionPoller(1, TimeUnit.SECONDS);7poller.execute(() -> {8System.out.println("Polling action");9Assert.fail();10});11}12}13package com.qaprosoft.carina.core.foundation.retry;14import java.util.concurrent.TimeUnit;15import org.testng.Assert;16public class ActionPollerTest2 {17public static void main(String[] args) {18ActionPoller poller = new ActionPoller(1, TimeUnit.SECONDS);19poller.execute(() -> {20System.out.println("Polling action");21Assert.fail();22});23}24}25package com.qaprosoft.carina.core.foundation.retry;26import java.util.concurrent.TimeUnit;27import org.testng.Assert;28public class ActionPollerTest3 {29public static void main(String[] args) {30ActionPoller poller = new ActionPoller(1, TimeUnit.SECONDS);31poller.execute(() -> {32System.out.println("Polling action");33Assert.fail();34});35}36}37package com.qaprosoft.carina.core.foundation.retry;38import java.util.concurrent.TimeUnit;39import org.testng.Assert;40public class ActionPollerTest4 {41public static void main(String[] args) {42ActionPoller poller = new ActionPoller(1, TimeUnit.SECONDS);43poller.execute(() -> {44System.out.println("Polling action");45Assert.fail();46});47}48}49package com.qaprosoft.carina.core.foundation.retry;50import java.util.concurrent.TimeUnit;51import org.testng.Assert;52public class ActionPollerTest5 {53public static void main(String[] args) {54ActionPoller poller = new ActionPoller(1, TimeUnit.SECONDS);55poller.execute(() -> {56System.out.println("Polling action");57Assert.fail();58});59}60}61package com.qaprosoft.carina.core.foundation.retry;62import java.util.concurrent.TimeUnit;63import org.testng.Assert;64public class ActionPollerTest6 {65public static void main(String[] args) {66ActionPoller poller = new ActionPoller(1, TimeUnit.SECONDS);67poller.execute(() -> {68System.out.println("Polling action");69Assert.fail();70});71}72}73package com.qaprosoft.carina.core.foundation.retry;74import java

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.retry.ActionPoller;2import com.qaprosoft.carina.core.foundation.retry.IAction;3public class ActionPollerDemo {4public static void main(String[] args) {5ActionPoller poller = new ActionPoller(10, 100);6poller.execute(new IAction() {7public boolean doAction() {8System.out.println("Executing action");9return true;10}11});12}13}14import com.qaprosoft.carina.core.foundation.retry.ActionPoller;15import com.qaprosoft.carina.core.foundation.retry.IAction;16public class ActionPollerDemo {17public static void main(String[] args) {18ActionPoller poller = new ActionPoller(10, 100);19poller.execute(new IAction() {20public boolean doAction() {21System.out.println("Executing action");22return false;23}24});25}26}27import com.qaprosoft.carina.core.foundation.retry.ActionPoller;28import com.qaprosoft.carina.core.foundation.retry.IAction;29public class ActionPollerDemo {30public static void main(String[] args) {31ActionPoller poller = new ActionPoller(10, 100);32poller.execute(new IAction() {33public boolean doAction() {34System.out.println("Executing action");35return false;36}37}, 5);38}39}40import com.qaprosoft.carina.core.foundation.retry.ActionPoller;41import com.qaprosoft.carina.core.foundation.retry.IAction;42public class ActionPollerDemo {43public static void main(String[] args) {44ActionPoller poller = new ActionPoller(10, 100);45poller.execute(new IAction() {46public boolean doAction() {47System.out.println("Executing action");48return false;49}50}, 5, 10);51}52}53import com.qaprosoft.carina.core.foundation.retry.ActionPoller;54import com.qaprosoft.carina

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import com.qaprosoft.carina.core.foundation.retry.ActionPoller;2public class Retry {3public static void main(String[] args) {4ActionPoller poller = new ActionPoller();5poller.setPollingInterval(1000);6poller.setPollingTimeout(10000);7poller.setPollingAction(new Action() {8public boolean doAction() {9System.out.println("Polling...");10return false;11}12});13poller.execute();14}15}

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1public static void main(String[] args) {2 ActionPoller poller = new ActionPoller(20, 1000);3 poller.execute(new Action() {4 public boolean action() {5 return true;6 }7 });8}9public static void main(String[] args) {10 ActionPoller poller = new ActionPoller(20, 1000);11 poller.execute(new Action() {12 public boolean action() {13 return false;14 }15 });16}17public static void main(String[] args) {18 ActionPoller poller = new ActionPoller(20, 1000);19 poller.execute(new Action() {20 public boolean action() {21 return true;22 }23 });24}25public static void main(String[] args) {26 ActionPoller poller = new ActionPoller(20, 1000);27 poller.execute(new Action() {28 public boolean action() {29 return false;30 }31 });32}33public static void main(String[] args) {34 ActionPoller poller = new ActionPoller(20, 1000);35 poller.execute(new Action() {36 public boolean action() {37 return true;38 }39 });40}41public static void main(String[] args) {42 ActionPoller poller = new ActionPoller(20, 1000);43 poller.execute(new Action() {44 public boolean action() {45 return false;46 }47 });48}49public static void main(String[]

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import org.testng.annotations.Test;2import org.testng.Assert;3import com.qaprosoft.carina.core.foundation.retry.ActionPoller;4import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;5public class ExecuteTest {6 @Test(retryAnalyzer = RetryAnalyzer.class)7 public void executeTest() {8 ActionPoller.execute(3, () -> {9 System.out.println("Executing action");10 Assert.assertTrue(false);11 });12 }13}14import org.testng.annotations.Test;15import org.testng.Assert;16import com.qaprosoft.carina.core.foundation.retry.ActionPoller;17import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;18public class ExecuteTest {19 @Test(retryAnalyzer = RetryAnalyzer.class)20 public void executeTest() {21 ActionPoller.execute(3, 5, () -> {22 System.out.println("Executing action");23 Assert.assertTrue(false);24 });25 }26}27import org.testng.annotations.Test;28import org.testng.Assert;29import com.qaprosoft.carina.core.foundation.retry.ActionPoller;30import com.qaprosoft.carina.core.foundation.retry.RetryAnalyzer;31public class ExecuteTest {32 @Test(retryAnalyzer = RetryAnalyzer.class)33 public void executeTest() {34 ActionPoller.execute(3, 5, "Action failed", () -> {35 System.out.println("Executing action");36 Assert.assertTrue(false);37 });38 }39}

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1public class Poller {2 public static void main(String[] args) {3 System.out.println("main");4 ActionPoller poller = new ActionPoller();5 poller.execute(new Action() {6 public void perform() {7 System.out.println("perform");8 }9 }, 5, 1000);10 }11}12public class Poller {13 public static void main(String[] args) {14 System.out.println("main");15 ActionPoller poller = new ActionPoller();16 poller.execute(new Action() {17 public void perform() {18 System.out.println("perform");19 }20 }, 5, 1000);21 }22}23public class Poller {24 public static void main(String[] args) {25 System.out.println("main");26 ActionPoller poller = new ActionPoller();27 poller.execute(new Action() {28 public void perform() {29 System.out.println("perform");30 }31 }, 5, 1000);32 }33}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Carina automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful