Best Carina code snippet using com.qaprosoft.carina.core.foundation.retry.ActionPoller.until
Source:DriverHelper.java
...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");...
Source:APIMethodPoller.java
...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, if...
Source:ActionPoller.java
...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()) {...
until
Using AI Code Generation
1public class ActionPollerUntilExample {2 public static void main(String[] args) {3 ActionPollerUntilExample example = new ActionPollerUntilExample();4 example.untilExample();5 }6 public void untilExample() {7 ActionPollerUntilExample example = new ActionPollerUntilExample();8 example.untilExample();9 }10 public void untilExample() {11 ActionPollerUntilExample example = new ActionPollerUntilExample();12 example.untilExample();13 }14 public void untilExample() {15 ActionPollerUntilExample example = new ActionPollerUntilExample();16 example.untilExample();17 }18}19public class ActionPollerUntilExample {20 public static void main(String[] args) {21 ActionPollerUntilExample example = new ActionPollerUntilExample();22 example.untilExample();23 }24 public void untilExample() {25 ActionPollerUntilExample example = new ActionPollerUntilExample();26 example.untilExample();27 }28 public void untilExample() {29 ActionPollerUntilExample example = new ActionPollerUntilExample();30 example.untilExample();31 }32 public void untilExample() {33 ActionPollerUntilExample example = new ActionPollerUntilExample();34 example.untilExample();35 }36}37public class ActionPollerUntilExample {38 public static void main(String[] args) {39 ActionPollerUntilExample example = new ActionPollerUntilExample();40 example.untilExample();41 }42 public void untilExample() {43 ActionPollerUntilExample example = new ActionPollerUntilExample();44 example.untilExample();45 }46 public void untilExample() {47 ActionPollerUntilExample example = new ActionPollerUntilExample();48 example.untilExample();49 }50 public void untilExample() {51 ActionPollerUntilExample example = new ActionPollerUntilExample();52 example.untilExample();53 }54}55public class ActionPollerUntilExample {56 public static void main(String[] args) {
until
Using AI Code Generation
1public class ActionPoller {2 private static final Logger LOGGER = LoggerFactory.getLogger(ActionPoller.class);3 private static final int DEFAULT_TIMEOUT = 30;4 private static final int DEFAULT_POLLING_INTERVAL = 1;5 private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;6 private static final int DEFAULT_ATTEMPTS = 3;7 private static final String DEFAULT_ERROR_MESSAGE = "Action is not performed!";8 private static final String DEFAULT_SUCCESS_MESSAGE = "Action is performed!";9 private static final String DEFAULT_TIMEOUT_MESSAGE = "Action is not performed during timeout!";10 private static final String DEFAULT_POLLING_INTERVAL_MESSAGE = "Polling interval is not correct!";11 private static final String DEFAULT_ATTEMPTS_MESSAGE = "Attempts count is not correct!";12 private static final String DEFAULT_TIME_UNIT_MESSAGE = "Time unit is not correct!";13 private static final String DEFAULT_ERROR_MESSAGE_MESSAGE = "Error message is not correct!";14 private static final String DEFAULT_SUCCESS_MESSAGE_MESSAGE = "Success message is not correct!";15 private static final String DEFAULT_TIMEOUT_MESSAGE_MESSAGE = "Timeout message is not correct!";16 private static final String DEFAULT_POLLING_INTERVAL_MESSAGE_MESSAGE = "Polling interval message is not correct!";17 private static final String DEFAULT_ATTEMPTS_MESSAGE_MESSAGE = "Attempts message is not correct!";18 private static final String DEFAULT_TIME_UNIT_MESSAGE_MESSAGE = "Time unit message is not correct!";19 private static final String DEFAULT_ERROR_MESSAGE_MESSAGE_MESSAGE = "Error message message is not correct!";20 private static final String DEFAULT_SUCCESS_MESSAGE_MESSAGE_MESSAGE = "Success message message is not correct!";21 private static final String DEFAULT_TIMEOUT_MESSAGE_MESSAGE_MESSAGE = "Timeout message message is not correct!";22 private static final String DEFAULT_POLLING_INTERVAL_MESSAGE_MESSAGE_MESSAGE = "Polling interval message message is not correct!";23 private static final String DEFAULT_ATTEMPTS_MESSAGE_MESSAGE_MESSAGE = "Attempts message message is not correct!";24 private static final String DEFAULT_TIME_UNIT_MESSAGE_MESSAGE_MESSAGE = "Time unit message message is not correct!";25 private static final String DEFAULT_ERROR_MESSAGE_MESSAGE_MESSAGE_MESSAGE = "Error message message message is not correct!";26 private static final String DEFAULT_SUCCESS_MESSAGE_MESSAGE_MESSAGE_MESSAGE = "Success message message message is not correct!";27 private static final String DEFAULT_TIMEOUT_MESSAGE_MESSAGE_MESSAGE_MESSAGE = "Timeout message message message is not correct!";
until
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.support.ui.ExpectedConditions;5import org.openqa.selenium.support.ui.WebDriverWait;6import com.qaprosoft.carina.core.foundation.retry.ActionPoller;7import com.qaprosoft.carina.core.foundation.retry.RetryType;8public class PollerDemo {9 public static void main(String[] args) throws InterruptedException {10 WebDriver driver = new ChromeDriver();11 WebElement element = driver.findElement(By.name("q"));12 ActionPoller.wait(RetryType.FIXED, 10, 1000, ExpectedConditions.visibilityOf(element));13 driver.quit();14 }15}16import org.openqa.selenium.WebDriver;17import org.openqa.selenium.WebElement;18import org.openqa.selenium.chrome.ChromeDriver;19import org.openqa.selenium.support.ui.ExpectedConditions;20import org.openqa.selenium.support.ui.WebDriverWait;21import com.qaprosoft.carina.core.foundation.retry.ActionPoller;22import com.qaprosoft.carina.core.foundation.retry.RetryType;23public class PollerDemo {24 public static void main(String[] args) throws InterruptedException {25 WebDriver driver = new ChromeDriver();26 WebElement element = driver.findElement(By.name("q"));27 ActionPoller.wait(RetryType.FIXED, 10, 1000, ExpectedConditions.elementToBeClickable(element));28 driver.quit();29 }30}31import org.openqa.selenium.WebDriver;32import org.openqa.selenium.WebElement;33import org.openqa.selenium.chrome.ChromeDriver;34import org.openqa.selenium.support.ui.ExpectedConditions;35import org.openqa.selenium.support.ui.WebDriverWait;36import com.qaprosoft.carina.core.foundation.retry.ActionPoller;37import com.qaprosoft.carina.core.foundation.retry.RetryType;38public class PollerDemo {39 public static void main(String[] args) throws InterruptedException {40 WebDriver driver = new ChromeDriver();41 WebElement element = driver.findElement(By.name("q"));42 ActionPoller.wait(RetryType.FIX
until
Using AI Code Generation
1public class 1 {2 public static void main(String[] args) {3 ActionPoller poller = new ActionPoller(30000, 1000);4 poller.until(() -> {5 return true;6 });7 }8}
until
Using AI Code Generation
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 PollerTest {6 @Test(retryAnalyzer = RetryAnalyzer.class)7 public void testUntil() {8 int i = 0;9 int result = ActionPoller.until(() -> {10 System.out.println("i: " + i);11 i++;12 return i;13 }, 5, 2000);14 Assert.assertEquals(result, 5, "Result is not as expected");15 }16}
until
Using AI Code Generation
1public class RetryUntilVisible {2 public static void main(String[] args) {3 WebDriver driver = new FirefoxDriver();4 WebElement element = driver.findElement(By.name("q"));5 ActionPoller.poller().until(element, "isDisplayed", true);6 driver.quit();7 }8}9public class RetryUntilVisible {10 public static void main(String[] args) {11 WebDriver driver = new FirefoxDriver();12 WebElement element = driver.findElement(By.name("q"));13 ActionPoller.poller().until(element, "isDisplayed", true);14 driver.quit();15 }16}17public class RetryUntilVisible {18 public static void main(String[] args) {19 WebDriver driver = new FirefoxDriver();20 WebElement element = driver.findElement(By.name("q"));21 ActionPoller.poller().until(element, "isDisplayed", true);22 driver.quit();23 }24}25public class RetryUntilVisible {26 public static void main(String[] args) {27 WebDriver driver = new FirefoxDriver();28 WebElement element = driver.findElement(By.name("q"));29 ActionPoller.poller().until(element, "isDisplayed", true);30 driver.quit();31 }32}33public class RetryUntilVisible {34 public static void main(String[] args) {35 WebDriver driver = new FirefoxDriver();36 WebElement element = driver.findElement(By.name("q"));37 ActionPoller.poller().until(element, "isDisplayed", true);38 driver.quit();39 }40}
until
Using AI Code Generation
1public class ActionPoller {2 public static void until(String action, int attempts, int timeout, int delay, String errorMessage, String successMessage) {3 boolean success = false;4 int attempt = 1;5 while (!success && attempt <= attempts) {6 try {7 success = Boolean.parseBoolean(action);8 } catch (Exception e) {9 LOGGER.info("Attempt " + attempt + " failed with error: " + e.getMessage());10 }11 if (success) {12 LOGGER.info(successMessage);13 break;14 } else {15 LOGGER.info("Attempt " + attempt + " failed. Retrying after " + delay + " seconds...");16 try {17 Thread.sleep(delay * 1000);18 } catch (InterruptedException e) {19 LOGGER.error("Interrupted exception: " + e.getMessage());20 }21 }22 attempt++;23 }24 if (!success) {25 Assert.fail(errorMessage);26 }27 }28}29public class ActionPoller {30 public static void until(String action, int attempts, int timeout, int delay, String errorMessage, String successMessage) {31 boolean success = false;32 int attempt = 1;33 while (!success && attempt <= attempts) {34 try {35 success = Boolean.parseBoolean(action);36 } catch (Exception e) {37 LOGGER.info("Attempt " + attempt + " failed with error: " + e.getMessage());38 }39 if (success) {40 LOGGER.info(successMessage);41 break;42 } else {43 LOGGER.info("Attempt " + attempt + " failed. Retrying after " + delay + " seconds...");44 try {45 Thread.sleep(delay * 1000);46 } catch (InterruptedException e) {47 LOGGER.error("Interrupted exception: " + e.getMessage());48 }49 }50 attempt++;51 }52 if (!success) {53 Assert.fail(errorMessage);54 }55 }56}57public class ActionPoller {58 public static void until(String action, int attempts, int timeout, int delay, String errorMessage, String successMessage) {59 boolean success = false;60 int attempt = 1;61 while (!success && attempt <= attempts) {62 try {63 success = Boolean.parseBoolean(action);64 } catch (Exception
until
Using AI Code Generation
1public class 1 {2 public void test() {3 WebDriver driver = new ChromeDriver();4 WebElement element = ActionPoller.until(10, 1, "Google search button is not present", 5 () -> driver.findElement(By.name("q")));6 element.sendKeys("Carina");7 driver.quit();8 }9}10public class 2 {11 public void test() {12 WebDriver driver = new ChromeDriver();13 WebElement element = ActionPoller.until(10, 1, "Google search button is not present", 14 () -> driver.findElement(By.name("q")));15 element.sendKeys("Carina");16 driver.quit();17 }18}19public class 3 {20 public void test() {21 WebDriver driver = new ChromeDriver();
until
Using AI Code Generation
1package com.qaprosoft.carina.core.foundation.retry;2import java.util.function.Supplier;3import org.apache.log4j.Logger;4import com.qaprosoft.carina.core.foundation.utils.R;5public class ActionPoller {6 private static final Logger LOGGER = Logger.getLogger(ActionPoller.class);7 public static void until(String actionName, Supplier<Boolean> condition) {8 until(actionName, R.CONFIG.getInt("polling_timeout"), condition);9 }10 public static void until(String actionName, int timeout, Supplier<Boolean> condition) {11 int pollingInterval = R.CONFIG.getInt("polling_interval");12 long startTime = System.currentTimeMillis();13 long endTime = startTime + timeout * 1000;14 long currentTime = startTime;15 boolean conditionResult = condition.get();16 while (!conditionResult && currentTime < endTime) {17 LOGGER.info(actionName + " is not completed yet. Waiting " + pollingInterval + " sec...");18 try {19 Thread.sleep(pollingInterval * 1000);20 } catch (InterruptedException e) {21 LOGGER.error("Thread was interrupted!", e);22 break;23 }24 currentTime = System.currentTimeMillis();25 conditionResult = condition.get();26 }27 if (conditionResult) {28 LOGGER.info(actionName + " was completed successfully!");29 } else {30 LOGGER.error(actionName + " was not completed after " + timeout + " sec!");31 }32 }33}34package com.qaprosoft.carina.core.foundation.retry;35import java.util.function.Supplier;36import org.apache.log4j.Logger;37import com.qaprosoft.carina.core.foundation.utils.R;38public class ActionPoller {39 private static final Logger LOGGER = Logger.getLogger(ActionPoller.class);40 public static void until(String actionName, Supplier<Boolean> condition) {41 until(actionName, R.CONFIG.getInt("polling_timeout"), condition);42 }43 public static void until(String actionName, int timeout, Supplier<Boolean
until
Using AI Code Generation
1public class WaitUntilElementToBeVisible {2 public static void main(String[] args) {3 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");4 WebDriver driver = new ChromeDriver();5 driver.manage().window().maximize();6 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);7 ActionPoller.poll(10, 1, () -> {8 WebElement email = driver.findElement(By.id("email"));9 if(email.isDisplayed()) {10 email.sendKeys("
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!!