How to use stream method of org.openqa.selenium.internal.Either class

Best Selenium code snippet using org.openqa.selenium.internal.Either.stream

Source:JBrowserDriverServer.java Github

copy

Full Screen

1/* 2 * jBrowserDriver (TM)3 * Copyright (C) 2014-2016 Machine Publishers, LLC and the jBrowserDriver contributors4 * https://github.com/MachinePublishers/jBrowserDriver5 *6 * Licensed under the Apache License, Version 2.0 (the "License");7 * you may not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 *10 * http://www.apache.org/licenses/LICENSE-2.011 * 12 * Unless required by applicable law or agreed to in writing, software13 * distributed under the License is distributed on an "AS IS" BASIS,14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15 * See the License for the specific language governing permissions and16 * limitations under the License.17 */18package com.machinepublishers.jbrowserdriver;19import java.io.File;20import java.io.IOException;21import java.lang.reflect.Field;22import java.net.InetSocketAddress;23import java.net.ServerSocket;24import java.net.URL;25import java.rmi.RemoteException;26import java.rmi.registry.LocateRegistry;27import java.rmi.registry.Registry;28import java.rmi.server.RMISocketFactory;29import java.util.HashSet;30import java.util.List;31import java.util.Set;32import java.util.concurrent.atomic.AtomicInteger;33import java.util.concurrent.atomic.AtomicReference;34import org.openqa.selenium.By;35import org.openqa.selenium.Capabilities;36import org.openqa.selenium.HasCapabilities;37import org.openqa.selenium.JavascriptExecutor;38import org.openqa.selenium.OutputType;39import org.openqa.selenium.TakesScreenshot;40import org.openqa.selenium.TimeoutException;41import org.openqa.selenium.WebDriver;42import org.openqa.selenium.WebDriverException;43import org.openqa.selenium.WebElement;44import org.openqa.selenium.interactions.HasInputDevices;45import org.openqa.selenium.internal.FindsByClassName;46import org.openqa.selenium.internal.FindsByCssSelector;47import org.openqa.selenium.internal.FindsById;48import org.openqa.selenium.internal.FindsByLinkText;49import org.openqa.selenium.internal.FindsByName;50import org.openqa.selenium.internal.FindsByTagName;51import org.openqa.selenium.internal.FindsByXPath;52import org.openqa.selenium.internal.Killable;53import com.machinepublishers.jbrowserdriver.AppThread.Sync;54import com.sun.javafx.webkit.Accessor;55import com.sun.webkit.WebPage;56import com.sun.webkit.network.CookieManager;57class JBrowserDriverServer extends RemoteObject implements JBrowserDriverRemote,58 WebDriver, JavascriptExecutor, FindsById, FindsByClassName, FindsByLinkText, FindsByName,59 FindsByCssSelector, FindsByTagName, FindsByXPath, HasInputDevices, HasCapabilities,60 TakesScreenshot, Killable {61 private static final AtomicInteger childPort = new AtomicInteger();62 private static final AtomicReference<SocketFactory> socketFactory = new AtomicReference<SocketFactory>();63 private static Registry registry;64 /*65 * RMI entry point.66 */67 public static void main(String[] args) {68 try {69 CookieManager.setDefault(new CookieStore());70 try {71 URL.setURLStreamHandlerFactory(new StreamHandler());72 } catch (Throwable t) {73 Field factory = null;74 try {75 factory = URL.class.getDeclaredField("factory");76 factory.setAccessible(true);77 Object curFac = factory.get(null);78 //assume we're in the Eclipse jar-in-jar loader79 Field chainedFactory = curFac.getClass().getDeclaredField("chainFac");80 chainedFactory.setAccessible(true);81 chainedFactory.set(curFac, new StreamHandler());82 } catch (Throwable t2) {83 //this should work regardless84 factory.set(null, new StreamHandler());85 }86 }87 final String host = System.getProperty("java.rmi.server.hostname");88 childPort.set((int) Long.parseLong(args[0]));89 long parentPort = Long.parseLong(args[1]);90 parentPort = parentPort < 0 ? 0 : parentPort;91 long parentAltPort = Long.parseLong(args[2]);92 parentAltPort = parentAltPort < 0 ? 0 : parentAltPort;93 Registry registryTmp = null;94 final int maxTries = 5;95 for (int i = 1; i <= maxTries; i++) {96 try {97 if (childPort.get() <= 0) {98 childPort.set(findPort(host));99 }100 socketFactory.set(new SocketFactory(host,101 new PortGroup(childPort.get(), parentPort, parentAltPort), new HashSet<SocketLock>()));102 registryTmp = LocateRegistry.createRegistry(childPort.get(), socketFactory.get(), socketFactory.get());103 break;104 } catch (Throwable t) {105 if (i == maxTries) {106 Util.handleException(t);107 }108 }109 }110 registry = registryTmp;111 registry.rebind("JBrowserDriverRemote", new JBrowserDriverServer());112 RMISocketFactory.setSocketFactory(socketFactory.get());113 System.out.println("ready on ports " + childPort.get() + "/" + parentPort + "/" + parentAltPort);114 } catch (Throwable t) {115 t.printStackTrace();116 System.exit(1);117 }118 }119 private static int findPort(String host) throws IOException {120 ServerSocket socket = null;121 try {122 socket = new ServerSocket();123 socket.setReuseAddress(true);124 socket.bind(new InetSocketAddress(host, 0));125 return socket.getLocalPort();126 } finally {127 Util.close(socket);128 }129 }130 static int childPort() {131 return childPort.get();132 }133 static SocketFactory socketFactory() {134 return socketFactory.get();135 }136 final AtomicReference<Context> context = new AtomicReference<Context>();137 public JBrowserDriverServer() throws RemoteException {}138 @Override139 public void setUp(final Settings settings) {140 SettingsManager.register(settings);141 context.set(new Context());142 }143 @Override144 public void storeCapabilities(final Capabilities capabilities) {145 context.get().capabilities.set(capabilities);146 }147 /**148 * Optionally call this method if you want JavaFX initialized and the browser149 * window opened immediately. Otherwise, initialization will happen lazily.150 */151 public void init() {152 context.get().init(this);153 }154 /**155 * Reset the state of the browser. More efficient than quitting the156 * browser and creating a new instance.157 * 158 * @param settings159 * New settings to take effect, superseding the original ones160 */161 public void reset(final Settings settings) {162 AppThread.exec(163 new Sync<Object>() {164 @Override165 public Object perform() {166 context.get().item().engine.get().getLoadWorker().cancel();167 return null;168 }169 });170 Accessor.getPageFor(context.get().item().engine.get()).stop();171 ((CookieStore) CookieManager.getDefault()).clear();172 StatusMonitor.instance().clear();173 LogsServer.instance().clear(null);174 SettingsManager.register(settings);175 context.get().reset(this);176 }177 /**178 * Reset the state of the browser. More efficient than quitting the179 * browser and creating a new instance.180 */181 public void reset() {182 reset(SettingsManager.settings());183 }184 /**185 * {@inheritDoc}186 */187 @Override188 public String getPageSource() {189 init();190 WebElement element = ElementServer.create(context.get().item()).findElementByTagName("html");191 if (element != null) {192 String outerHtml = element.getAttribute("outerHTML");193 if (outerHtml != null && !outerHtml.isEmpty()) {194 return outerHtml;195 }196 }197 WebPage page = Accessor.getPageFor(context.get().item().engine.get());198 String html = page.getHtml(page.getMainFrame());199 if (html != null && !html.isEmpty()) {200 return html;201 }202 return page.getInnerText(page.getMainFrame());203 }204 /**205 * {@inheritDoc}206 */207 @Override208 public String getCurrentUrl() {209 init();210 return AppThread.exec(context.get().item().statusCode, new Sync<String>() {211 public String perform() {212 return context.get().item().view.get().getEngine().getLocation();213 }214 });215 }216 /**217 * {@inheritDoc}218 */219 @Override220 public void pageWait() {221 context.get().item().httpListener.get().resetStatusCode();222 getStatusCode();223 }224 public int getStatusCode() {225 return getStatusCode(context.get().timeouts.get().getPageLoadTimeoutMS());226 }227 private int getStatusCode(long waitMS) {228 init();229 int statusCode;230 synchronized (context.get().item().statusCode) {231 long start = System.currentTimeMillis();232 while ((statusCode = context.get().item().statusCode.get()) <= 0) {233 try {234 long nextWait = waitMS - (System.currentTimeMillis() - start);235 if (nextWait >= 0) {236 context.get().item().statusCode.wait(nextWait);237 } else if (waitMS == 0) {238 context.get().item().statusCode.wait();239 } else {240 break;241 }242 } catch (InterruptedException e) {}243 }244 }245 return statusCode;246 }247 /**248 * {@inheritDoc}249 */250 @Override251 public String getTitle() {252 init();253 return AppThread.exec(context.get().item().statusCode, new Sync<String>() {254 public String perform() {255 return context.get().item().view.get().getEngine().getTitle();256 }257 });258 }259 /**260 * {@inheritDoc}261 */262 @Override263 public void get(final String url) {264 init();265 long start = System.currentTimeMillis();266 try {267 AppThread.exec(context.get().item().statusCode,268 context.get().timeouts.get().getPageLoadTimeoutMS(), new Sync<Object>() {269 public Object perform() {270 context.get().item().httpListener.get().resetStatusCode();271 context.get().item().engine.get().load(url);272 return null;273 }274 });275 long end = System.currentTimeMillis();276 if (context.get().timeouts.get().getPageLoadTimeoutMS() == 0) {277 getStatusCode();278 } else {279 long waitMS = context.get().timeouts.get().getPageLoadTimeoutMS() - (end - start);280 if (waitMS > 0) {281 getStatusCode(waitMS);282 }283 }284 } finally {285 if (context.get().item().statusCode.get() == 0) {286 AppThread.exec(287 new Sync<Object>() {288 @Override289 public Object perform() {290 context.get().item().engine.get().getLoadWorker().cancel();291 throw new TimeoutException(new StringBuilder()292 .append("Timeout of ")293 .append(context.get().timeouts.get().getPageLoadTimeoutMS())294 .append("ms reached.").toString());295 }296 });297 }298 }299 }300 /**301 * {@inheritDoc}302 */303 @Override304 public ElementServer findElement(By by) {305 init();306 return ElementServer.create(context.get().item()).findElement(by);307 }308 /**309 * {@inheritDoc}310 */311 @Override312 public List findElements(By by) {313 init();314 return ElementServer.create(context.get().item()).findElements(by);315 }316 /**317 * {@inheritDoc}318 */319 @Override320 public ElementServer findElementById(String id) {321 init();322 return ElementServer.create(context.get().item()).findElementById(id);323 }324 /**325 * {@inheritDoc}326 */327 @Override328 public List findElementsById(String id) {329 init();330 return ElementServer.create(context.get().item()).findElementsById(id);331 }332 /**333 * {@inheritDoc}334 */335 @Override336 public ElementServer findElementByXPath(String expr) {337 init();338 return ElementServer.create(context.get().item()).findElementByXPath(expr);339 }340 /**341 * {@inheritDoc}342 */343 @Override344 public List findElementsByXPath(String expr) {345 init();346 return ElementServer.create(context.get().item()).findElementsByXPath(expr);347 }348 /**349 * {@inheritDoc}350 */351 @Override352 public ElementServer findElementByLinkText(final String text) {353 init();354 return ElementServer.create(context.get().item()).findElementByLinkText(text);355 }356 /**357 * {@inheritDoc}358 */359 @Override360 public ElementServer findElementByPartialLinkText(String text) {361 init();362 return ElementServer.create(context.get().item()).findElementByPartialLinkText(text);363 }364 /**365 * {@inheritDoc}366 */367 @Override368 public List findElementsByLinkText(String text) {369 init();370 return ElementServer.create(context.get().item()).findElementsByLinkText(text);371 }372 /**373 * {@inheritDoc}374 */375 @Override376 public List findElementsByPartialLinkText(String text) {377 init();378 return ElementServer.create(context.get().item()).findElementsByPartialLinkText(text);379 }380 /**381 * {@inheritDoc}382 */383 @Override384 public ElementServer findElementByClassName(String cssClass) {385 init();386 return ElementServer.create(context.get().item()).findElementByClassName(cssClass);387 }388 /**389 * {@inheritDoc}390 */391 @Override392 public List findElementsByClassName(String cssClass) {393 init();394 return ElementServer.create(context.get().item()).findElementsByClassName(cssClass);395 }396 /**397 * {@inheritDoc}398 */399 @Override400 public ElementServer findElementByName(String name) {401 init();402 return ElementServer.create(context.get().item()).findElementByName(name);403 }404 /**405 * {@inheritDoc}406 */407 @Override408 public List findElementsByName(String name) {409 init();410 return ElementServer.create(context.get().item()).findElementsByName(name);411 }412 /**413 * {@inheritDoc}414 */415 @Override416 public ElementServer findElementByCssSelector(String expr) {417 init();418 return ElementServer.create(context.get().item()).findElementByCssSelector(expr);419 }420 /**421 * {@inheritDoc}422 */423 @Override424 public List findElementsByCssSelector(String expr) {425 init();426 return ElementServer.create(context.get().item()).findElementsByCssSelector(expr);427 }428 /**429 * {@inheritDoc}430 */431 @Override432 public ElementServer findElementByTagName(String tagName) {433 init();434 return ElementServer.create(context.get().item()).findElementByTagName(tagName);435 }436 /**437 * {@inheritDoc}438 */439 @Override440 public List findElementsByTagName(String tagName) {441 init();442 return ElementServer.create(context.get().item()).findElementsByTagName(tagName);443 }444 /**445 * {@inheritDoc}446 */447 @Override448 public Object executeAsyncScript(String script, Object... args) {449 init();450 return ElementServer.create(context.get().item()).executeAsyncScript(script, args);451 }452 /**453 * {@inheritDoc}454 */455 @Override456 public Object executeScript(String script, Object... args) {457 init();458 return ElementServer.create(context.get().item()).executeScript(script, args);459 }460 /**461 * {@inheritDoc}462 */463 @Override464 public KeyboardServer getKeyboard() {465 init();466 return context.get().keyboard.get();467 }468 /**469 * {@inheritDoc}470 */471 @Override472 public MouseServer getMouse() {473 init();474 return context.get().mouse.get();475 }476 /**477 * {@inheritDoc}478 */479 @Override480 public Capabilities getCapabilities() {481 init();482 return context.get().capabilities.get();483 }484 /**485 * {@inheritDoc}486 */487 @Override488 public void close() {489 init();490 context.get().removeItem();491 }492 /**493 * {@inheritDoc}494 */495 @Override496 public String getWindowHandle() {497 init();498 return context.get().itemId();499 }500 /**501 * {@inheritDoc}502 */503 @Override504 public Set<String> getWindowHandles() {505 init();506 return context.get().itemIds();507 }508 /**509 * {@inheritDoc}510 */511 @Override512 public OptionsServer manage() {513 init();514 return context.get().options.get();515 }516 /**517 * {@inheritDoc}518 */519 @Override520 public LogsServer logs() {521 return LogsServer.instance();522 }523 /**524 * {@inheritDoc}525 */526 @Override527 public NavigationServer navigate() {528 init();529 return context.get().navigation.get();530 }531 /**532 * {@inheritDoc}533 */534 @Override535 public void quit() {536 getStatusCode();537 }538 /**539 * {@inheritDoc}540 */541 @Override542 public TargetLocatorServer switchTo() {543 init();544 return context.get().targetLocator.get();545 }546 /**547 * {@inheritDoc}548 */549 @Override550 public void kill() {}551 /**552 * {@inheritDoc}553 */554 @Override555 public <X> X getScreenshotAs(final OutputType<X> outputType) throws WebDriverException {556 return outputType.convertFromPngBytes(getScreenshot());557 }558 /**559 * {@inheritDoc}560 */561 @Override562 public byte[] getScreenshot() throws WebDriverException {563 init();564 return context.get().robot.get().screenshot();565 }566 /**567 * {@inheritDoc}568 */569 @Override570 public File cacheDir() {571 return StreamConnection.cacheDir();572 }573 /**574 * {@inheritDoc}575 */576 @Override577 public File attachmentsDir() {578 return StreamConnection.attachmentsDir();579 }580 /**581 * {@inheritDoc}582 */583 @Override584 public File mediaDir() {585 return StreamConnection.mediaDir();586 }587}...

Full Screen

Full Screen

Source:By.java Github

copy

Full Screen

...26import java.util.Collections;27import java.util.HashMap;28import java.util.List;29import java.util.Map;30import java.util.stream.Stream;31import static java.util.stream.Collectors.joining;32/**33 * Mechanism used to locate elements within a document. In order to create your own locating34 * mechanisms, it is possible to subclass this class and override the protected methods as required,35 * though it is expected that all subclasses rely on the basic finding mechanisms provided36 * through static methods of this class:37 *38 * <code>39 * public WebElement findElement(WebDriver driver) {40 * WebElement element = driver.findElement(By.id(getSelector()));41 * if (element == null)42 * element = driver.findElement(By.name(getSelector());43 * return element;44 * }45 * </code>...

Full Screen

Full Screen

Source:RemoteWebElement.java Github

copy

Full Screen

...45import java.util.Arrays;46import java.util.Collections;47import java.util.List;48import java.util.Map;49import java.util.stream.Collectors;50public class RemoteWebElement implements WebElement, FindsByLinkText, FindsById, FindsByName,51 FindsByTagName, FindsByClassName, FindsByCssSelector,52 FindsByXPath, WrapsDriver, TakesScreenshot, Locatable {53 private String foundBy;54 protected String id;55 protected RemoteWebDriver parent;56 protected FileDetector fileDetector;57 protected void setFoundBy(SearchContext foundFrom, String locator, String term) {58 this.foundBy = String.format("[%s] -> %s: %s", foundFrom, locator, term);59 }60 public void setParent(RemoteWebDriver parent) {61 this.parent = parent;62 }63 public String getId() {64 return id;65 }66 public void setId(String id) {67 this.id = id;68 }69 public void setFileDetector(FileDetector detector) {70 fileDetector = detector;71 }72 @Override73 public void click() {74 execute(DriverCommand.CLICK_ELEMENT(id));75 }76 @Override77 public void submit() {78 execute(DriverCommand.SUBMIT_ELEMENT(id));79 }80 @Override81 public void sendKeys(CharSequence... keysToSend) {82 if (keysToSend == null || keysToSend.length == 0) {83 throw new IllegalArgumentException("Keys to send should be a not null CharSequence");84 }85 for (CharSequence cs : keysToSend) {86 if (cs == null) {87 throw new IllegalArgumentException("Keys to send should be a not null CharSequence");88 }89 }90 String allKeysToSend = String.join("", keysToSend);91 List<File> files = Arrays.stream(allKeysToSend.split("\n"))92 .map(fileDetector::getLocalFile)93 .collect(Collectors.toList());94 if (! files.contains(null)) {95 allKeysToSend = files.stream()96 .map(this::upload)97 .collect(Collectors.joining("\n"));98 }99 execute(DriverCommand.SEND_KEYS_TO_ELEMENT(id, new CharSequence[]{allKeysToSend}));100 }101 private String upload(File localFile) {102 if (!localFile.isFile()) {103 throw new WebDriverException("You may only upload files: " + localFile);104 }105 try {106 String zip = Zip.zip(localFile);107 Response response = execute(DriverCommand.UPLOAD_FILE(zip));108 return (String) response.getValue();109 } catch (IOException e) {...

Full Screen

Full Screen

Source:ForwardingTargetedWebDriver.java Github

copy

Full Screen

...31import org.openqa.selenium.internal.WrapsDriver;32import java.util.List;33import java.util.Objects;34import java.util.Set;35import java.util.stream.Collectors;36public class ForwardingTargetedWebDriver implements TargetedWebDriver, FindsByClassName,37 FindsByCssSelector, FindsById, FindsByLinkText, FindsByName, FindsByTagName, FindsByXPath,38 JavascriptExecutor, WrapsDriver {39 private final TargetLocator locator;40 private final WebDriverTarget target;41 /**42 * @param locator Should not be a {@link com.redhat.darcy.webdriver.internal.TargetedTargetLocator}.43 * @param target The target this driver will always refer to.44 */45 public ForwardingTargetedWebDriver(TargetLocator locator, WebDriverTarget target) {46 this.locator = locator;47 this.target = target;48 }49 public TargetLocator getTargetLocator() {50 return locator;51 }52 @Override53 public WebDriverTarget getWebDriverTarget() {54 return target;55 }56 @Override57 public boolean isPresent() {58 try {59 driver().getTitle();60 return true;61 } catch (NotFoundException e) {62 return false;63 }64 }65 @Override66 public void get(String url) {67 driver().get(url);68 }69 @Override70 public String getCurrentUrl() {71 return driver().getCurrentUrl();72 }73 @Override74 public String getTitle() {75 return driver().getTitle();76 }77 @Override78 public List<WebElement> findElements(By by) {79 return targetedWebElements(driver().findElements(by));80 }81 @Override82 public WebElement findElement(By by) {83 return targetedWebElement(driver().findElement(by));84 }85 @Override86 public String getPageSource() {87 return driver().getPageSource();88 }89 @Override90 public void close() {91 driver().close();92 }93 @Override94 public void quit() {95 driver().quit();96 }97 @Override98 public Set<String> getWindowHandles() {99 return driver().getWindowHandles();100 }101 @Override102 public String getWindowHandle() {103 return driver().getWindowHandle();104 }105 @Override106 public TargetedTargetLocator switchTo() {107 return new TargetedTargetLocator(locator, target);108 }109 // TODO: Navigation object wont be targeted110 @Override111 public Navigation navigate() {112 return driver().navigate();113 }114 // TODO: Options object wont be targeted115 @Override116 public Options manage() {117 return driver().manage();118 }119 @Override120 public WebElement findElementByClassName(String using) {121 return targetedWebElement(((FindsByClassName) driver()).findElementByClassName(using));122 }123 @Override124 public List<WebElement> findElementsByClassName(String using) {125 return targetedWebElements(((FindsByClassName) driver()).findElementsByClassName(using));126 }127 @Override128 public WebElement findElementByCssSelector(String using) {129 return targetedWebElement(((FindsByCssSelector) driver()).findElementByCssSelector(using));130 }131 @Override132 public List<WebElement> findElementsByCssSelector(String using) {133 return targetedWebElements(((FindsByCssSelector) driver()).findElementsByCssSelector(using));134 }135 @Override136 public WebElement findElementById(String using) {137 return targetedWebElement(((FindsById) driver()).findElementById(using));138 }139 @Override140 public List<WebElement> findElementsById(String using) {141 return targetedWebElements(((FindsById) driver()).findElementsById(using));142 }143 @Override144 public WebElement findElementByLinkText(String using) {145 return targetedWebElement(((FindsByLinkText) driver()).findElementByLinkText(using));146 }147 @Override148 public List<WebElement> findElementsByLinkText(String using) {149 return targetedWebElements(((FindsByLinkText) driver()).findElementsByLinkText(using));150 }151 @Override152 public WebElement findElementByPartialLinkText(String using) {153 return targetedWebElement(((FindsByLinkText) driver()).findElementByPartialLinkText(using));154 }155 @Override156 public List<WebElement> findElementsByPartialLinkText(String using) {157 return targetedWebElements(((FindsByLinkText) driver()).findElementsByPartialLinkText158 (using));159 }160 @Override161 public WebElement findElementByName(String using) {162 return targetedWebElement(((FindsByName) driver()).findElementByName(using));163 }164 @Override165 public List<WebElement> findElementsByName(String using) {166 return targetedWebElements(((FindsByName) driver()).findElementsByName(using));167 }168 @Override169 public WebElement findElementByTagName(String using) {170 return targetedWebElement(((FindsByTagName) driver()).findElementByTagName(using));171 }172 @Override173 public List<WebElement> findElementsByTagName(String using) {174 return targetedWebElements(((FindsByTagName) driver()).findElementsByTagName(using));175 }176 @Override177 public WebElement findElementByXPath(String using) {178 return targetedWebElement(((FindsByXPath) driver()).findElementByXPath(using));179 }180 @Override181 public List<WebElement> findElementsByXPath(String using) {182 return targetedWebElements(((FindsByXPath) driver()).findElementsByXPath(using));183 }184 // TODO: Protect WebElements returned from executeScript?185 @Override186 public Object executeScript(String script, Object... args) {187 return ((JavascriptExecutor) driver()).executeScript(script, args);188 }189 @Override190 public Object executeAsyncScript(String script, Object... args) {191 return ((JavascriptExecutor) driver()).executeAsyncScript(script, args);192 }193 @Override194 public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {195 return ((TakesScreenshot) driver()).getScreenshotAs(target);196 }197 @Override198 public WebDriver getWrappedDriver() {199 return driver();200 }201 @Override202 public boolean equals(Object o) {203 if (this == o) {204 return true;205 }206 if (o == null || getClass() != o.getClass()) {207 return false;208 }209 ForwardingTargetedWebDriver that = (ForwardingTargetedWebDriver) o;210 return Objects.equals(locator, that.locator) &&211 Objects.equals(target, that.target);212 }213 @Override214 public int hashCode() {215 return Objects.hash(locator, target);216 }217 @Override218 public String toString() {219 return "ForwardingTargetedWebDriver{" +220 "locator=" + locator +221 ", target=" + target +222 '}';223 }224 /**225 * @return The switched-to {@link org.openqa.selenium.WebDriver} instance which we can forward226 * calls to.227 */228 private WebDriver driver() {229 return target.switchTo(locator);230 }231 private WebElement targetedWebElement(WebElement element) {232 return new TargetedWebElement(locator, target, element);233 }234 private List<WebElement> targetedWebElements(List<WebElement> elements) {235 return elements236 .stream()237 .map(e -> new TargetedWebElement(locator, target, e))238 .collect(Collectors.toList());239 }240}...

Full Screen

Full Screen

Source:TargetedWebElement.java Github

copy

Full Screen

...28import org.openqa.selenium.internal.FindsByName;29import org.openqa.selenium.internal.FindsByTagName;30import org.openqa.selenium.internal.FindsByXPath;31import java.util.List;32import java.util.stream.Collectors;33public class TargetedWebElement implements WebElement, FindsByClassName,34 FindsByCssSelector, FindsById, FindsByLinkText, FindsByName, FindsByTagName, FindsByXPath {35 private final TargetLocator locator;36 private final WebDriverTarget target;37 /**38 * The backing {@link org.openqa.selenium.WebElement}. Using this directly may result in39 * {@link org.openqa.selenium.StaleElementReferenceException StaleElementReferenceExceptions}.40 * Use {@link #element()} instead.41 */42 private final WebElement element;43 public TargetedWebElement(TargetLocator locator, WebDriverTarget target, WebElement element) {44 this.locator = locator;45 this.target = target;46 this.element = element;47 }48 @Override49 public void click() {50 element().click();51 }52 @Override53 public void submit() {54 element().submit();55 }56 @Override57 public void sendKeys(CharSequence... keysToSend) {58 element().sendKeys(keysToSend);59 }60 @Override61 public void clear() {62 element().clear();63 }64 @Override65 public String getTagName() {66 return element().getTagName();67 }68 @Override69 public String getAttribute(String name) {70 return element().getAttribute(name);71 }72 @Override73 public boolean isSelected() {74 return element().isSelected();75 }76 @Override77 public boolean isEnabled() {78 return element().isEnabled();79 }80 @Override81 public String getText() {82 return element().getText();83 }84 @Override85 public List<WebElement> findElements(By by) {86 return targetedWebElements(element().findElements(by));87 }88 @Override89 public WebElement findElement(By by) {90 return targetedWebElement(element().findElement(by));91 }92 @Override93 public boolean isDisplayed() {94 return element().isDisplayed();95 }96 @Override97 public Point getLocation() {98 return element().getLocation();99 }100 @Override101 public Dimension getSize() {102 return element().getSize();103 }104 @Override105 public Rectangle getRect() {106 return element().getRect();107 }108 @Override109 public String getCssValue(String propertyName) {110 return element().getCssValue(propertyName);111 }112 @Override113 public WebElement findElementByClassName(String using) {114 return targetedWebElement(((FindsByClassName) element()).findElementByClassName(using));115 }116 @Override117 public List<WebElement> findElementsByClassName(String using) {118 return targetedWebElements(((FindsByClassName) element()).findElementsByClassName(using));119 }120 @Override121 public WebElement findElementByCssSelector(String using) {122 return targetedWebElement(((FindsByCssSelector) element()).findElementByCssSelector(using));123 }124 @Override125 public List<WebElement> findElementsByCssSelector(String using) {126 return targetedWebElements(((FindsByCssSelector) element()).findElementsByCssSelector(using));127 }128 @Override129 public WebElement findElementById(String using) {130 return targetedWebElement(((FindsById) element()).findElementById(using));131 }132 @Override133 public List<WebElement> findElementsById(String using) {134 return targetedWebElements(((FindsById) element()).findElementsById(using));135 }136 @Override137 public WebElement findElementByLinkText(String using) {138 return targetedWebElement(((FindsByLinkText) element()).findElementByLinkText(using));139 }140 @Override141 public List<WebElement> findElementsByLinkText(String using) {142 return targetedWebElements(((FindsByLinkText) element()).findElementsByLinkText(using));143 }144 @Override145 public WebElement findElementByPartialLinkText(String using) {146 return targetedWebElement(((FindsByLinkText) element()).findElementByPartialLinkText(using));147 }148 @Override149 public List<WebElement> findElementsByPartialLinkText(String using) {150 return targetedWebElements(((FindsByLinkText) element()).findElementsByPartialLinkText(using));151 }152 @Override153 public WebElement findElementByName(String using) {154 return targetedWebElement(((FindsByName) element()).findElementByName(using));155 }156 @Override157 public List<WebElement> findElementsByName(String using) {158 return targetedWebElements(((FindsByName) element()).findElementsByName(using));159 }160 @Override161 public WebElement findElementByTagName(String using) {162 return targetedWebElement(((FindsByTagName) element()).findElementByTagName(using));163 }164 @Override165 public List<WebElement> findElementsByTagName(String using) {166 return targetedWebElements(((FindsByTagName) element()).findElementsByTagName(using));167 }168 @Override169 public WebElement findElementByXPath(String using) {170 return targetedWebElement(((FindsByXPath) element()).findElementByXPath(using));171 }172 @Override173 public List<WebElement> findElementsByXPath(String using) {174 return targetedWebElements(((FindsByXPath) element()).findElementsByXPath(using));175 }176 @Override177 public <X> X getScreenshotAs(OutputType<X> outputType) throws WebDriverException {178 return element().getScreenshotAs(outputType);179 }180 /**181 * @return The backing {@link org.openqa.selenium.WebElement}, with the driver switched to the182 * appropriate target.183 */184 private WebElement element() {185 target.switchTo(locator);186 return element;187 }188 private WebElement targetedWebElement(WebElement element) {189 return new TargetedWebElement(locator, target, element);190 }191 private List<WebElement> targetedWebElements(List<WebElement> elements) {192 return elements193 .stream()194 .map(e -> new TargetedWebElement(locator, target, e))195 .collect(Collectors.toList());196 }197}...

Full Screen

Full Screen

Source:FxSearchContext.java Github

copy

Full Screen

...26import org.openqa.selenium.internal.FindsById;27import java.util.ArrayList;28import java.util.Arrays;29import java.util.List;30import java.util.stream.Collectors;31public class FxSearchContext implements SearchContext, FindsById, FindsByClassName, FindsByCssSelector32{33 protected IFxRobot robot;34 protected Node root;35 public FxSearchContext(IFxRobot robot)36 {37 this.robot = robot;38 }39 public FxSearchContext(IFxRobot robot, Node root)40 {41 this(robot);42 this.root = root;43 }44 private List<Node> getRoots()45 {46 if (root != null)47 return Arrays.asList(root);48 else49 return NodeUtils.listWindows().stream().map(w -> (Node)w.getScene().getRoot()).collect(Collectors.toList());50 }51 @Override52 public List<WebElement> findElements(By by)53 {54 return null;55 }56 @Override57 public WebElement findElement(By by)58 {59 return null;60 }61 @Override62 public WebElement findElementById(String id)63 {64 for (Node root : getRoots())65 {66 Node node = NodeUtils.execute(() -> root.lookup("#" + id));67 if (node != null)68 return createWebElement(node);69 }70 throw new NoSuchElementException("Element with id '" + id + "' not found");71 }72 @Override73 public List<WebElement> findElementsById(String id)74 {75 List<WebElement> elements = new ArrayList<>();76 for (Node root : getRoots())77 {78 NodeUtils.execute(() -> root.lookupAll("#" + id).stream()79 .map(this::createWebElement)80 .forEach(elements::add));81 }82 return elements;83 }84 @Override85 public WebElement findElementByClassName(String className)86 {87 for (Node root : getRoots())88 {89 Node node = NodeUtils.execute(() -> root.lookup("." + className));90 if (node != null)91 return createWebElement(node);92 }93 throw new NoSuchElementException("Element with class '" + className + "' not found");94 }95 @Override96 public List<WebElement> findElementsByClassName(String className)97 {98 List<WebElement> elements = new ArrayList<>();99 for (Node root : getRoots())100 {101 NodeUtils.execute(() -> root.lookupAll("." + className).stream()102 .map(this::createWebElement)103 .forEach(elements::add));104 }105 return elements;106 }107 @Override108 public WebElement findElementByCssSelector(String cssSelector)109 {110 for (Node root : getRoots())111 {112 Node node = NodeUtils.execute(() -> root.lookup(cssSelector));113 if (node != null)114 return createWebElement(node);115 }116 throw new NoSuchElementException("Element with selector '" + cssSelector + "' not found");117 }118 @Override119 public List<WebElement> findElementsByCssSelector(String cssSelector)120 {121 List<WebElement> elements = new ArrayList<>();122 for (Node root : getRoots())123 {124 NodeUtils.execute(() -> root.lookupAll(cssSelector).stream()125 .map(this::createWebElement)126 .forEach(elements::add));127 }128 return elements;129 }130 private WebElement createWebElement(Node node)131 {132 if (node instanceof WebView)133 return new FxWebViewElement(node, robot);134 else135 return new FxElement(node, robot);136 }137}...

Full Screen

Full Screen

Source:JavascriptLibrary.java Github

copy

Full Screen

1/*2Copyright 2007-2009 WebDriver committers3Copyright 2007-2009 Google Inc.4Licensed under the Apache License, Version 2.0 (the "License");5you may not use this file except in compliance with the License.6You may obtain a copy of the License at7 http://www.apache.org/licenses/LICENSE-2.08Unless required by applicable law or agreed to in writing, software9distributed under the License is distributed on an "AS IS" BASIS,10WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11See the License for the specific language governing permissions and12limitations under the License.13*/14package org.openqa.selenium.internal.seleniumemulation;15import java.io.BufferedReader;16import java.io.IOException;17import java.io.InputStream;18import java.io.InputStreamReader;19import java.util.ArrayList;20import java.util.Arrays;21import java.util.List;22import org.openqa.selenium.JavascriptExecutor;23import org.openqa.selenium.WebDriver;24import org.openqa.selenium.WebElement;25public class JavascriptLibrary {26 private static final String injectableSelenium =27 "/org/openqa/selenium/internal/seleniumemulation/injectableSelenium.js";28 private static final String htmlUtils =29 "/org/openqa/selenium/internal/seleniumemulation/htmlutils.js";30 public void callEmbeddedSelenium(WebDriver driver, String functionName,31 WebElement element, Object... values) {32 StringBuilder builder = new StringBuilder(readScript(injectableSelenium));33 builder.append("return browserbot.").append(functionName).append(".apply(browserbot, arguments);");34 List<Object> args = new ArrayList<Object>();35 args.add(element);36 args.addAll(Arrays.asList(values));37 ((JavascriptExecutor) driver).executeScript(builder.toString(), args.toArray());38 }39 public Object callEmbeddedHtmlUtils(WebDriver driver, String functionName, WebElement element, Object... values) {40 StringBuilder builder = new StringBuilder(readScript(htmlUtils));41 builder.append("return htmlutils.").append(functionName).append(".apply(htmlutils, arguments);");42 List<Object> args = new ArrayList<Object>();43 args.add(element);44 args.addAll(Arrays.asList(values));45 return ((JavascriptExecutor) driver).executeScript(builder.toString(), args.toArray());46 }47 public Object executeScript(WebDriver driver, String script, Object... args) {48 if (driver instanceof JavascriptExecutor) {49 return ((JavascriptExecutor) driver).executeScript(script, args);50 }51 throw new UnsupportedOperationException(52 "The underlying WebDriver instance does not support executing javascript");53 }54 private String readScript(String script) {55 InputStream raw = getClass().getResourceAsStream(script);56 if (raw == null) {57 throw new RuntimeException("Cannot locate the embedded selenium instance");58 }59 try {60 BufferedReader reader = new BufferedReader(new InputStreamReader(raw));61 StringBuilder builder = new StringBuilder();62 for (String line = reader.readLine(); line != null; line = reader.readLine()) {63 builder.append(line).append("\n");64 }65 return builder.toString();66 } catch (IOException e) {67 throw new RuntimeException(e);68 } finally {69 try {70 raw.close();71 } catch (IOException e) {72 // Nothing sane to do73 }74 }75 }76}...

Full Screen

Full Screen

Source:DumpHttpExchangeFilter.java Github

copy

Full Screen

...21import java.io.InputStream;22import java.util.function.Supplier;23import java.util.logging.Level;24import java.util.logging.Logger;25import java.util.stream.StreamSupport;26import static java.util.stream.Collectors.joining;27public class DumpHttpExchangeFilter implements Filter {28 public static final Logger LOG = Logger.getLogger(DumpHttpExchangeFilter.class.getName());29 private final Level logLevel;30 public DumpHttpExchangeFilter() {31 this(Debug.getDebugLogLevel());32 }33 public DumpHttpExchangeFilter(Level logLevel) {34 this.logLevel = Require.nonNull("Log level", logLevel);35 }36 @Override37 public HttpHandler apply(HttpHandler next) {38 return req -> {39 // Use the supplier to avoid messing with the request unless we're logging40 LOG.log(logLevel, () -> requestLogMessage(req));41 HttpResponse res = next.execute(req);42 LOG.log(logLevel, () -> responseLogMessage(res));43 return res;44 };45 }46 private void expandHeadersAndContent(StringBuilder builder, HttpMessage<?> message) {47 message.getHeaderNames().forEach(name -> {48 builder.append(" ").append(name).append(": ");49 builder.append(StreamSupport.stream(message.getHeaders(name).spliterator(), false).collect(joining(", ")));50 builder.append("\n");51 });52 builder.append("\n");53 builder.append(Contents.string(message));54 }55 @VisibleForTesting56 String requestLogMessage(HttpRequest req) {57 // There's no requirement that requests or responses can be read more than once. Protect ourselves.58 Supplier<InputStream> memoized = Contents.memoize(req.getContent());59 req.setContent(memoized);60 StringBuilder reqInfo = new StringBuilder();61 reqInfo.append("HTTP Request: ").append(req).append("\n");62 expandHeadersAndContent(reqInfo, req);63 return reqInfo.toString();...

Full Screen

Full Screen

stream

Using AI Code Generation

copy

Full Screen

1private String getEitherText(WebElement element) {2 return element.isDisplayed() ?3 element.getText() :4 orElse("");5}6private String getEitherText(WebElement element) {7 return element.isDisplayed() ?8 element.getText() :9 orElse("");10}11private String getEitherText(WebElement element) {12 return element.isDisplayed() ?13 element.getText() :14 orElse("");15}16private String getEitherText(WebElement element) {17 return element.isDisplayed() ?18 element.getText() :19 orElse("");20}21private String getEitherText(WebElement element) {22 return element.isDisplayed() ?23 element.getText() :24 orElse("");25}26private String getEitherText(WebElement element) {27 return element.isDisplayed() ?28 element.getText() :29 orElse("");30}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful