Example usage for org.openqa.selenium.remote RemoteWebDriver switchTo

List of usage examples for org.openqa.selenium.remote RemoteWebDriver switchTo

Introduction

In this page you can find the example usage for org.openqa.selenium.remote RemoteWebDriver switchTo.

Prototype

@Override
    public TargetLocator switchTo() 

Source Link

Usage

From source file:com.comcast.dawg.house.EditDeviceUIIT.java

License:Apache License

@Test
public void testAddPropertyKeyExists() throws IOException {
    RemoteWebDriver driver = BrowserServiceManager.getDriver(Browser.chrome);
    MetaStb stb = MetaStbBuilder.build().uid(DEVICE_PREF).stb();
    addStb(stb);/* ww  w.  j a v  a  2s.  co m*/
    String token = MetaStbBuilder.getUID("testtoken");
    EditDeviceOverlay edOverlay = loadPageAndLaunchEditOverlay(driver, token, stb.getId());

    Assert.assertEquals(edOverlay.getRow(MetaStb.NAME).getValueText(), MetaStbBuilder.NAME);
    edOverlay.addProp(MetaStb.NAME, false);
    Alert alert = driver.switchTo().alert();
    alert.accept();
    Assert.assertEquals(edOverlay.getRow(MetaStb.NAME).getValueText(), MetaStbBuilder.NAME);
}

From source file:com.screenslicer.core.util.Util.java

License:Open Source License

public static void get(RemoteWebDriver driver, String url, Node urlNode, boolean retry) throws ActionFailed {
    boolean exception = true;
    boolean success = true;
    String origHandle = null;/*from w w w  .j  a  va 2  s.c om*/
    try {
        String source = null;
        boolean badUrl = true;
        boolean statusFail = true;
        if (urlNode != null) {
            origHandle = driver.getWindowHandle();
        }
        for (int i = 0; i < REFRESH_TRIES
                && (badUrl || statusFail || exception || CommonUtil.isEmpty(source)); i++) {
            badUrl = false;
            statusFail = false;
            exception = false;
            source = null;
            if (WebApp.DEBUG) {
                System.out.println("getting url...");
            }
            try {
                driver.getKeyboard().sendKeys(Keys.ESCAPE);
            } catch (Throwable t) {
                Log.exception(t);
            }
            if (urlNode != null) {
                try {
                    cleanUpNewWindows(driver, origHandle);
                } catch (Throwable t) {
                    Log.exception(t);
                }
            }
            try {
                Util.driverSleepVeryShort();
                if (urlNode != null) {
                    try {
                        Util.clickToNewWindow(driver, toElement(driver, urlNode));
                        Set<String> newHandles = driver.getWindowHandles();
                        for (String newHandle : newHandles) {
                            if (!origHandle.equals(newHandle)) {
                                driver.switchTo().window(newHandle);
                                break;
                            }
                        }
                    } catch (Throwable t) {
                        exception = true;
                        Log.exception(t);
                        Util.cleanUpNewWindows(driver, origHandle);
                    }
                } else {
                    driver.get("about:blank");
                    try {
                        driver.get(url);
                    } catch (TimeoutException e) {
                        Log.exception(e);
                    }
                }
                if (!exception) {
                    Util.driverSleepShort();
                    Util.driverSleepLong();
                    statusFail = HttpStatus.status(driver, urlNode != null) != 200;
                    driver.switchTo().defaultContent();
                    source = driver.getPageSource();
                    try {
                        new URL(driver.getCurrentUrl());
                        badUrl = false;
                    } catch (Throwable t) {
                        badUrl = true;
                    }
                }
            } catch (Throwable t) {
                Log.exception(t);
                exception = true;
            }
            if ((!retry || i + 1 == REFRESH_TRIES)
                    && (badUrl || statusFail || exception || CommonUtil.isEmpty(source))) {
                try {
                    driver.getKeyboard().sendKeys(Keys.ESCAPE);
                    Util.driverSleepVeryShort();
                } catch (Throwable t) {
                    Log.exception(t);
                }
                success = false;
                if (!retry) {
                    break;
                }
            }
        }
        if (WebApp.DEBUG) {
            System.out.println("getting url - done");
        }
    } catch (Throwable t) {
        Log.exception(t);
        success = false;
    }
    if (!success) {
        if (urlNode != null && origHandle != null) {
            try {
                cleanUpNewWindows(driver, origHandle);
            } catch (Throwable t) {
                Log.exception(t);
            }
        }
        throw new ActionFailed();
    }
}

From source file:com.screenslicer.core.util.Util.java

License:Open Source License

public static String newWindow(RemoteWebDriver driver) throws ActionFailed {
    try {//from ww  w  . ja v a  2  s.  co m
        String origHandle = driver.getWindowHandle();
        cleanUpNewWindows(driver, origHandle);
        try {
            driver.getKeyboard().sendKeys(Keys.chord(Keys.CONTROL + "n"));
        } catch (Throwable t) {
            Log.exception(t);
        }
        Util.driverSleepStartup();
        Collection<String> handles = new HashSet<String>(driver.getWindowHandles());
        handles.remove(origHandle);
        if (!handles.isEmpty()) {
            driver.switchTo().window(handles.iterator().next());
        } else {
            driver.executeScript("window.open('');");
            Util.driverSleepStartup();
            handles = new HashSet<String>(driver.getWindowHandles());
            handles.remove(origHandle);
            if (!handles.isEmpty()) {
                driver.switchTo().window(handles.iterator().next());
            }
        }
        return driver.getWindowHandle();
    } catch (Throwable t) {
        Log.exception(t);
        throw new ActionFailed(t);
    }
}

From source file:com.screenslicer.core.util.Util.java

License:Open Source License

public static void cleanUpNewWindows(RemoteWebDriver driver, String handleToKeep) throws ActionFailed {
    try {/* ww w .j a v a2 s.  c  om*/
        Set<String> handles = new HashSet<String>(driver.getWindowHandles());
        for (String handle : handles) {
            try {
                if (!handleToKeep.equals(handle)) {
                    driver.switchTo().window(handle);
                    driver.close();
                }
            } catch (Throwable t) {
                Log.exception(t);
            }
        }
        driver.switchTo().window(handleToKeep);
        driver.switchTo().defaultContent();
    } catch (Throwable t) {
        Log.exception(t);
        throw new ActionFailed(t);
    }
}

From source file:io.selendroid.server.model.SelendroidStandaloneDriver.java

License:Apache License

public String createNewTestSession(JSONObject caps, Integer retries) throws AndroidSdkException, JSONException {
    SelendroidCapabilities desiredCapabilities = null;

    // Convert the JSON capabilities to SelendroidCapabilities
    try {/*from  www  .  jav  a2  s.  c o  m*/
        desiredCapabilities = new SelendroidCapabilities(caps);
    } catch (JSONException e) {
        throw new SelendroidException("Desired capabilities cannot be parsed.");
    }

    // Find the App being requested for use
    AndroidApp app = appsStore.get(desiredCapabilities.getAut());
    if (app == null) {
        throw new SessionNotCreatedException(
                "The requested application under test is not configured in selendroid server.");
    }
    // adjust app based on capabilities (some parameters are session specific)
    app = augmentApp(app, desiredCapabilities);

    // Find a device to match the capabilities
    AndroidDevice device = null;
    try {
        device = getAndroidDevice(desiredCapabilities);
    } catch (AndroidDeviceException e) {
        SessionNotCreatedException error = new SessionNotCreatedException(
                "Error occured while finding android device: " + e.getMessage());
        e.printStackTrace();
        log.severe(error.getMessage());
        throw error;
    }

    // If we are using an emulator need to start it up
    if (device instanceof AndroidEmulator) {
        AndroidEmulator emulator = (AndroidEmulator) device;
        try {
            if (emulator.isEmulatorStarted()) {
                emulator.unlockEmulatorScreen();
            } else {
                Map<String, Object> config = new HashMap<String, Object>();
                if (serverConfiguration.getEmulatorOptions() != null) {
                    config.put(AndroidEmulator.EMULATOR_OPTIONS, serverConfiguration.getEmulatorOptions());
                }
                config.put(AndroidEmulator.TIMEOUT_OPTION, serverConfiguration.getTimeoutEmulatorStart());
                if (desiredCapabilities.asMap().containsKey(SelendroidCapabilities.DISPLAY)) {
                    Object d = desiredCapabilities.getCapability(SelendroidCapabilities.DISPLAY);
                    config.put(AndroidEmulator.DISPLAY_OPTION, String.valueOf(d));
                }

                Locale locale = parseLocale(desiredCapabilities);
                emulator.start(locale, deviceStore.nextEmulatorPort(), config);
            }
        } catch (AndroidDeviceException e) {
            deviceStore.release(device, app);
            if (retries > 0) {
                return createNewTestSession(caps, retries - 1);
            }
            throw new SessionNotCreatedException(
                    "Error occured while interacting with the emulator: " + emulator + ": " + e.getMessage());
        }
        emulator.setIDevice(deviceManager.getVirtualDevice(emulator.getAvdName()));
    }
    boolean appInstalledOnDevice = device.isInstalled(app);
    if (!appInstalledOnDevice || serverConfiguration.isForceReinstall()) {
        device.install(app);
    } else {
        log.info("the app under test is already installed.");
    }

    int port = getNextSelendroidServerPort();
    Boolean selendroidInstalledSuccessfully = device.isInstalled("io.selendroid." + app.getBasePackage());
    if (!selendroidInstalledSuccessfully || serverConfiguration.isForceReinstall()) {
        AndroidApp selendroidServer = createSelendroidServerApk(app);

        selendroidInstalledSuccessfully = device.install(selendroidServer);
        if (!selendroidInstalledSuccessfully) {
            if (!device.install(selendroidServer)) {
                deviceStore.release(device, app);

                if (retries > 0) {
                    return createNewTestSession(caps, retries - 1);
                }
            }
        }
    } else {
        log.info(
                "selendroid-server will not be created and installed because it already exists for the app under test.");
    }

    // Run any adb commands requested in the capabilities
    List<String> adbCommands = new ArrayList<String>();
    adbCommands.add("shell setprop log.tag.SELENDROID " + serverConfiguration.getLogLevel().name());
    adbCommands.addAll(desiredCapabilities.getPreSessionAdbCommands());

    for (String adbCommandParameter : adbCommands) {
        device.runAdbCommand(adbCommandParameter);
    }

    // It's GO TIME!
    // start the selendroid server on the device and make sure it's up
    try {
        device.startSelendroid(app, port);
    } catch (AndroidSdkException e) {
        log.info("error while starting selendroid: " + e.getMessage());

        deviceStore.release(device, app);
        if (retries > 0) {
            return createNewTestSession(caps, retries - 1);
        }
        throw new SessionNotCreatedException(
                "Error occurred while starting instrumentation: " + e.getMessage());
    }
    long start = System.currentTimeMillis();
    long startTimeOut = 20000;
    long timemoutEnd = start + startTimeOut;
    while (device.isSelendroidRunning() == false) {
        if (timemoutEnd >= System.currentTimeMillis()) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
        } else {
            throw new SelendroidException(
                    "Selendroid server on the device didn't came up after " + startTimeOut / 1000 + "sec:");
        }
    }

    // arbitrary sleeps? yay...
    // looks like after the server starts responding
    // we need to give it a moment before starting a session?
    try {
        Thread.sleep(500);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    // create the new session on the device server
    RemoteWebDriver driver;
    try {
        driver = new RemoteWebDriver(new URL("http://localhost:" + port + "/wd/hub"), desiredCapabilities);
    } catch (Exception e) {
        e.printStackTrace();
        deviceStore.release(device, app);
        throw new SessionNotCreatedException("Error occurred while creating session on Android device", e);
    }
    String sessionId = driver.getSessionId().toString();
    SelendroidCapabilities requiredCapabilities = new SelendroidCapabilities(driver.getCapabilities().asMap());
    ActiveSession session = new ActiveSession(sessionId, requiredCapabilities, app, device, port, this);

    this.sessions.put(sessionId, session);

    // We are requesting an "AndroidDriver" so automatically switch to the webview
    if (BrowserType.ANDROID.equals(desiredCapabilities.getAut())) {
        // arbitrarily high wait time, will this cover our slowest possible device/emulator?
        WebDriverWait wait = new WebDriverWait(driver, 60);
        // wait for the WebView to appear
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("android.webkit.WebView")));
        driver.switchTo().window("WEBVIEW");
        // the 'android-driver' webview has an h1 with id 'AndroidDriver' embedded in it
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("AndroidDriver")));
    }

    return sessionId;
}

From source file:io.selendroid.standalone.server.model.SelendroidStandaloneDriver.java

License:Apache License

private void switchToWebView(RemoteWebDriver driver) {
    // arbitrarily high wait time, will this cover our slowest possible device/emulator?
    WebDriverWait wait = new WebDriverWait(driver, 60);
    // wait for the WebView to appear
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("android.webkit.WebView")));
    driver.switchTo().window("WEBVIEW");
    // the 'android-driver' webview has an h1 with id 'AndroidDriver' embedded in it
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("AndroidDriver")));
}

From source file:org.miloss.fgsms.smoke.post.UITest.java

License:Mozilla Public License

private static void login() throws Exception {
    Assume.assumeFalse(drivers.isEmpty());
    //DO login/*from w  w w .j a v a 2  s  . c  om*/
    for (int i = 0; i < drivers.size(); i++) {
        RemoteWebDriver driver = drivers.get(i);
        driver.navigate().to(url);
        driver.findElementByName("username").sendKeys(props.getProperty("fgsmsadminuser"));
        driver.findElementByName("password").sendKeys(props.getProperty("fgsmsadminpass"));
        driver.findElementById("loginButton").click();
        //initial disclaimer
        driver.switchTo().alert().accept();
        if (url.startsWith("http://")) {
            //warning about ssl
            driver.switchTo().alert().accept();
        }

    }
}

From source file:org.uiautomation.ios.Demo.java

License:Apache License

public static void main(String[] args) throws Exception {

    String[] a = { "-port", "5555", "-host", "127.0.0.1",
            //"-aut", SampleApps.getUICatalogFile(),
            //"-aut", SampleApps.getUICatalogIpad(),
            //"-beta",
            "-folder", "applications", "-simulators", "-hub", "http://127.0.0.1:4444/grid/register" };

    IOSServerConfiguration config = IOSServerConfiguration.create(a);

    IOSServer server = new IOSServer(config);
    server.start();//from  ww w .java  2s.co m

    IOSCapabilities cap = IOSCapabilities.iphone("eBay");
    cap.setCapability(IOSCapabilities.IOS_SWITCHES, Arrays.asList(new String[] { "-e", "useQA", "YES" }));

    RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), cap);
    try {

        driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);

        WebElement agree = driver.findElement(By.name("Agree"));
        agree.click();

        //driver.switchTo().alert().dismiss();
        WebElement signInButton = driver.findElement(By.xpath("//UIAButton[@name='Sign In']"));
        signInButton.click();
        WebElement user = driver.findElement(By.xpath("//UIATextField[@value='User ID or email']"));
        user.sendKeys(userId);
        WebElement pass = driver.findElement(By.xpath("//UIASecureTextField[@value='Password']"));
        pass.sendKeys(password);
        WebElement element4 = driver.findElement(By.xpath("//UIAButton[@name='Done']"));
        element4.click();

        Thread.sleep(2000);
        boolean cartDown = false;
        // navigate
        String itemId = "220003725262";
        if (cartDown) {
            WebElement search = driver.findElement(By.xpath("//UIAButton[@name='Search']"));
            search.click();

            //validate
            WebElement element1 = driver.findElement(By.xpath("//UIASearchBar[@value='Search Watching']"));
            element1.sendKeys(itemId);

            // check it's there.
            WebElement result = driver.findElement(By.className("UIATableCell"));
            System.out.println(result.getAttribute("name"));

        } else {
            WebElement basket = driver.findElement(By.xpath("//UIAButton[@name='Basket, 1 item']"));
            //By.xpath("//UIAButton[matches(@name,l10n('ItemCountFormatStringPlural'))]"));
            //ItemCountFormatStringSingular
            basket.click();

            //WebElement firstItem = driver.findElement(By.xpath("//UIATableCell[2]"));
            //firstItem.click();

            WebElement search = driver.findElement(By.name("Checkout"));
            search.click();

        }

        // watch
        WebElement paypal = driver.findElement(By.name("Please login to your account"));
        paypal.click();

        while (driver.getWindowHandles().size() != 3) {
            Thread.sleep(1000);
        }

        WebElement email = null;
        while (email == null) {
            try {
                driver.switchTo().window("Web_3");
                email = driver.findElement(By.id("email"));
            } catch (NoSuchElementException e) {
                Thread.sleep(1000);
                System.out.println("not found");
            }
        }

        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

        driver.findElement(By.cssSelector(".resetter")).click();
        email.sendKeys("ppbuild-1920977828325914@paypal.com");

        WebElement password = driver.findElement(By.id("password"));
        password.sendKeys("11111111");

        WebElement login = driver.findElement(By.id("login"));
        login.click();

        Thread.sleep(30000);

    } finally {
        driver.quit();
        server.stop();
    }

}

From source file:org.uiautomation.ios.selenium.Demo.java

License:Apache License

public static void main(String[] args) throws Exception {
    IOSCapabilities catalog = IOSCapabilities.iphone("UICatalog");

    RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), catalog);
    // by default, the app starts in native mode.
    WebElement web = driver.findElement(By.xpath("//UIATableCell[contains(@name,'Web')]"));
    web.click();/*from w  w  w  .j a  v a 2  s.  co  m*/

    // now that a webview is displayed, switch to web mode.
    driver.switchTo().window("Web");

    // and select items using natural web selectors.
    final By cssSelector = By.cssSelector("a[href='http://store.apple.com/']");

    // reuse whatever contrust your webdriver tests are using.
    WebElement el = waitFor(elementToExist(driver, cssSelector));
    Assert.assertEquals(el.getAttribute("href"), "http://store.apple.com/");

    driver.quit();
}