How to use execute method of org.openqa.selenium.remote.tracing.TracedHttpClient class

Best Selenium code snippet using org.openqa.selenium.remote.tracing.TracedHttpClient.execute

Source:RemoteWebDriver.java Github

copy

Full Screen

...103 private CommandExecutor executor;104 private Capabilities capabilities;105 private SessionId sessionId;106 private FileDetector fileDetector = new UselessFileDetector();107 private ExecuteMethod executeMethod;108 private JsonToWebElementConverter converter;109 private RemoteKeyboard keyboard;110 private RemoteMouse mouse;111 private Logs remoteLogs;112 private LocalLogs localLogs;113 // For cglib114 protected RemoteWebDriver() {115 this.capabilities = init(new ImmutableCapabilities());116 }117 private static URL getDefaultServerURL() {118 try {119 return new URL(System.getProperty("webdriver.remote.server", "http://localhost:4444/"));120 } catch (MalformedURLException e) {121 throw new WebDriverException(e);122 }123 }124 public RemoteWebDriver(Capabilities capabilities) {125 this(getDefaultServerURL(),126 Require.nonNull("Capabilities", capabilities));127 }128 public RemoteWebDriver(URL remoteAddress, Capabilities capabilities) {129 this(createTracedExecutorWithTracedHttpClient(Require.nonNull("Server URL", remoteAddress)),130 Require.nonNull("Capabilities", capabilities));131 }132 private static CommandExecutor createTracedExecutorWithTracedHttpClient(URL remoteAddress) {133 Tracer tracer = OpenTelemetryTracer.getInstance();134 CommandExecutor executor = new HttpCommandExecutor(135 Collections.emptyMap(),136 ClientConfig.defaultConfig().baseUrl(remoteAddress),137 new TracedHttpClient.Factory(tracer, HttpClient.Factory.createDefault()));138 return new TracedCommandExecutor(executor, tracer);139 }140 public RemoteWebDriver(CommandExecutor executor, Capabilities capabilities) {141 this.executor = Require.nonNull("Command executor", executor);142 capabilities = init(capabilities);143 if (executor instanceof NeedsLocalLogs) {144 ((NeedsLocalLogs) executor).setLocalLogs(localLogs);145 }146 try {147 startSession(capabilities);148 } catch (RuntimeException e) {149 try {150 quit();151 } catch (Exception ignored) {152 // Ignore the clean-up exception. We'll propagate the original failure.153 }154 throw e;155 }156 }157 @Beta158 public static RemoteWebDriverBuilder builder() {159 return new RemoteWebDriverBuilder();160 }161 private Capabilities init(Capabilities capabilities) {162 capabilities = capabilities == null ? new ImmutableCapabilities() : capabilities;163 logger.addHandler(LoggingHandler.getInstance());164 converter = new JsonToWebElementConverter(this);165 executeMethod = new RemoteExecuteMethod(this);166 keyboard = new RemoteKeyboard(executeMethod);167 mouse = new RemoteMouse(executeMethod);168 ImmutableSet.Builder<String> builder = new ImmutableSet.Builder<>();169 boolean isProfilingEnabled = capabilities.is(CapabilityType.ENABLE_PROFILING_CAPABILITY);170 if (isProfilingEnabled) {171 builder.add(LogType.PROFILER);172 }173 LoggingPreferences mergedLoggingPrefs = new LoggingPreferences();174 mergedLoggingPrefs.addPreferences((LoggingPreferences) capabilities.getCapability(LOGGING_PREFS));175 if (!mergedLoggingPrefs.getEnabledLogTypes().contains(LogType.CLIENT) ||176 mergedLoggingPrefs.getLevel(LogType.CLIENT) != Level.OFF) {177 builder.add(LogType.CLIENT);178 }179 Set<String> logTypesToInclude = builder.build();180 LocalLogs performanceLogger = LocalLogs.getStoringLoggerInstance(logTypesToInclude);181 LocalLogs clientLogs = LocalLogs.getHandlerBasedLoggerInstance(182 LoggingHandler.getInstance(), logTypesToInclude);183 localLogs = LocalLogs.getCombinedLogsHolder(clientLogs, performanceLogger);184 remoteLogs = new RemoteLogs(executeMethod, localLogs);185 return capabilities;186 }187 /**188 * Set the file detector to be used when sending keyboard input. By default, this is set to a file189 * detector that does nothing.190 *191 * @param detector The detector to use. Must not be null.192 * @see FileDetector193 * @see LocalFileDetector194 * @see UselessFileDetector195 */196 public void setFileDetector(FileDetector detector) {197 if (detector == null) {198 throw new WebDriverException("You may not set a file detector that is null");199 }200 fileDetector = detector;201 }202 @Override203 public SessionId getSessionId() {204 return sessionId;205 }206 protected void setSessionId(String opaqueKey) {207 sessionId = new SessionId(opaqueKey);208 }209 protected void startSession(Capabilities capabilities) {210 Response response = execute(DriverCommand.NEW_SESSION(singleton(capabilities)));211 if (response == null) {212 throw new SessionNotCreatedException(213 "The underlying command executor returned a null response.");214 }215 Object responseValue = response.getValue();216 if (responseValue == null) {217 throw new SessionNotCreatedException(218 "The underlying command executor returned a response without payload: " +219 response.toString());220 }221 if (!(responseValue instanceof Map)) {222 throw new SessionNotCreatedException(223 "The underlying command executor returned a response with a non well formed payload: " +224 response.toString());225 }226 @SuppressWarnings("unchecked") Map<String, Object> rawCapabilities = (Map<String, Object>) responseValue;227 MutableCapabilities returnedCapabilities = new MutableCapabilities(rawCapabilities);228 String platformString = (String) rawCapabilities.getOrDefault(229 PLATFORM,230 rawCapabilities.get(PLATFORM_NAME));231 Platform platform;232 try {233 if (platformString == null || "".equals(platformString)) {234 platform = Platform.ANY;235 } else {236 platform = Platform.fromString(platformString);237 }238 } catch (WebDriverException e) {239 // The server probably responded with a name matching the os.name240 // system property. Try to recover and parse this.241 platform = Platform.extractFromSysProperty(platformString);242 }243 returnedCapabilities.setCapability(PLATFORM, platform);244 returnedCapabilities.setCapability(PLATFORM_NAME, platform);245 if (rawCapabilities.containsKey(SUPPORTS_JAVASCRIPT)) {246 Object raw = rawCapabilities.get(SUPPORTS_JAVASCRIPT);247 if (raw instanceof String) {248 returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, Boolean.parseBoolean((String) raw));249 } else if (raw instanceof Boolean) {250 returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, ((Boolean) raw).booleanValue());251 }252 } else {253 returnedCapabilities.setCapability(SUPPORTS_JAVASCRIPT, true);254 }255 this.capabilities = returnedCapabilities;256 sessionId = new SessionId(response.getSessionId());257 }258 public ErrorHandler getErrorHandler() {259 return errorHandler;260 }261 public void setErrorHandler(ErrorHandler handler) {262 this.errorHandler = handler;263 }264 public CommandExecutor getCommandExecutor() {265 return executor;266 }267 protected void setCommandExecutor(CommandExecutor executor) {268 this.executor = executor;269 }270 @Override271 public Capabilities getCapabilities() {272 if(capabilities == null){273 return new ImmutableCapabilities();274 }275 return capabilities;276 }277 @Override278 public void get(String url) {279 execute(DriverCommand.GET(url));280 }281 @Override282 public String getTitle() {283 Response response = execute(DriverCommand.GET_TITLE);284 Object value = response.getValue();285 return value == null ? "" : value.toString();286 }287 @Override288 public String getCurrentUrl() {289 Response response = execute(DriverCommand.GET_CURRENT_URL);290 if (response == null || response.getValue() == null) {291 throw new WebDriverException("Remote browser did not respond to getCurrentUrl");292 }293 return response.getValue().toString();294 }295 @Override296 public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException {297 Response response = execute(DriverCommand.SCREENSHOT);298 Object result = response.getValue();299 if (result instanceof String) {300 String base64EncodedPng = (String) result;301 return outputType.convertFromBase64Png(base64EncodedPng);302 } else if (result instanceof byte[]) {303 return outputType.convertFromPngBytes((byte[]) result);304 } else {305 throw new RuntimeException(String.format("Unexpected result for %s command: %s",306 DriverCommand.SCREENSHOT,307 result == null ? "null" : result.getClass().getName() + " instance"));308 }309 }310 @Override311 public Pdf print(PrintOptions printOptions) throws WebDriverException {312 Response response = execute(DriverCommand.PRINT_PAGE(printOptions));313 Object result = response.getValue();314 return new Pdf((String) result);315 }316 @Override317 public WebElement findElement(By locator) {318 Require.nonNull("Locator", locator);319 return findElement(this, this, locator);320 }321 WebElement findElement(RemoteWebDriver parent, SearchContext context, By locator) {322 Mechanism mechanism = remotableBys.get(locator.getClass());323 if (mechanism != null) {324 WebElement element = mechanism.findElement(parent, context, locator);325 return massage(parent, context, element, locator);326 }327 // Attempt to find the element remotely328 if (locator instanceof By.Remotable) {329 try {330 WebElement element = Mechanism.REMOTE.findElement(parent, context, locator);331 remotableBys.put(locator.getClass(), Mechanism.REMOTE);332 return massage(parent, context, element, locator);333 } catch (NoSuchElementException e) {334 remotableBys.put(locator.getClass(), Mechanism.REMOTE);335 throw e;336 } catch (InvalidArgumentException e) {337 // Fall through338 }339 }340 try {341 WebElement element = Mechanism.CONTEXT.findElement(parent, context, locator);342 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);343 return massage(parent, context, element, locator);344 } catch (NoSuchElementException e) {345 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);346 throw e;347 }348 }349 @Override350 public List<WebElement> findElements(By locator) {351 Require.nonNull("Locator", locator);352 return findElements(this, this, locator);353 }354 public List<WebElement> findElements(RemoteWebDriver parent, SearchContext context, By locator) {355 Mechanism mechanism = remotableBys.get(locator.getClass());356 if (mechanism != null) {357 List<WebElement> elements = mechanism.findElements(parent, context, locator);358 elements.forEach(e -> massage(parent, context, e, locator));359 return elements;360 }361 // Attempt to find the element remotely362 if (locator instanceof By.Remotable) {363 try {364 List<WebElement> elements = Mechanism.REMOTE.findElements(parent, context, locator);365 remotableBys.put(locator.getClass(), Mechanism.REMOTE);366 elements.forEach(e -> massage(parent, context, e, locator));367 return elements;368 } catch (NoSuchElementException e) {369 remotableBys.put(locator.getClass(), Mechanism.REMOTE);370 throw e;371 } catch (InvalidArgumentException e) {372 // Fall through373 }374 }375 try {376 List<WebElement> elements = Mechanism.CONTEXT.findElements(parent, context, locator);377 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);378 elements.forEach(e -> massage(parent, context, e, locator));379 return elements;380 } catch (NoSuchElementException e) {381 remotableBys.put(locator.getClass(), Mechanism.CONTEXT);382 throw e;383 }384 }385 private WebElement massage(RemoteWebDriver parent, SearchContext context, WebElement element, By locator) {386 if (!(element instanceof RemoteWebElement)) {387 return element;388 }389 RemoteWebElement remoteElement = (RemoteWebElement) element;390 if (locator instanceof By.Remotable) {391 By.Remotable.Parameters params = ((By.Remotable) locator).getRemoteParameters();392 remoteElement.setFoundBy(context, params.using(), String.valueOf(params.value()));393 }394 remoteElement.setFileDetector(parent.getFileDetector());395 remoteElement.setParent(parent);396 return remoteElement;397 }398 /**399 * @deprecated Rely on using {@link By.Remotable} instead400 */401 @Deprecated402 protected WebElement findElement(String by, String using) {403 throw new UnsupportedOperationException("`findElement` has been replaced by usages of " + By.Remotable.class);404 }405 /**406 * @deprecated Rely on using {@link By.Remotable} instead407 */408 @Deprecated409 protected List<WebElement> findElements(String by, String using) {410 throw new UnsupportedOperationException("`findElement` has been replaced by usages of " + By.Remotable.class);411 }412 protected void setFoundBy(SearchContext context, WebElement element, String by, String using) {413 if (element instanceof RemoteWebElement) {414 RemoteWebElement remoteElement = (RemoteWebElement) element;415 remoteElement.setFoundBy(context, by, using);416 remoteElement.setFileDetector(getFileDetector());417 }418 }419 // Misc420 @Override421 public String getPageSource() {422 return (String) execute(DriverCommand.GET_PAGE_SOURCE).getValue();423 }424 @Override425 public void close() {426 execute(DriverCommand.CLOSE);427 }428 @Override429 public void quit() {430 // no-op if session id is null. We're only going to make ourselves unhappy431 if (sessionId == null) {432 return;433 }434 try {435 execute(DriverCommand.QUIT);436 } finally {437 sessionId = null;438 }439 }440 @Override441 @SuppressWarnings({"unchecked"})442 public Set<String> getWindowHandles() {443 Response response = execute(DriverCommand.GET_WINDOW_HANDLES);444 Object value = response.getValue();445 try {446 List<String> returnedValues = (List<String>) value;447 return new LinkedHashSet<>(returnedValues);448 } catch (ClassCastException ex) {449 throw new WebDriverException(450 "Returned value cannot be converted to List<String>: " + value, ex);451 }452 }453 @Override454 public String getWindowHandle() {455 return String.valueOf(execute(DriverCommand.GET_CURRENT_WINDOW_HANDLE).getValue());456 }457 @Override458 public Object executeScript(String script, Object... args) {459 if (!isJavascriptEnabled()) {460 throw new UnsupportedOperationException(461 "You must be using an underlying instance of WebDriver that supports executing javascript");462 }463 // Escape the quote marks464 script = script.replaceAll("\"", "\\\"");465 List<Object> convertedArgs = Stream.of(args).map(new WebElementToJsonConverter()).collect(466 Collectors.toList());467 return execute(DriverCommand.EXECUTE_SCRIPT(script, convertedArgs)).getValue();468 }469 @Override470 public Object executeAsyncScript(String script, Object... args) {471 if (!isJavascriptEnabled()) {472 throw new UnsupportedOperationException("You must be using an underlying instance of " +473 "WebDriver that supports executing javascript");474 }475 // Escape the quote marks476 script = script.replaceAll("\"", "\\\"");477 List<Object> convertedArgs = Stream.of(args).map(new WebElementToJsonConverter()).collect(478 Collectors.toList());479 return execute(DriverCommand.EXECUTE_ASYNC_SCRIPT(script, convertedArgs)).getValue();480 }481 private boolean isJavascriptEnabled() {482 return getCapabilities().is(SUPPORTS_JAVASCRIPT);483 }484 @Override485 public TargetLocator switchTo() {486 return new RemoteTargetLocator();487 }488 @Override489 public Navigation navigate() {490 return new RemoteNavigation();491 }492 @Override493 public Options manage() {494 return new RemoteWebDriverOptions();495 }496 protected void setElementConverter(JsonToWebElementConverter converter) {497 this.converter = Require.nonNull("Element converter", converter);498 }499 protected JsonToWebElementConverter getElementConverter() {500 return converter;501 }502 /**503 * Sets the RemoteWebDriver's client log level.504 *505 * @param level The log level to use.506 */507 public void setLogLevel(Level level) {508 this.level = level;509 logger.setLevel(level);510 }511 protected Response execute(CommandPayload payload) {512 Command command = new Command(sessionId, payload);513 Response response;514 long start = System.currentTimeMillis();515 String currentName = Thread.currentThread().getName();516 Thread.currentThread().setName(517 String.format("Forwarding %s on session %s to remote", command.getName(), sessionId));518 try {519 log(sessionId, command.getName(), command, When.BEFORE);520 response = executor.execute(command);521 log(sessionId, command.getName(), response, When.AFTER);522 if (response == null) {523 return null;524 }525 // Unwrap the response value by converting any JSON objects of the form526 // {"ELEMENT": id} to RemoteWebElements.527 Object value = getElementConverter().apply(response.getValue());528 response.setValue(value);529 } catch (Throwable e) {530 log(sessionId, command.getName(), command, When.EXCEPTION);531 WebDriverException toThrow;532 if (command.getName().equals(DriverCommand.NEW_SESSION)) {533 if (e instanceof SessionNotCreatedException) {534 toThrow = (WebDriverException) e;535 } else {536 toThrow = new SessionNotCreatedException(537 "Possible causes are invalid address of the remote server or browser start-up failure.", e);538 }539 } else if (e instanceof WebDriverException) {540 toThrow = (WebDriverException) e;541 } else {542 toThrow = new UnreachableBrowserException(543 "Error communicating with the remote browser. It may have died.", e);544 }545 populateWebDriverException(toThrow);546 toThrow.addInfo("Command", command.toString());547 throw toThrow;548 } finally {549 Thread.currentThread().setName(currentName);550 }551 try {552 errorHandler.throwIfResponseFailed(response, System.currentTimeMillis() - start);553 } catch (WebDriverException ex) {554 populateWebDriverException(ex);555 ex.addInfo("Command", command.toString());556 throw ex;557 }558 return response;559 }560 private void populateWebDriverException(WebDriverException ex) {561 ex.addInfo(WebDriverException.DRIVER_INFO, this.getClass().getName());562 if (getSessionId() != null) {563 ex.addInfo(WebDriverException.SESSION_ID, getSessionId().toString());564 }565 if (getCapabilities() != null) {566 ex.addInfo("Capabilities", getCapabilities().toString());567 }568 }569 protected Response execute(String driverCommand, Map<String, ?> parameters) {570 return execute(new CommandPayload(driverCommand, parameters));571 }572 protected Response execute(String command) {573 return execute(command, ImmutableMap.of());574 }575 protected ExecuteMethod getExecuteMethod() {576 return executeMethod;577 }578 @Override579 public void perform(Collection<Sequence> actions) {580 execute(DriverCommand.ACTIONS(actions));581 }582 @Override583 public void resetInputState() {584 execute(DriverCommand.CLEAR_ACTIONS_STATE);585 }586 @Override587 public Keyboard getKeyboard() {588 return keyboard;589 }590 @Override591 public Mouse getMouse() {592 return mouse;593 }594 @Override595 public VirtualAuthenticator addVirtualAuthenticator(VirtualAuthenticatorOptions options) {596 String authenticatorId = (String)597 execute(DriverCommand.ADD_VIRTUAL_AUTHENTICATOR, options.toMap()).getValue();598 return new RemoteVirtualAuthenticator(authenticatorId);599 }600 @Override601 public void removeVirtualAuthenticator(VirtualAuthenticator authenticator) {602 execute(DriverCommand.REMOVE_VIRTUAL_AUTHENTICATOR,603 ImmutableMap.of("authenticatorId", authenticator.getId()));604 }605 /**606 * Override this to be notified at key points in the execution of a command.607 *608 * @param sessionId the session id.609 * @param commandName the command that is being executed.610 * @param toLog any data that might be interesting.611 * @param when verb tense of "Execute" to prefix message612 */613 protected void log(SessionId sessionId, String commandName, Object toLog, When when) {614 if (!logger.isLoggable(level)) {615 return;616 }617 String text = String.valueOf(toLog);618 if (commandName.equals(DriverCommand.EXECUTE_SCRIPT)619 || commandName.equals(DriverCommand.EXECUTE_ASYNC_SCRIPT)) {620 if (text.length() > 100 && Boolean.getBoolean("webdriver.remote.shorten_log_messages")) {621 text = text.substring(0, 100) + "...";622 }623 }624 switch(when) {625 case BEFORE:626 logger.log(level, "Executing: " + commandName + " " + text);627 break;628 case AFTER:629 logger.log(level, "Executed: " + text);630 break;631 case EXCEPTION:632 logger.log(level, "Exception: " + text);633 break;634 default:635 logger.log(level, text);636 break;637 }638 }639 public FileDetector getFileDetector() {640 return fileDetector;641 }642 protected class RemoteWebDriverOptions implements Options {643 @Override644 @Beta645 public Logs logs() {646 return remoteLogs;647 }648 @Override649 public void addCookie(Cookie cookie) {650 cookie.validate();651 execute(DriverCommand.ADD_COOKIE(cookie));652 }653 @Override654 public void deleteCookieNamed(String name) {655 execute(DriverCommand.DELETE_COOKIE(name));656 }657 @Override658 public void deleteCookie(Cookie cookie) {659 deleteCookieNamed(cookie.getName());660 }661 @Override662 public void deleteAllCookies() {663 execute(DriverCommand.DELETE_ALL_COOKIES);664 }665 @Override666 @SuppressWarnings({"unchecked"})667 public Set<Cookie> getCookies() {668 Object returned = execute(DriverCommand.GET_ALL_COOKIES).getValue();669 Set<Cookie> toReturn = new HashSet<>();670 if (!(returned instanceof Collection)) {671 return toReturn;672 }673 ((Collection<?>) returned).stream()674 .map(o -> (Map<String, Object>) o)675 .map(rawCookie -> {676 // JSON object keys are defined in677 // https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion.678 Cookie.Builder builder =679 new Cookie.Builder((String) rawCookie.get("name"), (String) rawCookie.get("value"))680 .path((String) rawCookie.get("path"))681 .domain((String) rawCookie.get("domain"))682 .isSecure(rawCookie.containsKey("secure") && (Boolean) rawCookie.get("secure"))683 .isHttpOnly(684 rawCookie.containsKey("httpOnly") && (Boolean) rawCookie.get("httpOnly"))685 .sameSite((String) rawCookie.get("sameSite"));686 Number expiryNum = (Number) rawCookie.get("expiry");687 builder.expiresOn(expiryNum == null ? null : new Date(SECONDS.toMillis(expiryNum.longValue())));688 return builder.build();689 })690 .forEach(toReturn::add);691 return toReturn;692 }693 @Override694 public Cookie getCookieNamed(String name) {695 Set<Cookie> allCookies = getCookies();696 for (Cookie cookie : allCookies) {697 if (cookie.getName().equals(name)) {698 return cookie;699 }700 }701 return null;702 }703 @Override704 public Timeouts timeouts() {705 return new RemoteTimeouts();706 }707 @Override708 public ImeHandler ime() {709 return new RemoteInputMethodManager();710 }711 @Override712 @Beta713 public Window window() {714 return new RemoteWindow();715 }716 protected class RemoteInputMethodManager implements WebDriver.ImeHandler {717 @Override718 @SuppressWarnings("unchecked")719 public List<String> getAvailableEngines() {720 Response response = execute(DriverCommand.IME_GET_AVAILABLE_ENGINES);721 return (List<String>) response.getValue();722 }723 @Override724 public String getActiveEngine() {725 Response response = execute(DriverCommand.IME_GET_ACTIVE_ENGINE);726 return (String) response.getValue();727 }728 @Override729 public boolean isActivated() {730 Response response = execute(DriverCommand.IME_IS_ACTIVATED);731 return (Boolean) response.getValue();732 }733 @Override734 public void deactivate() {735 execute(DriverCommand.IME_DEACTIVATE);736 }737 @Override738 public void activateEngine(String engine) {739 execute(DriverCommand.IME_ACTIVATE_ENGINE(engine));740 }741 } // RemoteInputMethodManager class742 protected class RemoteTimeouts implements Timeouts {743 @Deprecated744 @Override745 public Timeouts implicitlyWait(long time, TimeUnit unit) {746 return implicitlyWait(Duration.ofMillis(unit.toMillis(time)));747 }748 @Override749 public Timeouts implicitlyWait(Duration duration) {750 execute(DriverCommand.SET_IMPLICIT_WAIT_TIMEOUT(duration));751 return this;752 }753 @Override754 public Duration getImplicitWaitTimeout() {755 Response response = execute(DriverCommand.GET_TIMEOUTS);756 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();757 long timeout = ((Number) rawSize.get("implicit")).longValue();758 return Duration.ofMillis(timeout);759 }760 @Deprecated761 @Override762 public Timeouts setScriptTimeout(long time, TimeUnit unit) {763 return setScriptTimeout(Duration.ofMillis(unit.toMillis(time)));764 }765 @Override766 public Timeouts setScriptTimeout(Duration duration) {767 return scriptTimeout(duration);768 }769 @Override770 public Timeouts scriptTimeout(Duration duration) {771 execute(DriverCommand.SET_SCRIPT_TIMEOUT(duration));772 return this;773 }774 @Override775 public Duration getScriptTimeout() {776 Response response = execute(DriverCommand.GET_TIMEOUTS);777 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();778 long timeout = ((Number) rawSize.get("script")).longValue();779 return Duration.ofMillis(timeout);780 }781 @Deprecated782 @Override783 public Timeouts pageLoadTimeout(long time, TimeUnit unit) {784 return pageLoadTimeout(Duration.ofMillis(unit.toMillis(time)));785 }786 @Override787 public Timeouts pageLoadTimeout(Duration duration) {788 execute(DriverCommand.SET_PAGE_LOAD_TIMEOUT(duration));789 return this;790 }791 @Override792 public Duration getPageLoadTimeout() {793 Response response = execute(DriverCommand.GET_TIMEOUTS);794 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();795 long timeout = ((Number) rawSize.get("pageLoad")).longValue();796 return Duration.ofMillis(timeout);797 }798 } // timeouts class.799 @Beta800 protected class RemoteWindow implements Window {801 @Override802 public void setSize(Dimension targetSize) {803 execute(DriverCommand.SET_CURRENT_WINDOW_SIZE(targetSize));804 }805 @Override806 public void setPosition(Point targetPosition) {807 execute(DriverCommand.SET_CURRENT_WINDOW_POSITION(targetPosition));808 }809 @Override810 @SuppressWarnings({"unchecked"})811 public Dimension getSize() {812 Response response = execute(DriverCommand.GET_CURRENT_WINDOW_SIZE);813 Map<String, Object> rawSize = (Map<String, Object>) response.getValue();814 int width = ((Number) rawSize.get("width")).intValue();815 int height = ((Number) rawSize.get("height")).intValue();816 return new Dimension(width, height);817 }818 Map<String, Object> rawPoint;819 @Override820 @SuppressWarnings("unchecked")821 public Point getPosition() {822 Response response = execute(DriverCommand.GET_CURRENT_WINDOW_POSITION());823 rawPoint = (Map<String, Object>) response.getValue();824 int x = ((Number) rawPoint.get("x")).intValue();825 int y = ((Number) rawPoint.get("y")).intValue();826 return new Point(x, y);827 }828 @Override829 public void maximize() {830 execute(DriverCommand.MAXIMIZE_CURRENT_WINDOW);831 }832 @Override833 public void minimize() {834 execute(DriverCommand.MINIMIZE_CURRENT_WINDOW);835 }836 @Override837 public void fullscreen() {838 execute(DriverCommand.FULLSCREEN_CURRENT_WINDOW);839 }840 }841 }842 private class RemoteNavigation implements Navigation {843 @Override844 public void back() {845 execute(DriverCommand.GO_BACK);846 }847 @Override848 public void forward() {849 execute(DriverCommand.GO_FORWARD);850 }851 @Override852 public void to(String url) {853 get(url);854 }855 @Override856 public void to(URL url) {857 get(String.valueOf(url));858 }859 @Override860 public void refresh() {861 execute(DriverCommand.REFRESH);862 }863 }864 protected class RemoteTargetLocator implements TargetLocator {865 @Override866 public WebDriver frame(int frameIndex) {867 execute(DriverCommand.SWITCH_TO_FRAME(frameIndex));868 return RemoteWebDriver.this;869 }870 @Override871 public WebDriver frame(String frameName) {872 String name = frameName.replaceAll("(['\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-/\\[\\]\\(\\)])", "\\\\$1");873 List<WebElement> frameElements = RemoteWebDriver.this.findElements(874 By.cssSelector("frame[name='" + name + "'],iframe[name='" + name + "']"));875 if (frameElements.size() == 0) {876 frameElements = RemoteWebDriver.this.findElements(877 By.cssSelector("frame#" + name + ",iframe#" + name));878 }879 if (frameElements.size() == 0) {880 throw new NoSuchFrameException("No frame element found by name or id " + frameName);881 }882 return frame(frameElements.get(0));883 }884 @Override885 public WebDriver frame(WebElement frameElement) {886 Object elementAsJson = new WebElementToJsonConverter().apply(frameElement);887 execute(DriverCommand.SWITCH_TO_FRAME(elementAsJson));888 return RemoteWebDriver.this;889 }890 @Override891 public WebDriver parentFrame() {892 execute(DriverCommand.SWITCH_TO_PARENT_FRAME);893 return RemoteWebDriver.this;894 }895 @Override896 public WebDriver window(String windowHandleOrName) {897 try {898 execute(DriverCommand.SWITCH_TO_WINDOW(windowHandleOrName));899 return RemoteWebDriver.this;900 } catch (NoSuchWindowException nsw) {901 // simulate search by name902 String original = getWindowHandle();903 for (String handle : getWindowHandles()) {904 switchTo().window(handle);905 if (windowHandleOrName.equals(executeScript("return window.name"))) {906 return RemoteWebDriver.this; // found by name907 }908 }909 switchTo().window(original);910 throw nsw;911 }912 }913 @Override914 public WebDriver newWindow(WindowType typeHint) {915 String original = getWindowHandle();916 try {917 Response response = execute(DriverCommand.SWITCH_TO_NEW_WINDOW(typeHint));918 String newWindowHandle = ((Map<String, Object>) response.getValue()).get("handle").toString();919 switchTo().window(newWindowHandle);920 return RemoteWebDriver.this;921 } catch (WebDriverException ex) {922 switchTo().window(original);923 throw ex;924 }925 }926 @Override927 public WebDriver defaultContent() {928 execute(DriverCommand.SWITCH_TO_FRAME(null));929 return RemoteWebDriver.this;930 }931 @Override932 public WebElement activeElement() {933 Response response = execute(DriverCommand.GET_ACTIVE_ELEMENT);934 return (WebElement) response.getValue();935 }936 @Override937 public Alert alert() {938 execute(DriverCommand.GET_ALERT_TEXT);939 return new RemoteAlert();940 }941 }942 private class RemoteAlert implements Alert {943 public RemoteAlert() {944 }945 @Override946 public void dismiss() {947 execute(DriverCommand.DISMISS_ALERT);948 }949 @Override950 public void accept() {951 execute(DriverCommand.ACCEPT_ALERT);952 }953 @Override954 public String getText() {955 return (String) execute(DriverCommand.GET_ALERT_TEXT).getValue();956 }957 /**958 * @param keysToSend character sequence to send to the alert959 *960 * @throws IllegalArgumentException if keysToSend is null961 */962 @Override963 public void sendKeys(String keysToSend) {964 if(keysToSend==null) {965 throw new IllegalArgumentException("Keys to send should be a not null CharSequence");966 }967 execute(DriverCommand.SET_ALERT_VALUE(keysToSend));968 }969 }970 private class RemoteVirtualAuthenticator implements VirtualAuthenticator {971 private final String id;972 public RemoteVirtualAuthenticator(final String id) {973 this.id = Require.nonNull("Id", id);974 }975 @Override976 public String getId() {977 return id;978 }979 @Override980 public void addCredential(Credential credential) {981 execute(DriverCommand.ADD_CREDENTIAL,982 new ImmutableMap.Builder<String, Object>()983 .putAll(credential.toMap())984 .put("authenticatorId", id)985 .build());986 }987 @Override988 public List<Credential> getCredentials() {989 List<Map<String, Object>> response = (List<Map<String, Object>>)990 execute(DriverCommand.GET_CREDENTIALS, ImmutableMap.of("authenticatorId", id)).getValue();991 return response.stream().map(Credential::fromMap).collect(Collectors.toList());992 }993 @Override994 public void removeCredential(byte[] credentialId) {995 removeCredential(Base64.getUrlEncoder().encodeToString(credentialId));996 }997 @Override998 public void removeCredential(String credentialId) {999 execute(DriverCommand.REMOVE_CREDENTIAL,1000 ImmutableMap.of("authenticatorId", id, "credentialId", credentialId));1001 }1002 @Override1003 public void removeAllCredentials() {1004 execute(DriverCommand.REMOVE_ALL_CREDENTIALS, ImmutableMap.of("authenticatorId", id));1005 }1006 @Override1007 public void setUserVerified(boolean verified) {1008 execute(DriverCommand.SET_USER_VERIFIED,1009 ImmutableMap.of("authenticatorId", id, "isUserVerified", verified));1010 }1011 }1012 public enum When {1013 BEFORE,1014 AFTER,1015 EXCEPTION1016 }1017 @Override1018 public String toString() {1019 Capabilities caps = getCapabilities();1020 if (caps == null) {1021 return super.toString();1022 }1023 // w3c name first1024 Object platform = caps.getCapability(PLATFORM_NAME);1025 if (!(platform instanceof String)) {1026 platform = caps.getCapability(PLATFORM);1027 }1028 if (platform == null) {1029 platform = "unknown";1030 }1031 return String.format(1032 "%s: %s on %s (%s)",1033 getClass().getSimpleName(),1034 caps.getBrowserName(),1035 platform,1036 getSessionId());1037 }1038 private enum Mechanism {1039 CONTEXT {1040 @Override1041 WebElement findElement(RemoteWebDriver parent, SearchContext context, By locator) {1042 return locator.findElement(context);1043 }1044 @Override1045 List<WebElement> findElements(RemoteWebDriver parent, SearchContext context, By locator) {1046 return locator.findElements(context);1047 }1048 },1049 REMOTE {1050 @Override1051 WebElement findElement(RemoteWebDriver parent, SearchContext context, By locator) {1052 String commandName;1053 Map<String, Object> params = new HashMap<>();1054 By.Remotable.Parameters fromLocator = ((By.Remotable) locator).getRemoteParameters();1055 params.put("using", fromLocator.using());1056 params.put("value", fromLocator.value());1057 if (context instanceof RemoteWebElement) {1058 commandName = DriverCommand.FIND_CHILD_ELEMENT;1059 params.put("id", ((RemoteWebElement) context).getId());1060 } else {1061 commandName = DriverCommand.FIND_ELEMENT;1062 }1063 Response response = parent.execute(new CommandPayload(commandName, params));1064 Object value = response.getValue();1065 if (value == null) {1066 throw new NoSuchElementException("Unable to find element with locator " + locator);1067 }1068 try {1069 return (WebElement) value;1070 } catch (ClassCastException ex) {1071 throw new WebDriverException(1072 "Returned value cannot be converted to WebElement: " + value, ex);1073 }1074 }1075 @Override1076 List<WebElement> findElements(RemoteWebDriver parent, SearchContext context, By locator) {1077 String commandName;1078 Map<String, Object> params = new HashMap<>();1079 By.Remotable.Parameters fromLocator = ((By.Remotable) locator).getRemoteParameters();1080 params.put("using", fromLocator.using());1081 params.put("value", fromLocator.value());1082 if (context instanceof RemoteWebElement) {1083 commandName = DriverCommand.FIND_CHILD_ELEMENTS;1084 params.put("id", ((RemoteWebElement) context).getId());1085 } else {1086 commandName = DriverCommand.FIND_ELEMENTS;1087 }1088 Response response = parent.execute(new CommandPayload(commandName, params));1089 Object value = response.getValue();1090 if (value == null) { // see https://github.com/SeleniumHQ/selenium/issues/45551091 return Collections.emptyList();1092 }1093 try {1094 @SuppressWarnings("unchecked") List<WebElement> toReturn = (List<WebElement>) value;1095 return toReturn;1096 } catch (ClassCastException ex) {1097 throw new WebDriverException(1098 "Returned value cannot be converted to WebElement: " + value, ex);1099 }1100 }1101 }1102 ;...

Full Screen

Full Screen

Source:TracedHttpClient.java Github

copy

Full Screen

...41 public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {42 return delegate.openSocket(request, listener);43 }44 @Override45 public HttpResponse execute(HttpRequest req) {46 try (Span span = newSpanAsChildOf(tracer, req, "httpclient.execute")) {47 KIND.accept(span, Span.Kind.CLIENT);48 HTTP_REQUEST.accept(span, req);49 tracer.getPropagator().inject(span, req, (r, key, value) -> r.setHeader(key, value));50 HttpResponse response = delegate.execute(req);51 HTTP_RESPONSE.accept(span, response);52 return response;53 }54 }55 public static class Factory implements HttpClient.Factory {56 private final Tracer tracer;57 private final HttpClient.Factory delegate;58 public Factory(Tracer tracer, HttpClient.Factory delegate) {59 this.tracer = Require.nonNull("Tracer", tracer);60 this.delegate = Require.nonNull("Actual handler", delegate);61 }62 public HttpClient createClient(ClientConfig config) {63 HttpClient client = delegate.createClient(config);64 return new TracedHttpClient(tracer, client);...

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.tracing.TracedHttpClient;2import org.openqa.selenium.remote.tracing.HttpClient;3import org.openqa.selenium.remote.tracing.HttpRequest;4import org.openqa.selenium.remote.tracing.HttpResponse;5import org.openqa.selenium.remote.tracing.Span;6import org.openqa.selenium.remote.tracing.SpanAttribute;7import org.openqa.selenium.remote.tracing.SpanAttributeBuilder;8import org.openqa.selenium.remote.tracing.SpanBuilder;9import org.openqa.selenium.remote.tracing.SpanBuilder.SpanBuilderSupplier;10import org.openqa.selenium.remote.tracing.Tracer;11import java.io.IOException;12import java.net.URI;13import java.util.Map;14import java.util.function.Supplier;15public class TracedHttpClient implements HttpClient {16 private final Tracer tracer;17 private final HttpClient client;18 public TracedHttpClient(Tracer tracer, HttpClient client) {19 this.tracer = tracer;20 this.client = client;21 }22 public HttpResponse execute(HttpRequest req) throws IOException {23 return tracer.createSpan(24 new SpanBuilderSupplier() {25 public SpanBuilder apply(SpanBuilder builder) {26 .addAttribute(SpanAttribute.HTTP_METHOD, req.getMethod())27 .addAttribute(SpanAttribute.HTTP_URL, req.getUri().toString());28 }29 },30 new Supplier<HttpResponse>() {31 public HttpResponse get() {32 return client.execute(req);33 }34 });35 }36}37import org.openqa.selenium.remote.tracing.TracedHttpClient;38driver = new TracedHttpClient(tracer, new OkHttpClient()).execute(req);

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1package org.openqa.selenium.remote.tracing;2import com.google.common.collect.ImmutableMap;3import com.google.common.collect.ImmutableSet;4import com.google.common.collect.ImmutableSortedMap;5import com.google.common.collect.ImmutableSortedSet;6import com.google.common.collect.Maps;7import com.google.common.collect.Sets;8import com.google.common.collect.SortedMaps;9import com.google.common.collect.SortedSets;10import com.google.common.collect.Streams;11import com.google.common.collect.TreeTraverser;12import com.google.common.io.BaseEncoding;13import com.google.common.reflect.TypeToken;14import com.google.common.util.concurrent.MoreExecutors;15import com.google.common.util.concurrent.ThreadFactoryBuilder;16import com.google.common.util.concurrent.Uninterruptibles;17import com.google.gson.JsonArray;18import com.google.gson.JsonElement;19import com.google.gson.JsonObject;20import com.google.gson.JsonPrimitive;21import com.google.gson.internal.Streams;22import com.google.gson.stream.JsonWriter;23import com.google.protobuf.ByteString;24import com.google.protobuf.InvalidProtocolBufferException;25import com.google.protobuf.Message;26import com.google.protobuf.MessageOrBuilder;27import com.google.protobuf.util.JsonFormat;28import com.google.protobuf.util.JsonFormat.TypeRegistry;29import com.google.protobuf.util.Timestamps;30import io.grpc.CallOptions;31import io.grpc.Channel;32import io.grpc.ClientCall;33import io.grpc.ClientInterceptor;34import io.grpc.ClientInterceptors;35import io.grpc.Context;36import io.grpc.Context.CancellationListener;37import io.grpc.Contexts;38import io.grpc.ForwardingClientCall;39import io.grpc.ForwardingClientCallListener;40import io.grpc.ManagedChannel;41import io.grpc.ManagedChannelBuilder;42import io.grpc.MethodDescriptor;43import io.grpc.Metadata;44import io.grpc.Metadata.Key;45import io.grpc.Server;46import io.grpc.ServerBuilder;47import io.grpc.ServerCall;48import io.grpc.ServerCall.Listener;49import io.grpc.ServerCallHandler;50import io.grpc.ServerInterceptor;51import io.grpc.Status;52import io.grpc.Status.Code;53import io.grpc.StatusException;54import io.grpc.StatusRuntimeException;55import io.grpc.StringMarshaller;56import io.grpc.internal.DnsNameResolverProvider;57import io.grpc.netty.GrpcSslContexts;58import io.grpc.netty.NettyChannelBuilder;59import io.grpc.netty.NettyServerBuilder;60import io.grpc.stub.StreamObserver;61import io.grpc.util.MutableHandlerRegistry;62import io.netty.channel.epoll.Epoll;63import io.netty.channel.epoll.EpollDomainSocketChannel;64import io.netty.channel.epoll.EpollEventLoopGroup;65import io.netty.channel.ep

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.HttpMethod;2import org.openqa.selenium.remote.http.HttpRequest;3import org.openqa.selenium.remote.tracing.TracedHttpClient;4import org.openqa.selenium.remote.tracing.Tracer;5import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;6public class TracingHttpClientExample {7 public static void main(String[] args) {8 Tracer tracer = new OpenTelemetryTracer();9 TracedHttpClient httpClient = new TracedHttpClient(tracer, new HttpClient());10 HttpResponse response = httpClient.execute(request);11 System.out.println(response.getStatus());12 }13}14import org.openqa.selenium.remote.http.HttpMethod;15import org.openqa.selenium.remote.http.HttpRequest;16import org.openqa.selenium.remote.tracing.TracedHttpClient;17import org.openqa.selenium.remote.tracing.Tracer;18import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;19public class TracingHttpClientExample {20 public static void main(String[] args) {21 Tracer tracer = new OpenTelemetryTracer();22 TracedHttpClient httpClient = new TracedHttpClient(tracer, new HttpClient());23 HttpResponse response = httpClient.executeAsync(request).join();24 System.out.println(response.getStatus());25 }26}27import org.openqa.selenium.remote.http.HttpMethod;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import org.openqa.selenium.remote.tracing.Tr

Full Screen

Full Screen

execute

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.tracing.HttpTracing;2import org.openqa.selenium.remote.tracing.TracedHttpClient;3import org.openqa.selenium.remote.tracing.global.GlobalTracer;4import java.net.http.HttpClient;5import java.time.Duration;6HttpClient client = HttpClient.newBuilder()7 .version(HttpClient.Version.HTTP_2)8 .connectTimeout(Duration.ofSeconds(5))9 .build();10HttpTracing tracing = GlobalTracer.get().getHttpTracing();11HttpClient tracedClient = new TracedHttpClient(client, tracing);12import org.openqa.selenium.remote.tracing.HttpTracing;13import org.openqa.selenium.remote.tracing.TracedHttpClient;14import org.openqa.selenium.remote.tracing.global.GlobalTracer;15import java.net.http.HttpClient;16import java.time.Duration;17HttpClient client = HttpClient.newBuilder()18 .version(HttpClient.Version.HTTP_2)19 .connectTimeout(Duration.ofSeconds(5))20 .build();21HttpTracing tracing = GlobalTracer.get().getHttpTracing();22HttpClient tracedClient = new TracedHttpClient(client, tracing);23import org.openqa.selenium.remote.tracing.HttpTracing;24import org.openqa.selenium.remote.tracing.TracedHttpClient;25import org.openqa.selenium.remote.tracing.global.GlobalTracer;26import java.net.http.HttpClient;27import java.time.Duration;28HttpClient client = HttpClient.newBuilder()29 .version(HttpClient.Version.HTTP_2)30 .connectTimeout(Duration.ofSeconds(5))31 .build();32HttpTracing tracing = GlobalTracer.get().getHttpTracing();33HttpClient tracedClient = new TracedHttpClient(client, tracing);34import org.openqa.selenium.remote.tracing.HttpTracing;35import org.openqa.selenium.remote.tracing.TracedHttpClient;36import org.openqa.selenium.remote.tracing.global.GlobalTracer;37import java.net.http.HttpClient;38import java.time.Duration;39HttpClient client = HttpClient.newBuilder()40 .version(HttpClient.Version.HTTP_2)41 .connectTimeout(Duration.ofSeconds(5))42 .build();43HttpTracing tracing = GlobalTracer.get().getHttpTracing();

Full Screen

Full Screen

Selenium 4 Tutorial:

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

Chapters:

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

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

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

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

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

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

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

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

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

Most used method in TracedHttpClient

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful