Java Code Examples for org.openqa.selenium.remote.RemoteWebDriver

The following examples show how to use org.openqa.selenium.remote.RemoteWebDriver. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: collect-earth   Source File: BrowserService.java    License: MIT License 6 votes vote down vote up
private boolean loadPlotInDGMap(SimplePlacemarkObject placemarkObject, RemoteWebDriver driver)
		throws InterruptedException {

	boolean success = true;
	if (driver != null && waitFor("mainContent", driver) && driver instanceof JavascriptExecutor) {
		try {
			String dgmapJs = getDGMapJavascript(placemarkObject);
			driver.executeScript(dgmapJs);

			Thread.sleep( 1000 );
			// Unlock the view if it is locked
			if( isCssElementPresent(".lock.on",  driver)  ) {
				driver.findElementByCssSelector(".lock.on").click(); // UNLOCK
			}

		} catch (final Exception e) {
			processSeleniumError(e);
			success = false;
		}
	}
	return success;
}
 
Example 2
@Override
public void start() throws CandybeanException {
	capabilities.setBrowserName(candybean.config.getValue("grid.browser"));
	capabilities.setCapability("platform",candybean.config.getValue("grid.platform"));
	String ip = candybean.config.getValue("grid.ip");
	String port = candybean.config.getValue("grid.port");
	logger.info("Starting interface with ip " + ip + " and port " + port);
	try {
		URL url = new URL("http://" + ip + ":" + port +  "/wd/hub");
		System.out.println(url.toString());
		wd = new RemoteWebDriver(url, capabilities);
	} catch (MalformedURLException e) {
		throw new CandybeanException(e);
	}
	super.start(); // requires wd to be instantiated first
}
 
Example 3
Source Project: adf-selenium   Source File: ButtonTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWindowPopupButton() {
    RemoteWebDriver webdriver = driver.getDriver();
    ButtonDemoPage page = pages.goHome();

    DialogManager dialogManager = driver.getDialogManager();
    assertEquals(0, dialogManager.totalNumberOfDialogsOpen());
    assertNull(dialogManager.getCurrentDialog());

    // find an click af:button with useWindow='true'
    NewFileWindowDialog dialog = page.clickUseWindowButton(); // opens popup in new browser window

    // verify new dialog is opened and active
    assertEquals(1, dialogManager.totalNumberOfDialogsOpen());
    Dialog firstDialog = dialogManager.getCurrentDialog();
    assertNotNull(firstDialog);
    assertEquals("New File", firstDialog.getTitle(webdriver));

    // close dialog by clicking Save button in dialog
    dialog.findSaveButton().clickWithDialogDetect();
    assertEquals(0, dialogManager.totalNumberOfDialogsOpen());
}
 
Example 4
Source Project: carina   Source File: DesktopFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getVncURL(WebDriver driver) {
    String vncURL = null;
    if (driver instanceof RemoteWebDriver && "true".equals(Configuration.getCapability("enableVNC"))) {
        // TODO: resolve negative case when VNC is not supported
        final RemoteWebDriver rwd = (RemoteWebDriver) driver;
        String protocol = R.CONFIG.get(vnc_protocol);
        String host = R.CONFIG.get(vnc_host);
        String port = R.CONFIG.get(vnc_port);
        // If VNC host/port not set user them from Selenium
        if (StringUtils.isEmpty(host) || StringUtils.isEmpty(port)) {
            host = ((HttpCommandExecutor) rwd.getCommandExecutor()).getAddressOfRemoteServer().getHost();
            port = String.valueOf(((HttpCommandExecutor) rwd.getCommandExecutor()).getAddressOfRemoteServer().getPort());
        }
        vncURL = String.format(R.CONFIG.get("vnc_desktop"), protocol, host, port, rwd.getSessionId().toString());
    }
    return vncURL;
}
 
Example 5
Source Project: demo-java   Source File: UpdateSauceStatusTest.java    License: MIT License 6 votes vote down vote up
public void setUp() throws MalformedURLException {
    String username = System.getenv("SAUCE_USERNAME");
    String accessKey = System.getenv("SAUCE_ACCESS_KEY");

    ChromeOptions chromeOpts = new ChromeOptions();
    chromeOpts.setExperimentalOption("w3c", true);

    MutableCapabilities sauceOpts = new MutableCapabilities();
    sauceOpts.setCapability("username", username);
    sauceOpts.setCapability("accessKey", accessKey);

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability(ChromeOptions.CAPABILITY,  chromeOpts);
    caps.setCapability("sauce:options", sauceOpts);
    caps.setCapability("browserName", "googlechrome");
    caps.setCapability("browserVersion", "latest");
    caps.setCapability("platformName", "windows 10");

    String sauceUrl = "https://ondemand.saucelabs.com:443/wd/hub";
    URL url = new URL(sauceUrl);
    driver = new RemoteWebDriver(url, caps);
}
 
Example 6
Source Project: xframium-java   Source File: BackAction.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean _executeAction( WebDriver webDriver, List<Object> parameterList )
{
	String deviceName = getDeviceName( webDriver );
	Handset localDevice = PerfectoMobile.instance(( (DeviceWebDriver) webDriver ).getxFID() ).devices().getDevice( deviceName );

	if ( (localDevice.getOs().toLowerCase().equals( "android" )) && (webDriver instanceof DeviceWebDriver) )
	{
		try
		{
			Map<String, Object> params = new HashMap<>();
			params.put("keySequence", "BACK");
			((RemoteWebDriver) ((DeviceWebDriver) webDriver).getWebDriver()).executeScript("mobile:presskey", params);
		}
		catch ( Throwable e )
		{
			log.error("Failed to press BACK key.");
		}
	}
	else
	{
		webDriver.navigate().back();
	}
	return true;
}
 
Example 7
@Test
public void testConnection() {
    // getWebDriver {
    RemoteWebDriver driver = chrome.getWebDriver();
    // }

    // Construct a URL that the browser container can access
    // getPage {
    String hostIpAddress = chrome.getTestHostIpAddress();
    driver.get("http://" + hostIpAddress + ":" + localPort);
    // }

    String headingText = driver.findElement(By.cssSelector("h1")).getText().trim();

    assertEquals("The hardcoded success message was found on a page fetched from a local server", "It worked", headingText);
}
 
Example 8
public static WebDriver getFirefoxDriver()
            throws Exception
	{
        baseDir = new File(".").getPath();
        System.out.println("******** " + baseDir);

        String path = "src/test/resources/geckodriver";
        System.out.println("******** " + path);
		System.setProperty("webdriver.gecko.driver", path);

        DesiredCapabilities capabilities =  DesiredCapabilities.firefox();
		capabilities.setCapability("marionette", true);
        capabilities.setCapability("networkConnectionEnabled", true);
        capabilities.setCapability("browserConnectionEnabled", true);


        WebDriver driver = new RemoteWebDriver(
                new URL("http://localhost:4444"),
                capabilities);

//		WebDriver driver = new MarionetteDriver(capabilities);

		return driver;
	}
 
Example 9
Source Project: AndroidRobot   Source File: MyTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test() {
		SelendroidCapabilities capa = new SelendroidCapabilities(TEST_APP_ID);
		capa.setLaunchActivity("com.eg.android.AlipayGphone.AlipayLogin");
		WebDriver driver = new RemoteWebDriver(capa);
		//driver.switchTo().window("NATIVE_APP");//
		WebElement inputField = driver.findElement(By.id("buttonStartWebview"));
		inputField.click();
		
		driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

		System.out.println("============================================");
		WebDriver webDriver = driver.switchTo().window("WEBVIEW_0");
		System.out.println("=====================3432=======================");
		webDriver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
		System.out.println("getWindowHandle:" + webDriver.getPageSource());
		//WebElement element3 = webDriver.findElement(By.xpath("//input[@value='Send me your name!']"));
		WebElement element3 = webDriver.findElement(By.xpath("//input[@id='name_input']"));
		element3.sendKeys("he zheng");
		//element3.clear();

		webDriver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
//		inputField.sendKeys("Selendroid");
//		Assert.assertEquals("Selendroid", inputField.getText());
		//driver.quit();
	}
 
Example 10
Source Project: akita   Source File: CustomDriverProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Задает capabilities для запуска Remote драйвера для Selenoid
 *
 * @param capabilities - capabilities для установленного браузера
 * @param remoteUrl    - url для запуска тестов, например http://remoteIP:4444/wd/hub
 * @return WebDriver
 */
private WebDriver getRemoteDriver(MutableCapabilities capabilities, String remoteUrl) {
    log.info("---------------run Remote Driver---------------------");
    Boolean isSelenoidRun = loadSystemPropertyOrDefault(SELENOID, true);
    if (isSelenoidRun) {
        capabilities.setCapability("enableVNC", true);
        capabilities.setCapability("screenResolution", String.format("%sx%s", loadSystemPropertyOrDefault(WINDOW_WIDTH, DEFAULT_WIDTH),
                loadSystemPropertyOrDefault(WINDOW_HEIGHT, DEFAULT_HEIGHT)));
        String sessionName = loadSystemPropertyOrDefault(SELENOID_SESSION_NAME, "");
        if (!sessionName.isEmpty()) {
            capabilities.setCapability("name", String.format("%s %s", sessionName, AkitaScenario.getInstance().getScenario().getName()));
        }
    }
    try {
        RemoteWebDriver remoteWebDriver = new RemoteWebDriver(
            URI.create(remoteUrl).toURL(),
            capabilities
        );
        remoteWebDriver.setFileDetector(new LocalFileDetector());
        return remoteWebDriver;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source Project: neodymium-library   Source File: BrowserStatement.java    License: MIT License 6 votes vote down vote up
private boolean isWebDriverStillOpen(WebDriver webDriver)
{
    if (webDriver == null)
    {
        return false;
    }
    try
    {
        RemoteWebDriver driver = (RemoteWebDriver) ((EventFiringWebDriver) webDriver).getWrappedDriver();
        return driver.getSessionId() != null;
    }
    catch (Exception e)
    {
        LOGGER.warn("Couldn't detect if the WebDriver is still open!", e);
        return true;
    }
}
 
Example 12
Source Project: glowroot   Source File: WebDriverSetup.java    License: Apache License 2.0 5 votes vote down vote up
public void beforeEachTest(String testName, ScreenshotOnExceptionRule screenshotOnExceptionRule)
        throws Exception {
    if (SauceLabs.useSauceLabs()) {
        // need separate webdriver instance per test in order to report each test separately in
        // saucelabs
        driver = SauceLabs.getWebDriver(testName);
        // need to capture sessionId since it is needed in sauceLabsTestWatcher, after
        // driver.quit() is called
        remoteWebDriverSessionId = ((RemoteWebDriver) driver).getSessionId().toString();
    } else {
        screenshotOnExceptionRule.setDriver(driver);
    }
}
 
Example 13
Source Project: KITE   Source File: Client.java    License: Apache License 2.0 5 votes vote down vote up
/**
   * Adds the webdriver to the sessionData map.
   * 
   * @param sessionData
   * @throws KiteGridException
   */
  private void addToSessionMap(Map<WebDriver, Map<String, Object>> sessionData) throws KiteGridException {
    Map<String, Object> map = new HashMap<>();
    map.put("end_point", this);
//    if (!this.isApp()) {
      String node = TestUtils.getNode(
        this.getPaas().getUrl(),
        ((RemoteWebDriver) this.getWebDriver()).getSessionId().toString());
      if (node != null) {
        map.put("node_host", node);
      }
//    }
    sessionData.put(this.getWebDriver(), map);
  }
 
Example 14
public RemoteWebDriver getDriver() throws MalformedURLException {
    if (null == webDriver) {
        instantiateWebDriver(selectedDriverType);
    }

    return webDriver;
}
 
Example 15
Source Project: selenium-jupiter   Source File: DockerFirefoxJupiterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLatest(
        @DockerBrowser(type = FIREFOX) RemoteWebDriver driver) {
    driver.get("https://bonigarcia.github.io/selenium-jupiter/");
    assertThat(driver.getTitle(),
            containsString("JUnit 5 extension for Selenium"));
}
 
Example 16
Source Project: site-infrastructure-tests   Source File: PageSteps.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void beforeTest() {
	logger.info("Test setup...");
	ChromeOptions chromeOptions = new ChromeOptions();
	chromeOptions.addArguments("--headless");
	// driver = new ChromeDriver(chromeOptions);
	if (logger.isDebugEnabled()) {
		logger.debug("Initialising ChromeDriver...");
	}
	driver = new RemoteWebDriver(CucumberFeatureTest.getService().getUrl(), chromeOptions);
	_jsExecutor = (JavascriptExecutor) driver;
	logger.info("Test setup complete.");
}
 
Example 17
Source Project: xframium-java   Source File: NLXpathFactory.java    License: GNU General Public License v3.0 5 votes vote down vote up
public NLXpath getGenerator( DeviceWebDriver webDriver )
{
    if ( webDriver.getNativeDriver() instanceof RemoteWebDriver )
    {
        if ( webDriver.getContext() == null || webDriver.getContext().contains( "WEB" ) )
            return web;
        else
        {
            if ( webDriver.getDevice().getOs().toUpperCase().equals( "IOS" ) )
            {
                return ios;
            }
            else if ( webDriver.getDevice().getOs().toUpperCase().equals( "ANDROID" ) )
            {
                return android;
            }
        }
    }
    else if ( webDriver.getNativeDriver() instanceof AppiumDriver )
    {
        if ( webDriver.getDevice().getOs().toUpperCase().equals( "IOS" ) )
        {
            return ios;
        }
        else if ( webDriver.getDevice().getOs().toUpperCase().equals( "ANDROID" ) )
        {
            return android;
        }
    }
    
    return null;
}
 
Example 18
private RemoteWebDriver createRemoteDriver(Capabilities capabilities) {
    AqualityServices.getLocalizedLogger().info("loc.browser.grid");

    ClientFactory clientFactory = new ClientFactory();
    CommandExecutor commandExecutor = new HttpCommandExecutor(
            ImmutableMap.of(),
            browserProfile.getRemoteConnectionUrl(),
            clientFactory);

    RemoteWebDriver driver = getDriver(RemoteWebDriver.class, commandExecutor, capabilities);
    driver.setFileDetector(new LocalFileDetector());
    return driver;
}
 
Example 19
Source Project: selenium-shutterbug   Source File: Browser.java    License: MIT License 5 votes vote down vote up
private void defineCustomCommand(String name, CommandInfo info) {
    try {
        Method defineCommand = HttpCommandExecutor.class.getDeclaredMethod("defineCommand", String.class, CommandInfo.class);
        defineCommand.setAccessible(true);
        defineCommand.invoke(((RemoteWebDriver) this.driver).getCommandExecutor(), name, info);
    } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
 
Example 20
Source Project: marathonv5   Source File: JavaDriverTest.java    License: Apache License 2.0 5 votes vote down vote up
public void javaDriver() {
    driver = new JavaDriver();
    Capabilities capabilities = ((RemoteWebDriver) driver).getCapabilities();
    AssertJUnit.assertEquals("java", capabilities.getBrowserName());
    AssertJUnit.assertEquals(true, capabilities.is("takesScreenshot"));
    AssertJUnit.assertEquals(false, capabilities.is("nativeEvents"));
}
 
Example 21
@Test
public void testSessions() throws Exception {
    HttpGet request = new HttpGet("http://localhost:4723/wd/hub/sessions");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject = (JSONObject) new JSONParser().parse(EntityUtils.toString(entity));
    String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
    assertEquals(sessionId, jsonObject.get("sessionId"));
    httpClient.close();
}
 
Example 22
Source Project: IridiumApplicationTesting   Source File: BrowserDetectionImpl.java    License: MIT License 5 votes vote down vote up
@Override
public boolean isAndroid(@NotNull final WebDriver webDriver) {
	final Capabilities remoteWebDriverCapabilities = ((RemoteWebDriver) webDriver).getCapabilities();

	return remoteWebDriverCapabilities.getPlatform().is(Platform.ANDROID)
		// realMobile and Linux means a remote browserstack android device
		|| (remoteWebDriverCapabilities.getPlatform().is(Platform.LINUX)
		&& "true".equals(remoteWebDriverCapabilities.asMap().get("realMobile")));
}
 
Example 23
Source Project: demo-java   Source File: SynchSalsaVerdeTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() {
    SauceOptions options = new SauceOptions();
    options.setName(name.getMethodName());
    session = new SauceSession(options);
    RemoteWebDriver driver = session.start();
    browser = new Browser(driver);
}
 
Example 24
Source Project: selenium-jupiter   Source File: SeleniumExtension.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean supportsTestTemplate(ExtensionContext context) {
    boolean allWebDriver = false;
    if (context.getTestMethod().isPresent()) {
        allWebDriver = !stream(
                context.getTestMethod().get().getParameterTypes())
                        .map(s -> s.equals(WebDriver.class)
                                || s.equals(RemoteWebDriver.class))
                        .collect(toList()).contains(false);
    }
    return allWebDriver;
}
 
Example 25
@Test
public void webrtcTest(@Preferences({
        "media.navigator.permission.disabled=true",
        "media.navigator.streams.fake=true" }) @DockerBrowser(type = FIREFOX) RemoteWebDriver driver) {
    driver.get(
            "https://webrtc.github.io/samples/src/content/devices/input-output/");
    assertThat(driver.findElement(By.id("video")).getTagName(),
            equalTo("video"));
}
 
Example 26
Source Project: testcontainers-java   Source File: BrowserWebDriverContainer.java    License: MIT License 5 votes vote down vote up
@Override
protected void containerIsStarted(InspectContainerResponse containerInfo) {
    driver = Unreliables.retryUntilSuccess(30, TimeUnit.SECONDS,
            Timeouts.getWithTimeout(10, TimeUnit.SECONDS,
                    () ->
                        () -> new RemoteWebDriver(getSeleniumAddress(), capabilities)));

    if (vncRecordingContainer != null) {
        LOGGER.debug("Starting VNC recording");
        vncRecordingContainer.start();
    }
}
 
Example 27
Source Project: appiumpro   Source File: Edition054_Selenium_Grid_IOS.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIOS() throws MalformedURLException {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("platformName", "iOS");
    caps.setCapability("platformVersion", "11.4");
    caps.setCapability("deviceName", "iPhone 8");
    caps.setCapability("browserName", "Safari");

    driver = new RemoteWebDriver(new URL(HUB_URL), caps);
    actualTest(driver);
}
 
Example 28
@Test
public void testAndroid() throws MalformedURLException {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("platformName", "Android");
    caps.setCapability("deviceName", "Android Emulator");
    caps.setCapability("automationName", "UiAutomator2");
    caps.setCapability("browserName", "Chrome");

    driver = new RemoteWebDriver(new URL(HUB_URL), caps);
    actualTest(driver);
}
 
Example 29
private void instantiateWebDriver(DriverType driverType) throws MalformedURLException {
    System.out.println(" ");
    System.out.println("Local Operating System: " + operatingSystem);
    System.out.println("Local Architecture: " + systemArchitecture);
    System.out.println("Selected Browser: " + selectedDriverType);
    System.out.println("Connecting to Selenium Grid: " + useRemoteWebDriver);
    System.out.println(" ");

    DesiredCapabilities desiredCapabilities = new DesiredCapabilities();

    if (useRemoteWebDriver) {
        URL seleniumGridURL = new URL(System.getProperty("gridURL"));
        String desiredBrowserVersion = System.getProperty("desiredBrowserVersion");
        String desiredPlatform = System.getProperty("desiredPlatform");

        if (null != desiredPlatform && !desiredPlatform.isEmpty()) {
            desiredCapabilities.setPlatform(Platform.valueOf(desiredPlatform.toUpperCase()));
        }

        if (null != desiredBrowserVersion && !desiredBrowserVersion.isEmpty()) {
            desiredCapabilities.setVersion(desiredBrowserVersion);
        }

        desiredCapabilities.setBrowserName(selectedDriverType.toString());
        webDriver = new RemoteWebDriver(seleniumGridURL, desiredCapabilities);
    } else {
        webDriver = driverType.getWebDriverObject(desiredCapabilities);
    }
}
 
Example 30
Source Project: JTAF-ExtWebDriver   Source File: ScreenshotUtils.java    License: Apache License 2.0 5 votes vote down vote up
/***
 * Take a screenshot of the browser content. Note that while using RemoteWebDriver sessions (ie: with
 * Sauce Labs), the screenshot will be a full page of content--not only the visible content where the
 * page is scrolled (as when using a non-RemoteWebDriver session).
 * 
 * @param toSaveAs - name of the file to save the picture in (Note: must be PNG)
 * @throws IOException 
 */
public static void takeScreenshotOfPage(File toSaveAs) throws IOException {
	WebDriver wd = SessionManager.getInstance().getCurrentSession().getWrappedDriver();
	File screenshot;
	if(!(wd instanceof RemoteWebDriver)) {
		screenshot = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);		
	}
	else {
		Augmenter augmenter = new Augmenter();
		screenshot = ((TakesScreenshot) augmenter.augment(wd)).getScreenshotAs(OutputType.FILE);
	}
	FileUtils.copyFile(screenshot, toSaveAs);
}