Source:replace simple factory using polymorphism
javac HelloWorld.java
Best Selenium code snippet using org.openqa.selenium.remote.Interface FileDetector
Source:FirefoxDriver.java  
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements.  See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership.  The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License.  You may obtain a copy of the License at8//9//   http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied.  See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.firefox;18import static java.util.Collections.singletonMap;19import static org.openqa.selenium.remote.CapabilityType.PROXY;20import com.google.common.collect.ImmutableMap;21import com.google.common.collect.Maps;22import com.google.common.collect.Sets;23import org.openqa.selenium.Capabilities;24import org.openqa.selenium.ImmutableCapabilities;25import org.openqa.selenium.MutableCapabilities;26import org.openqa.selenium.Proxy;27import org.openqa.selenium.WebDriverException;28import org.openqa.selenium.html5.LocalStorage;29import org.openqa.selenium.html5.SessionStorage;30import org.openqa.selenium.html5.WebStorage;31import org.openqa.selenium.remote.CommandExecutor;32import org.openqa.selenium.remote.CommandInfo;33import org.openqa.selenium.remote.FileDetector;34import org.openqa.selenium.remote.RemoteWebDriver;35import org.openqa.selenium.remote.html5.RemoteWebStorage;36import org.openqa.selenium.remote.http.HttpMethod;37import org.openqa.selenium.remote.service.DriverCommandExecutor;38import org.openqa.selenium.remote.service.DriverService;39import java.nio.file.Path;40import java.util.Objects;41import java.util.ServiceLoader;42import java.util.Set;43import java.util.stream.StreamSupport;44/**45 * An implementation of the {#link WebDriver} interface that drives Firefox.46 * <p>47 * The best way to construct a {@code FirefoxDriver} with various options is to make use of the48 * {@link FirefoxOptions}, like so:49 *50 * <pre>51 *FirefoxOptions options = new FirefoxOptions()52 *    .setProfile(new FirefoxProfile());53 *WebDriver driver = new FirefoxDriver(options);54 * </pre>55 */56public class FirefoxDriver extends RemoteWebDriver implements WebStorage, HasExtensions {57  public static final class SystemProperty {58    /**59     * System property that defines the location of the Firefox executable file.60     */61    public static final String BROWSER_BINARY = "webdriver.firefox.bin";62    /**63     * System property that defines the location of the file where Firefox log should be stored.64     */65    public static final String BROWSER_LOGFILE = "webdriver.firefox.logfile";66    /**67     * System property that defines the additional library path (Linux only).68     */69    public static final String BROWSER_LIBRARY_PATH = "webdriver.firefox.library.path";70    /**71     * System property that defines the profile that should be used as a template.72     * When the driver starts, it will make a copy of the profile it is using,73     * rather than using that profile directly.74     */75    public static final String BROWSER_PROFILE = "webdriver.firefox.profile";76    /**77     * System property that defines the location of the webdriver.xpi browser extension to install78     * in the browser. If not set, the prebuilt extension bundled with this class will be used.79     */80    public static final String DRIVER_XPI_PROPERTY = "webdriver.firefox.driver";81    /**82     * Boolean system property that instructs FirefoxDriver to use Marionette backend,83     * overrides any capabilities specified by the user84     */85    public static final String DRIVER_USE_MARIONETTE = "webdriver.firefox.marionette";86  }87  public static final String BINARY = "firefox_binary";88  public static final String PROFILE = "firefox_profile";89  public static final String MARIONETTE = "marionette";90  private static class ExtraCommands {91    static String INSTALL_EXTENSION = "installExtension";92    static String UNINSTALL_EXTENSION = "uninstallExtension";93  }94  private static final ImmutableMap<String, CommandInfo> EXTRA_COMMANDS = ImmutableMap.of(95      ExtraCommands.INSTALL_EXTENSION,96      new CommandInfo("/session/:sessionId/moz/addon/install", HttpMethod.POST),97      ExtraCommands.UNINSTALL_EXTENSION,98      new CommandInfo("/session/:sessionId/moz/addon/uninstall", HttpMethod.POST)99  );100  private static class FirefoxDriverCommandExecutor extends DriverCommandExecutor {101    public FirefoxDriverCommandExecutor(DriverService service) {102      super(service, EXTRA_COMMANDS);103    }104  }105  protected FirefoxBinary binary;106  private RemoteWebStorage webStorage;107  public FirefoxDriver() {108    this(new FirefoxOptions());109  }110  /**111   * @deprecated Use {@link #FirefoxDriver(FirefoxOptions)}.112   */113  @Deprecated114  public FirefoxDriver(Capabilities desiredCapabilities) {115    this(new FirefoxOptions(Objects.requireNonNull(desiredCapabilities, "No capabilities seen")));116  }117  /**118   * @deprecated Use {@link #FirefoxDriver(FirefoxDriverService, FirefoxOptions)}.119   */120  @Deprecated121  public FirefoxDriver(FirefoxDriverService service, Capabilities desiredCapabilities) {122    this(123        Objects.requireNonNull(service, "No driver service provided"),124        new FirefoxOptions(desiredCapabilities));125  }126  public FirefoxDriver(FirefoxOptions options) {127    super(toExecutor(options), dropCapabilities(options));128    webStorage = new RemoteWebStorage(getExecuteMethod());129  }130  public FirefoxDriver(FirefoxDriverService service) {131    this(service, new FirefoxOptions());132  }133  public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options) {134    super(new FirefoxDriverCommandExecutor(service), dropCapabilities(options));135    webStorage = new RemoteWebStorage(getExecuteMethod());136  }137  private static CommandExecutor toExecutor(FirefoxOptions options) {138    Objects.requireNonNull(options, "No options to construct executor from");139    String sysProperty = System.getProperty(SystemProperty.DRIVER_USE_MARIONETTE);140    boolean isLegacy = (sysProperty != null && ! Boolean.parseBoolean(sysProperty))141                       ||  options.isLegacy();142    FirefoxDriverService.Builder<?, ?> builder =143        StreamSupport.stream(ServiceLoader.load(DriverService.Builder.class).spliterator(), false)144            .filter(b -> b instanceof FirefoxDriverService.Builder)145            .map(b -> (FirefoxDriverService.Builder) b)146            .filter(b -> b.isLegacy() == isLegacy)147            .findFirst().orElseThrow(WebDriverException::new);148    return new FirefoxDriverCommandExecutor(builder.withOptions(options).build());149  }150  @Override151  public void setFileDetector(FileDetector detector) {152    throw new WebDriverException(153        "Setting the file detector only works on remote webdriver instances obtained " +154        "via RemoteWebDriver");155  }156  @Override157  public LocalStorage getLocalStorage() {158    return webStorage.getLocalStorage();159  }160  @Override161  public SessionStorage getSessionStorage() {162    return webStorage.getSessionStorage();163  }164  private static boolean isLegacy(Capabilities desiredCapabilities) {165    Boolean forceMarionette = forceMarionetteFromSystemProperty();166    if (forceMarionette != null) {167      return !forceMarionette;168    }169    Object marionette = desiredCapabilities.getCapability(MARIONETTE);170    return marionette instanceof Boolean && ! (Boolean) marionette;171  }172  @Override173  public String installExtension(Path path) {174    return (String) execute(ExtraCommands.INSTALL_EXTENSION,175                            ImmutableMap.of("path", path.toAbsolutePath().toString(),176                                            "temporary", false)).getValue();177  }178  @Override179  public void uninstallExtension(String extensionId) {180    execute(ExtraCommands.UNINSTALL_EXTENSION, singletonMap("id", extensionId));181  }182  private static Boolean forceMarionetteFromSystemProperty() {183    String useMarionette = System.getProperty(SystemProperty.DRIVER_USE_MARIONETTE);184    if (useMarionette == null) {185      return null;186    }187    return Boolean.valueOf(useMarionette);188  }189  /**190   * Drops capabilities that we shouldn't send over the wire.191   *192   * Used for capabilities which aren't BeanToJson-convertable, and are only used by the local193   * launcher.194   */195  private static Capabilities dropCapabilities(Capabilities capabilities) {196    if (capabilities == null) {197      return new ImmutableCapabilities();198    }199    MutableCapabilities caps;200    if (isLegacy(capabilities)) {201      final Set<String> toRemove = Sets.newHashSet(BINARY, PROFILE);202      caps = new MutableCapabilities(203          Maps.filterKeys(capabilities.asMap(), key -> !toRemove.contains(key)));204    } else {205      caps = new MutableCapabilities(capabilities);206    }207    // Ensure that the proxy is in a state fit to be sent to the extension208    Proxy proxy = Proxy.extractFrom(capabilities);209    if (proxy != null) {210      caps.setCapability(PROXY, proxy);211    }212    return caps;213  }214}...Source:JavaDriver.java  
1/*******************************************************************************2 * Copyright 2016 Jalian Systems Pvt. Ltd.3 * 4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 * 8 *   http://www.apache.org/licenses/LICENSE-2.09 * 10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 ******************************************************************************/16package net.sourceforge.marathon.javadriver;17import java.util.Set;18import java.util.logging.Logger;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.OutputType;21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.WebDriverException;23import org.openqa.selenium.logging.Logs;24import org.openqa.selenium.remote.CapabilityType;25import org.openqa.selenium.remote.DesiredCapabilities;26import org.openqa.selenium.remote.DriverCommand;27import org.openqa.selenium.remote.FileDetector;28import org.openqa.selenium.remote.LocalFileDetector;29import org.openqa.selenium.remote.RemoteWebDriver;30import org.openqa.selenium.remote.UselessFileDetector;31import com.google.common.base.Predicate;32import com.google.common.collect.Maps;33import com.google.common.collect.Sets;34/**35 * Implementation of {@link WebDriver} interface that driver Java applications.36 * 37 * <p>38 * A {@code JavaDriver} can be created by using {@link JavaProfile} as follows:39 * </p>40 * 41 * <pre>42 * <code>43 *       JavaProfile profile = new JavaProfile(LaunchMode.COMMAND_LINE);44 *       profile.setWorkingDirectory("some-folder").setCommand("path-to-batch-script");45 *       JavaDriver driver = new JavaDriver(profile);46 * </code>47 * </pre>48 *49 */50public class JavaDriver extends RemoteWebDriver {51    public static final Logger LOGGER = Logger.getLogger(JavaDriver.class.getName());52    /**53     * Create a {@code JavaDriver}54     * 55     * <p>56     * Use {@link JavaDriver#JavaDriver(JavaProfile)}57     */58    public JavaDriver() {59        this(defaultCapabilities());60    }61    /**62     * Create a {@code JavaDriver}63     * 64     * <p>65     * Use {@link JavaDriver#JavaDriver(JavaProfile)}66     * </p>67     * 68     * @param desiredCapabilities69     *            desired capabilities70     */71    public JavaDriver(Capabilities desiredCapabilities) {72        this(desiredCapabilities, null);73    }74    /**75     * Create a {@code JavaDriver}76     * 77     * <p>78     * Use {@link JavaDriver#JavaDriver(JavaProfile)}79     * </p>80     * 81     * @param desiredCapabilities82     *            desired capabilities83     * @param requiredCapabilities84     *            required capabilities85     */86    public JavaDriver(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {87        this(extractProfile(desiredCapabilities, requiredCapabilities), desiredCapabilities, requiredCapabilities);88    }89    /**90     * Constructs a {@code JavaDriver} with the given profile91     * 92     * <p>93     * Once the {@code JavaDriver} is constructed, the AUT will be launched and94     * the driver is ready for operations. Unlike in {@link WebDriver}95     * implementations for browsers, there is no need for calling a96     * {@link WebDriver#get(String)} method.97     * </p>98     * 99     * @param profile100     *            the java profile101     */102    public JavaDriver(JavaProfile profile) {103        this(profile, defaultCapabilities());104    }105    /**106     * Constructs a {@code JavaDriver} with the given profile107     * 108     * <p>109     * Once the {@code JavaDriver} is constructed, the AUT will be launched and110     * the driver is ready for operations. Unlike in {@link WebDriver}111     * implementations for browsers, there is no need for calling a112     * {@link WebDriver#get(String)} method.113     * </p>114     * 115     * @param profile116     *            the java profile117     * @param desiredCapabilities118     *            desired capabilities119     */120    public JavaDriver(JavaProfile profile, DesiredCapabilities desiredCapabilities) {121        this(profile, defaultCapabilities(), null);122    }123    /**124     * Constructs a {@code JavaDriver} with the given profile125     * 126     * <p>127     * Once the {@code JavaDriver} is constructed, the AUT will be launched and128     * the driver is ready for operations. Unlike in {@link WebDriver}129     * implementations for browsers, there is no need for calling a130     * {@link WebDriver#get(String)} method.131     * </p>132     * 133     * <p>134     * The only capability of interest may be <code>nativeEvents</code>135     * </p>136     * 137     * @param profile138     *            the java profile139     * @param desiredCapabilities140     *            desired capabilities141     * @param requiredCapabilities142     *            required capabilities143     */144    public JavaDriver(JavaProfile profile, Capabilities desiredCapabilities, Capabilities requiredCapabilities) {145        super(new JavaDriverCommandExecutor(profile), dropCapabilities(desiredCapabilities, CapabilityType.VERSION));146    }147    private static Capabilities dropCapabilities(Capabilities capabilities, String... keysToRemove) {148        if (capabilities == null) {149            return new DesiredCapabilities();150        }151        final Set<String> toRemove = Sets.newHashSet(keysToRemove);152        DesiredCapabilities caps = new DesiredCapabilities(Maps.filterKeys(capabilities.asMap(), new Predicate<String>() {153            @Override154            public boolean apply(String key) {155                return !toRemove.contains(key);156            }157        }));158        return caps;159    }160    private static JavaProfile extractProfile(Capabilities desiredCapabilities, Capabilities requiredCapabilities) {161        JavaProfile javaProfile = new JavaProfile();162        if (requiredCapabilities == null) {163            return javaProfile;164        }165        return javaProfile;166    }167    /**168     * Default capabilities for {@code JavaDriver}169     * 170     * @return default capabilities171     */172    public static DesiredCapabilities defaultCapabilities() {173        return new DesiredCapabilities("java", "1.0", org.openqa.selenium.Platform.ANY);174    }175    /**176     * Not implemented177     *178     * @param detector179     *            The detector to use. Must not be null.180     * @see FileDetector181     * @see LocalFileDetector182     * @see UselessFileDetector183     */184    @Override185    public void setFileDetector(FileDetector detector) {186        throw new WebDriverException(187                "Setting the file detector only works on remote webdriver instances obtained " + "via RemoteWebDriver");188    }189    /**190     * Capture the screenshot and store it in the specified location.191     *192     * <p>193     * For WebDriver extending TakesScreenshot, this makes a best effort194     * depending on the browser to return the following in order of preference:195     * <ul>196     * <li>Entire page</li>197     * <li>Current window</li>198     * <li>Visible portion of the current frame</li>199     * <li>The screenshot of the entire display containing the browser</li>200     * </ul>201     *202     * <p>203     * For WebElement extending TakesScreenshot, this makes a best effort204     * depending on the browser to return the following in order of preference:205     * - The entire content of the HTML element - The visible portion of the206     * HTML element207     *208     * @param <X>209     *            Return type for getScreenshotAs.210     * @param target211     *            target type, @see OutputType212     * @return Object in which is stored information about the screenshot.213     * @throws WebDriverException214     *             on failure.215     * @throws UnsupportedOperationException216     *             if the underlying implementation does not support screenshot217     *             capturing.218     */219    @Override220    public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {221        // Get the screenshot as base64.222        String base64 = (String) execute(DriverCommand.SCREENSHOT).getValue();223        // ... and convert it.224        return target.convertFromBase64Png(base64);225    }226    public void clearlogs(String logType) {227        Logs logs = manage().logs();228        logs.get(logType);229    }230    /**231     * Quits the driver232     */233    @Override234    public void quit() {235        try {236            super.quit();237        } catch (Throwable t) {238        } finally {239        }240    }241    @Override242    protected void finalize() throws Throwable {243        quit();244    }245}...Source:ChromeDriver.java  
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements.  See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership.  The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License.  You may obtain a copy of the License at8//9//   http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied.  See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.chrome;18import com.google.common.collect.ImmutableMap;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.WebDriver;21import org.openqa.selenium.WebDriverException;22import org.openqa.selenium.html5.LocalStorage;23import org.openqa.selenium.html5.Location;24import org.openqa.selenium.html5.LocationContext;25import org.openqa.selenium.html5.SessionStorage;26import org.openqa.selenium.html5.WebStorage;27import org.openqa.selenium.interactions.HasTouchScreen;28import org.openqa.selenium.interactions.TouchScreen;29import org.openqa.selenium.mobile.NetworkConnection;30import org.openqa.selenium.remote.FileDetector;31import org.openqa.selenium.remote.RemoteTouchScreen;32import org.openqa.selenium.remote.RemoteWebDriver;33import org.openqa.selenium.remote.html5.RemoteLocationContext;34import org.openqa.selenium.remote.html5.RemoteWebStorage;35import org.openqa.selenium.remote.mobile.RemoteNetworkConnection;36/**37 * A {@link WebDriver} implementation that controls a Chrome browser running on the local machine.38 * This class is provided as a convenience for easily testing the Chrome browser. The control server39 * which each instance communicates with will live and die with the instance.40 *41 * To avoid unnecessarily restarting the ChromeDriver server with each instance, use a42 * {@link RemoteWebDriver} coupled with the desired {@link ChromeDriverService}, which is managed43 * separately. For example: <pre>{@code44 *45 * import static org.junit.Assert.assertEquals;46 *47 * import org.junit.*;48 * import org.junit.runner.RunWith;49 * import org.junit.runners.JUnit4;50 * import org.openqa.selenium.chrome.ChromeDriverService;51 * import org.openqa.selenium.remote.DesiredCapabilities;52 * import org.openqa.selenium.remote.RemoteWebDriver;53 *54 * {@literal @RunWith(JUnit4.class)}55 * public class ChromeTest extends TestCase {56 *57 *   private static ChromeDriverService service;58 *   private WebDriver driver;59 *60 *   {@literal @BeforeClass}61 *   public static void createAndStartService() {62 *     service = new ChromeDriverService.Builder()63 *         .usingDriverExecutable(new File("path/to/my/chromedriver.exe"))64 *         .usingAnyFreePort()65 *         .build();66 *     service.start();67 *   }68 *69 *   {@literal @AfterClass}70 *   public static void createAndStopService() {71 *     service.stop();72 *   }73 *74 *   {@literal @Before}75 *   public void createDriver() {76 *     driver = new RemoteWebDriver(service.getUrl(),77 *         DesiredCapabilities.chrome());78 *   }79 *80 *   {@literal @After}81 *   public void quitDriver() {82 *     driver.quit();83 *   }84 *85 *   {@literal @Test}86 *   public void testGoogleSearch() {87 *     driver.get("http://www.google.com");88 *     WebElement searchBox = driver.findElement(By.name("q"));89 *     searchBox.sendKeys("webdriver");90 *     searchBox.quit();91 *     assertEquals("webdriver - Google Search", driver.getTitle());92 *   }93 * }94 * }</pre>95 *96 * Note that unlike ChromeDriver, RemoteWebDriver doesn't directly implement97 * role interfaces such as {@link LocationContext} and {@link WebStorage}.98 * Therefore, to access that functionality, it needs to be99 * {@link org.openqa.selenium.remote.Augmenter augmented} and then cast100 * to the appropriate interface.101 *102 * @see ChromeDriverService#createDefaultService103 */104public class ChromeDriver extends RemoteWebDriver105    implements LocationContext, WebStorage, HasTouchScreen, NetworkConnection {106  private RemoteLocationContext locationContext;107  private RemoteWebStorage webStorage;108  private TouchScreen touchScreen;109  private RemoteNetworkConnection networkConnection;110  /**111   * Creates a new ChromeDriver using the {@link ChromeDriverService#createDefaultService default}112   * server configuration.113   *114   * @see #ChromeDriver(ChromeDriverService, ChromeOptions)115   */116  public ChromeDriver() {117    this(ChromeDriverService.createDefaultService(), new ChromeOptions());118  }119  /**120   * Creates a new ChromeDriver instance. The {@code service} will be started along with the driver,121   * and shutdown upon calling {@link #quit()}.122   *123   * @param service The service to use.124   * @see RemoteWebDriver#RemoteWebDriver(org.openqa.selenium.remote.CommandExecutor, Capabilities)125   */126  public ChromeDriver(ChromeDriverService service) {127    this(service, new ChromeOptions());128  }129  /**130   * Creates a new ChromeDriver instance. The {@code capabilities} will be passed to the131   * chromedriver service.132   *133   * @param capabilities The capabilities required from the ChromeDriver.134   * @see #ChromeDriver(ChromeDriverService, Capabilities)135   */136  public ChromeDriver(Capabilities capabilities) {137    this(ChromeDriverService.createDefaultService(), capabilities);138  }139  /**140   * Creates a new ChromeDriver instance with the specified options.141   *142   * @param options The options to use.143   * @see #ChromeDriver(ChromeDriverService, ChromeOptions)144   */145  public ChromeDriver(ChromeOptions options) {146    this(ChromeDriverService.createDefaultService(), options);147  }148  /**149   * Creates a new ChromeDriver instance with the specified options. The {@code service} will be150   * started along with the driver, and shutdown upon calling {@link #quit()}.151   *152   * @param service The service to use.153   * @param options The options to use.154   */155  public ChromeDriver(ChromeDriverService service, ChromeOptions options) {156    this(service, options.toCapabilities());157  }158  /**159   * Creates a new ChromeDriver instance. The {@code service} will be started along with the160   * driver, and shutdown upon calling {@link #quit()}.161   *162   * @param service The service to use.163   * @param capabilities The capabilities required from the ChromeDriver.164   */165  public ChromeDriver(ChromeDriverService service, Capabilities capabilities) {166    super(new ChromeDriverCommandExecutor(service), capabilities);167    locationContext = new RemoteLocationContext(getExecuteMethod());168    webStorage = new  RemoteWebStorage(getExecuteMethod());169    touchScreen = new RemoteTouchScreen(getExecuteMethod());170    networkConnection = new RemoteNetworkConnection(getExecuteMethod());171  }172  @Override173  public void setFileDetector(FileDetector detector) {174    throw new WebDriverException(175        "Setting the file detector only works on remote webdriver instances obtained " +176        "via RemoteWebDriver");177  }178  @Override179  public LocalStorage getLocalStorage() {180    return webStorage.getLocalStorage();181  }182  @Override183  public SessionStorage getSessionStorage() {184    return webStorage.getSessionStorage();185  }186  @Override187  public Location location() {188    return locationContext.location();189  }190  @Override191  public void setLocation(Location location) {192    locationContext.setLocation(location);193  }194  @Override195  public TouchScreen getTouch() {196    return touchScreen;197  }198  @Override199  public ConnectionType getNetworkConnection() {200    return networkConnection.getNetworkConnection();201  }202  @Override203  public ConnectionType setNetworkConnection(ConnectionType type) {204    return networkConnection.setNetworkConnection(type);205  }206  /**207   * Launches Chrome app specified by id.208   *209   * @param id chrome app id210   */211  public void launchApp(String id) {212    execute(ChromeDriverCommand.LAUNCH_APP, ImmutableMap.of("id", id));213  }214  215}...Source:ChromiumDriver.java  
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements.  See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership.  The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License.  You may obtain a copy of the License at8//9//   http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied.  See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.chromium;18import com.google.common.collect.ImmutableMap;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.WebDriver;21import org.openqa.selenium.WebDriverException;22import org.openqa.selenium.devtools.Connection;23import org.openqa.selenium.devtools.DevTools;24import org.openqa.selenium.devtools.HasDevTools;25import org.openqa.selenium.html5.LocalStorage;26import org.openqa.selenium.html5.Location;27import org.openqa.selenium.html5.LocationContext;28import org.openqa.selenium.html5.SessionStorage;29import org.openqa.selenium.html5.WebStorage;30import org.openqa.selenium.interactions.HasTouchScreen;31import org.openqa.selenium.interactions.TouchScreen;32import org.openqa.selenium.mobile.NetworkConnection;33import org.openqa.selenium.remote.CommandExecutor;34import org.openqa.selenium.remote.FileDetector;35import org.openqa.selenium.remote.RemoteTouchScreen;36import org.openqa.selenium.remote.RemoteWebDriver;37import org.openqa.selenium.remote.html5.RemoteLocationContext;38import org.openqa.selenium.remote.html5.RemoteWebStorage;39import org.openqa.selenium.remote.http.HttpClient;40import org.openqa.selenium.remote.mobile.RemoteNetworkConnection;41import java.util.Map;42import java.util.Objects;43import java.util.Optional;44/**45 * A {@link WebDriver} implementation that controls a Chromium browser running on the local machine.46 * This class is provided as a convenience for easily testing the Chromium browser. The control server47 * which each instance communicates with will live and die with the instance.48 *49 * To avoid unnecessarily restarting the ChromiumDriver server with each instance, use a50 * {@link RemoteWebDriver} coupled with the desired WebDriverService, which is managed51 * separately.52 *53 * Note that unlike ChromiumDriver, RemoteWebDriver doesn't directly implement54 * role interfaces such as {@link LocationContext} and {@link WebStorage}.55 * Therefore, to access that functionality, it needs to be56 * {@link org.openqa.selenium.remote.Augmenter augmented} and then cast57 * to the appropriate interface.58 */59public class ChromiumDriver extends RemoteWebDriver60    implements HasDevTools, HasTouchScreen, LocationContext, NetworkConnection, WebStorage {61  private final RemoteLocationContext locationContext;62  private final RemoteWebStorage webStorage;63  private final TouchScreen touchScreen;64  private final RemoteNetworkConnection networkConnection;65  private final Optional<Connection> connection;66  private final Optional<DevTools> devTools;67  protected ChromiumDriver(CommandExecutor commandExecutor, Capabilities capabilities, String capabilityKey) {68    super(commandExecutor, capabilities);69    locationContext = new RemoteLocationContext(getExecuteMethod());70    webStorage = new RemoteWebStorage(getExecuteMethod());71    touchScreen = new RemoteTouchScreen(getExecuteMethod());72    networkConnection = new RemoteNetworkConnection(getExecuteMethod());73    HttpClient.Factory factory = HttpClient.Factory.createDefault();74    connection = ChromiumDevToolsLocator.getChromeConnector(75        factory,76        getCapabilities(),77        capabilityKey);78    devTools = connection.map(DevTools::new);79  }80  @Override81  public void setFileDetector(FileDetector detector) {82    throw new WebDriverException(83        "Setting the file detector only works on remote webdriver instances obtained " +84        "via RemoteWebDriver");85  }86  @Override87  public LocalStorage getLocalStorage() {88    return webStorage.getLocalStorage();89  }90  @Override91  public SessionStorage getSessionStorage() {92    return webStorage.getSessionStorage();93  }94  @Override95  public Location location() {96    return locationContext.location();97  }98  @Override99  public void setLocation(Location location) {100    locationContext.setLocation(location);101  }102  @Override103  public TouchScreen getTouch() {104    return touchScreen;105  }106  @Override107  public ConnectionType getNetworkConnection() {108    return networkConnection.getNetworkConnection();109  }110  @Override111  public ConnectionType setNetworkConnection(ConnectionType type) {112    return networkConnection.setNetworkConnection(type);113  }114  /**115   * Launches Chrome app specified by id.116   *117   * @param id Chrome app id.118   */119  public void launchApp(String id) {120    execute(ChromiumDriverCommand.LAUNCH_APP, ImmutableMap.of("id", id));121  }122  /**123   * Execute a Chrome Devtools Protocol command and get returned result. The124   * command and command args should follow125   * <a href="https://chromedevtools.github.io/devtools-protocol/">chrome126   * devtools protocol domains/commands</a>.127   */128  public Map<String, Object> executeCdpCommand(String commandName, Map<String, Object> parameters) {129    Objects.requireNonNull(commandName, "Command name must be set.");130    Objects.requireNonNull(parameters, "Parameters for command must be set.");131    @SuppressWarnings("unchecked")132    Map<String, Object> toReturn = (Map<String, Object>) getExecuteMethod().execute(133        ChromiumDriverCommand.EXECUTE_CDP_COMMAND,134        ImmutableMap.of("cmd", commandName, "params", parameters));135    return ImmutableMap.copyOf(toReturn);136  }137  @Override138  public DevTools getDevTools() {139    return devTools.orElseThrow(() -> new WebDriverException("Unable to create DevTools connection"));140  }141  public String getCastSinks() {142    Object response =  getExecuteMethod().execute(ChromiumDriverCommand.GET_CAST_SINKS, null);143    return response.toString();144  }145  public String getCastIssueMessage() {146    Object response = getExecuteMethod().execute(ChromiumDriverCommand.GET_CAST_ISSUE_MESSAGE, null);147    return response.toString();148  }149  public void selectCastSink(String deviceName) {150    Object response =  getExecuteMethod().execute(ChromiumDriverCommand.SET_CAST_SINK_TO_USE, ImmutableMap.of("sinkName", deviceName));151  }152  public void startTabMirroring(String deviceName) {153    Object response =  getExecuteMethod().execute(ChromiumDriverCommand.START_CAST_TAB_MIRRORING, ImmutableMap.of("sinkName", deviceName));154  }155  public void stopCasting(String deviceName) {156    Object response = getExecuteMethod().execute(ChromiumDriverCommand.STOP_CASTING, ImmutableMap.of("sinkName", deviceName));157  }158  public void setPermission(String name, String value) {159    Object response = getExecuteMethod().execute(ChromiumDriverCommand.SET_PERMISSION,160      ImmutableMap.of("descriptor", ImmutableMap.of("name", name), "state", value));161  }162  @Override163  public void quit() {164    connection.ifPresent(Connection::close);165    super.quit();166  }167}...Source:OperaDriver.java  
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements.  See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership.  The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License.  You may obtain a copy of the License at8//9//   http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied.  See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.opera;18import org.openqa.selenium.Capabilities;19import org.openqa.selenium.WebDriver;20import org.openqa.selenium.WebDriverException;21import org.openqa.selenium.html5.LocalStorage;22import org.openqa.selenium.html5.Location;23import org.openqa.selenium.html5.LocationContext;24import org.openqa.selenium.html5.SessionStorage;25import org.openqa.selenium.html5.WebStorage;26import org.openqa.selenium.remote.FileDetector;27import org.openqa.selenium.remote.RemoteWebDriver;28import org.openqa.selenium.remote.html5.RemoteLocationContext;29import org.openqa.selenium.remote.html5.RemoteWebStorage;30import org.openqa.selenium.remote.service.DriverCommandExecutor;31/**32 * A {@link WebDriver} implementation that controls a Blink-based Opera browser running on the local33 * machine. This class is provided as a convenience for easily testing the Chrome browser. The34 * control server which each instance communicates with will live and die with the instance.35 *36 * To avoid unnecessarily restarting the OperaDriver server with each instance, use a37 * {@link RemoteWebDriver} coupled with the desired {@link OperaDriverService}, which is managed38 * separately. For example: <pre>{@code39 *40 * import static org.junit.Assert.assertEquals;41 *42 * import org.junit.*;43 * import org.junit.runner.RunWith;44 * import org.junit.runners.JUnit4;45 * import org.openqa.selenium.opera.OperaDriverService;46 * import org.openqa.selenium.remote.DesiredCapabilities;47 * import org.openqa.selenium.remote.RemoteWebDriver;48 *49 * {@literal @RunWith(JUnit4.class)}50 * public class OperaTest extends TestCase {51 *52 *   private static OperaDriverService service;53 *   private WebDriver driver;54 *55 *   {@literal @BeforeClass}56 *   public static void createAndStartService() {57 *     service = new OperaDriverService.Builder()58 *         .usingDriverExecutable(new File("path/to/my/operadriver.exe"))59 *         .usingAnyFreePort()60 *         .build();61 *     service.start();62 *   }63 *64 *   {@literal @AfterClass}65 *   public static void createAndStopService() {66 *     service.stop();67 *   }68 *69 *   {@literal @Before}70 *   public void createDriver() {71 *     driver = new RemoteWebDriver(service.getUrl(),72 *         DesiredCapabilities.opera());73 *   }74 *75 *   {@literal @After}76 *   public void quitDriver() {77 *     driver.quit();78 *   }79 *80 *   {@literal @Test}81 *   public void testGoogleSearch() {82 *     driver.get("http://www.google.com");83 *     WebElement searchBox = driver.findElement(By.name("q"));84 *     searchBox.sendKeys("webdriver");85 *     searchBox.quit();86 *     assertEquals("webdriver - Google Search", driver.getTitle());87 *   }88 * }89 * }</pre>90 *91 * Note that unlike OperaDriver, RemoteWebDriver doesn't directly implement92 * role interfaces such as {@link LocationContext} and {@link WebStorage}.93 * Therefore, to access that functionality, it needs to be94 * {@link org.openqa.selenium.remote.Augmenter augmented} and then cast95 * to the appropriate interface.96 *97 * @see OperaDriverService#createDefaultService98 */99public class OperaDriver extends RemoteWebDriver100    implements LocationContext, WebStorage {101  private RemoteLocationContext locationContext;102  private RemoteWebStorage webStorage;103  /**104   * Creates a new OperaDriver using the {@link OperaDriverService#createDefaultService default}105   * server configuration.106   *107   * @see #OperaDriver(OperaDriverService, OperaOptions)108   */109  public OperaDriver() {110    this(OperaDriverService.createDefaultService(), new OperaOptions());111  }112  /**113   * Creates a new OperaDriver instance. The {@code service} will be started along with the driver,114   * and shutdown upon calling {@link #quit()}.115   *116   * @param service The service to use.117   * @see #OperaDriver(OperaDriverService, OperaOptions)118   */119  public OperaDriver(OperaDriverService service) {120    this(service, new OperaOptions());121  }122  /**123   * Creates a new OperaDriver instance. The {@code capabilities} will be passed to the124   * chromedriver service.125   *126   * @param capabilities The capabilities required from the OperaDriver.127   * @see #OperaDriver(OperaDriverService, Capabilities)128   */129  public OperaDriver(Capabilities capabilities) {130    this(OperaDriverService.createDefaultService(), capabilities);131  }132  /**133   * Creates a new OperaDriver instance with the specified options.134   *135   * @param options The options to use.136   * @see #OperaDriver(OperaDriverService, OperaOptions)137   */138  public OperaDriver(OperaOptions options) {139    this(OperaDriverService.createDefaultService(), options);140  }141  /**142   * Creates a new OperaDriver instance with the specified options. The {@code service} will be143   * started along with the driver, and shutdown upon calling {@link #quit()}.144   *145   * @param service The service to use.146   * @param options The options to use.147   */148  public OperaDriver(OperaDriverService service, OperaOptions options) {149    this(service, options.toCapabilities());150  }151  /**152   * Creates a new OperaDriver instance. The {@code service} will be started along with the153   * driver, and shutdown upon calling {@link #quit()}.154   *155   * @param service The service to use.156   * @param capabilities The capabilities required from the OperaDriver.157   */158  public OperaDriver(OperaDriverService service, Capabilities capabilities) {159    super(new DriverCommandExecutor(service), capabilities);160    locationContext = new RemoteLocationContext(getExecuteMethod());161    webStorage = new  RemoteWebStorage(getExecuteMethod());162  }163  @Override164  public void setFileDetector(FileDetector detector) {165    throw new WebDriverException(166        "Setting the file detector only works on remote webdriver instances obtained " +167        "via RemoteWebDriver");168  }169  @Override170  public LocalStorage getLocalStorage() {171    return webStorage.getLocalStorage();172  }173  @Override174  public SessionStorage getSessionStorage() {175    return webStorage.getSessionStorage();176  }177  @Override178  public Location location() {179    return locationContext.location();180  }181  @Override182  public void setLocation(Location location) {183    locationContext.setLocation(location);184  }185}...Source:IPhoneDriver.java  
1/*2Copyright 2012 Software Freedom Conservancy3Copyright 2007-2010 Selenium committers4Licensed 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.iphone;15import java.net.URL;16import java.util.HashSet;17import java.util.List;18import java.util.Set;19import org.openqa.selenium.Alert;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.OutputType;22import org.openqa.selenium.TakesScreenshot;23import org.openqa.selenium.WebDriverException;24import org.openqa.selenium.WebElement;25import org.openqa.selenium.html5.LocalStorage;26import org.openqa.selenium.html5.SessionStorage;27import org.openqa.selenium.html5.WebStorage;28import org.openqa.selenium.remote.CommandExecutor;29import org.openqa.selenium.remote.DesiredCapabilities;30import org.openqa.selenium.remote.DriverCommand;31import org.openqa.selenium.remote.FileDetector;32import org.openqa.selenium.remote.RemoteWebDriver;33import com.google.common.collect.ImmutableMap;34/**35 * IPhoneDriver is a driver for running tests on Mobile Safari on the iPhone, iPad and iPod Touch.36 * 37 * The driver uses WebDriver's remote REST interface to communicate with the iphone. The iphone (or38 * iphone simulator) must be running the iWebDriver app.39 */40public class IPhoneDriver extends RemoteWebDriver implements TakesScreenshot, WebStorage {41  /**42   * This is the default port and URL for iWebDriver. Eventually it would be nice to use DNS-SD to43   * detect iWebDriver instances running non locally or on non-default ports.44   */45  protected static final String DEFAULT_IWEBDRIVER_URL =46      "http://localhost:3001/wd/hub";47  48  public enum STORAGE_TYPE { local, session }49  /**50   * Create an IPhoneDriver that will use the given {@code executor} to communicate with the51   * iWebDriver app.52   * 53   * @param executor The executor to use for communicating with the iPhone.54   */55  public IPhoneDriver(CommandExecutor executor) {56    super(executor, DesiredCapabilities.iphone());57  }58  /**59   * Create an IPhoneDriver connected to the remote address passed in.60   * 61   * @param remoteAddress The full URL of the remote client (device or simulator).62   * @throws Exception63   * @see #IPhoneDriver(String)64   */65  public IPhoneDriver(URL remoteAddress) throws Exception {66    super(remoteAddress, DesiredCapabilities.iphone());67  }68  /**69   * Create an IPhoneDriver connected to the remote address passed in.70   * 71   * @param remoteAddress The full URL of the remote client running iWebDriver.72   * @throws Exception73   * @see #IPhoneDriver(URL)74   */75  public IPhoneDriver(String remoteAddress) throws Exception {76    this(new URL(remoteAddress));77  }78  /**79   * Create an IPhoneDriver connected to an iphone simulator running on the local machine.80   * 81   * @throws Exception82   */83  public IPhoneDriver() throws Exception {84    this(DEFAULT_IWEBDRIVER_URL);85  }86  public IPhoneDriver(Capabilities ignored) throws Exception {87    this();88  }89  @Override90  public void setFileDetector(FileDetector detector) {91    throw new WebDriverException(92        "Setting the file detector only works on remote webdriver instances obtained " +93        "via RemoteWebDriver");94  }95  @Override96  public void close() {97    throw new UnsupportedOperationException("Not yet implemented");98  }99  @Override100  public TargetLocator switchTo() {101    return new IPhoneTargetLocator();102  }103  private class IPhoneTargetLocator extends RemoteTargetLocator {104    public WebElement activeElement() {105      return (WebElement) executeScript("return document.activeElement || document.body;");106    }107    public Alert alert() {108      throw new UnsupportedOperationException("alert()");109    }110  }111  public <X> X getScreenshotAs(OutputType<X> target) {112    String png = (String) execute(DriverCommand.SCREENSHOT).getValue();113    // ... and convert it.114    return target.convertFromBase64Png(png);115  }116  public LocalStorage getLocalStorage() {117    return new IPhoneStorage(STORAGE_TYPE.local);118  }119  public SessionStorage getSessionStorage() {120    return new IPhoneStorage(STORAGE_TYPE.session);121  }122  private class IPhoneStorage implements LocalStorage, SessionStorage {123	private STORAGE_TYPE t;124	125	public IPhoneStorage(STORAGE_TYPE type) {126		t = type;127	}128	129	public String getItem(String key) {130		return (String) execute(t==STORAGE_TYPE.local?131				DriverCommand.GET_LOCAL_STORAGE_ITEM : DriverCommand.GET_SESSION_STORAGE_ITEM, 132				ImmutableMap.of("key", key)).getValue();133	}134	@SuppressWarnings("unchecked")135	public Set<String> keySet() {136		return new HashSet<String>((List<String>) execute(t==STORAGE_TYPE.local?137				DriverCommand.GET_LOCAL_STORAGE_KEYS : DriverCommand.GET_SESSION_STORAGE_KEYS).getValue());138	}139	public void setItem(String key, String value) {140		execute(t==STORAGE_TYPE.local?141				DriverCommand.SET_LOCAL_STORAGE_ITEM : DriverCommand.SET_SESSION_STORAGE_ITEM, 142				ImmutableMap.of("key", key, "value", value));143	}144	public String removeItem(String key) {145		return (String) execute(t==STORAGE_TYPE.local?146				DriverCommand.REMOVE_LOCAL_STORAGE_ITEM : DriverCommand.REMOVE_SESSION_STORAGE_ITEM, 147				ImmutableMap.of("key", key)).getValue();148	}149	public void clear() {150		execute(t==STORAGE_TYPE.local?151				DriverCommand.CLEAR_LOCAL_STORAGE : DriverCommand.CLEAR_SESSION_STORAGE);152	}153	public int size() {154		return ((Number) execute(t==STORAGE_TYPE.local?155				DriverCommand.GET_LOCAL_STORAGE_SIZE : DriverCommand.GET_SESSION_STORAGE_SIZE).getValue()).intValue();156	}157	  158  }159}...Source:MarionetteDriver.java  
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements.  See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership.  The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License.  You may obtain a copy of the License at8//9//   http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied.  See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.firefox;18import com.google.common.base.Throwables;19import org.openqa.selenium.Beta;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.WebDriverException;22import org.openqa.selenium.WebElement;23import org.openqa.selenium.remote.DesiredCapabilities;24import org.openqa.selenium.remote.FileDetector;25import org.openqa.selenium.remote.RemoteWebDriver;26import org.openqa.selenium.remote.service.DriverCommandExecutor;27import java.util.List;28/**29 * An implementation of the {#link WebDriver} interface that drives Firefox using Marionette interface.30 */31@Beta32public class MarionetteDriver extends RemoteWebDriver {33  /**34   * Port which is used by default.35   */36  private final static int DEFAULT_PORT = 0;37  public MarionetteDriver() {38    this(null, null, DEFAULT_PORT);39  }40  public MarionetteDriver(Capabilities capabilities) {41    this(null, capabilities, DEFAULT_PORT);42  }43  public MarionetteDriver(int port) {44    this(null, null, port);45  }46  public MarionetteDriver(GeckoDriverService service) {47    this(service, null, DEFAULT_PORT);48  }49  public MarionetteDriver(GeckoDriverService service, Capabilities capabilities) {50    this(service, capabilities, DEFAULT_PORT);51  }52  public MarionetteDriver(GeckoDriverService service, Capabilities capabilities,53                                int port) {54    if (capabilities == null) {55      capabilities = DesiredCapabilities.firefox();56    }57    if (service == null) {58      service = setupService(port);59    }60    run(service, capabilities);61  }62  @Override63  public int getW3CStandardComplianceLevel() {64    return 1;65  }66  private void run(GeckoDriverService service, Capabilities capabilities) {67    setCommandExecutor(new DriverCommandExecutor(service));68    startSession(capabilities);69  }70  @Override71  public void setFileDetector(FileDetector detector) {72    throw new WebDriverException(73      "Setting the file detector only works on remote webdriver instances obtained " +74      "via RemoteWebDriver");75  }76  private GeckoDriverService setupService(int port) {77    try {78      GeckoDriverService.Builder builder = new GeckoDriverService.Builder();79      builder.usingPort(port);80      return builder.build();81    } catch (IllegalStateException ex) {82      throw Throwables.propagate(ex);83    }84  }85}...Source:CachedElement.java  
1package foodtruck.element.pagesource;2import org.openqa.selenium.TakesScreenshot;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.remote.FileDetector;5import org.openqa.selenium.remote.RemoteWebDriver;6import java.util.Optional;7/**8 * @author Cheffey9 */10public interface CachedElement extends WebElement, TakesScreenshot {11    Optional<Bounds> getCacheRect();12    Optional<String> getCacheText();13    Optional<Boolean> getCacheDisplayed();14    String getId();15    void setId(String id);16    void setParent(RemoteWebDriver driver);17    void setFileDetector(FileDetector detector);18    Bounds getRect();19    Optional<String> getCacheTestID();20}...Interface FileDetector
Using AI Code Generation
1package selenium;2import java.io.File;3import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.remote.FileDetector;8import org.openqa.selenium.remote.LocalFileDetector;9import org.openqa.selenium.remote.RemoteWebElement;10public class FileUploadUsingFileDetector {11	public static void main(String[] args) {12		System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver.exe");13		WebDriver driver = new ChromeDriver();14		driver.manage().window().maximize();15		upload.click();16		FileDetector detector = new LocalFileDetector();17		((RemoteWebElement)upload).setFileDetector(detector);18		upload.sendKeys("D:\\Selenium\\Test.txt");19	}20}21package selenium;22import java.io.File;23import org.openqa.selenium.By;24import org.openqa.selenium.WebDriver;25import org.openqa.selenium.WebElement;26import org.openqa.selenium.chrome.ChromeDriver;27import org.openqa.selenium.remote.FileDetector;28import org.openqa.selenium.remote.RemoteFileDetector;29import org.openqa.selenium.remote.RemoteWebElement;30public class FileUploadUsingFileDetector {31	public static void main(String[] args) {32		System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver.exe");33		WebDriver driver = new ChromeDriver();34		driver.manage().window().maximize();35		upload.click();Interface FileDetector
Using AI Code Generation
1import org.openqa.selenium.remote.FileDetector;2import org.openqa.selenium.remote.LocalFileDetector;3import org.openqa.selenium.remote.RemoteWebDriver;4import org.openqa.selenium.TakesScreenshot;5import org.openqa.selenium.OutputType;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.By;10import org.openqa.selenium.WebDriver;11import org.openqa.selenium.WebElement;12import org.openqa.selenium.By;13import org.openqa.selenium.WebDriver;14import org.openqa.selenium.WebElement;15import org.openqa.selenium.By;16import org.openqa.selenium.WebDriver;17import org.openqa.selenium.WebElement;18import org.openqa.selenium.By;19import org.openqa.selenium.WebDriver;20import org.openqa.selenium.WebElement;21import org.openqa.selenium.By;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.WebElement;24import org.openqa.selenium.By;25import org.openqa.selenium.WebDriver;26import org.openqa.selenium.WebElement;27import org.openqa.selenium.By;28import org.openqa.selenium.WebDriver;29import org.openqa.selenium.WebElement;Interface FileDetector
Using AI Code Generation
1import org.openqa.selenium.FileDetector;2import org.openqa.selenium.LocalFileDetector;3import org.openqa.selenium.remote.RemoteWebDriver;4public class FileUploadTest {5    public static void main(String[] args) {6        WebDriver driver = new FirefoxDriver();7        ((RemoteWebDriver)driver).setFileDetector(new LocalFileDetector());8        WebElement uploadElement = driver.findElement(By.name("uploaded_file"));9        uploadElement.sendKeys("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");10    }11}Interface FileDetector
Using AI Code Generation
1package org.openqa.selenium.remote;2import java.io.File;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.By;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.chrome.ChromeOptions;8public class FileUploadUsingRemoteFileDetector {9public static void main(String[] args) {10System.setProperty("webdriver.chrome.driver","C:\\Users\\Rajesh\\Downloads\\chromedriver.exe");11ChromeOptions options = new ChromeOptions();12options.setFileDetector(new LocalFileDetector());13WebDriver driver = new ChromeDriver(options);14WebElement uploadElement = driver.findElement(By.id("fileupload"));15uploadElement.sendKeys("C:\\Users\\Rajesh\\Downloads\\chromedriver.exe");16}17}Interface FileDetector
Using AI Code Generation
1import org.openqa.selenium.support.FileDetector;2import org.openqa.selenium.support.ui.LocalFileDetector;3import org.openqa.selenium.support.ui.RemoteWebElement;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.remote.DesiredCapabilities;7public class FileUpload {8	public static void main(String[] args) {9		System.setProperty("webdriver.chrome.driver", "C:\\Users\\mukesh.otwani\\Desktop\\Selenium\\chromedriver.exe");10		WebDriver driver = new ChromeDriver();Interface FileDetector
Using AI Code Generation
1FileDetector detector = new LocalFileDetector();2driver.setFileDetector(detector);3WebElement upload = driver.findElement(By.id("upload"));4upload.sendKeys("C:\\Users\\Selenium\\Desktop\\test.txt");5driver.findElement(By.id("uploadbutton")).click();6driver.close();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.
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.
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.
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.
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.
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.
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.
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.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
