Example usage for org.openqa.selenium WebDriver manage

List of usage examples for org.openqa.selenium WebDriver manage

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver manage.

Prototype

Options manage();

Source Link

Document

Gets the Option interface

Usage

From source file:org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest.java

License:Open Source License

public static void navigateToUrl(String url) throws Exception {

    try {/*ww  w  .  ja  va 2s . c  o m*/
        WebDriver driver = GeneralUIUtils.getDriver();
        System.out.println("navigating to URL :" + url);
        driver.manage().window().maximize();
        driver.manage().deleteAllCookies();
        driver.navigate().to(url);
        GeneralUIUtils.windowZoomOut();
        GeneralUIUtils.waitForLoader();
    } catch (Exception e) {
        System.out.println("browser is unreachable");
        extendTest.log(LogStatus.ERROR, "browser is unreachable");
        Assert.fail("browser is unreachable");
    }
}

From source file:org.opennms.smoketest.BSMAdminIT.java

License:Open Source License

private ExpectedCondition<Boolean> getElementNotPresentCondition(final By by) {
    return ExpectedConditions.not(new ExpectedCondition<Boolean>() {
        @Nullable//  ww w.j  av a2  s .  c om
        @Override
        public Boolean apply(@Nullable WebDriver input) {
            try {
                // the default implicit wait timeout is too long, make it shorter
                input.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
                WebElement elementFound = input.findElement(by);
                return elementFound != null;
            } catch (NoSuchElementException | StaleElementReferenceException ex) {
                return false;
            } finally {
                // set the implicit wait timeout back to the value it has been before
                input.manage().timeouts().implicitlyWait(LOAD_TIMEOUT, TimeUnit.MILLISECONDS);
            }
        }
    });
}

From source file:org.safs.selenium.webdriver.DCDriverCommand.java

License:Open Source License

/**
 * TODO Need to move to class WDLibrary, this doesn't work yet!!!
 * @param webdriver//from ww w  .j  av  a2 s .c o  m
 * @throws SeleniumPlusException
 */
static void focusWindow(WebDriver webdriver) throws SeleniumPlusException {
    try {
        org.openqa.selenium.Point position = webdriver.manage().window().getPosition();
        org.openqa.selenium.Dimension dim = webdriver.manage().window().getSize();
        webdriver.manage().window().maximize();
        webdriver.manage().window().setPosition(position);
        webdriver.manage().window().setSize(dim);
        webdriver.switchTo().window(webdriver.getWindowHandle());
        WDLibrary.executeScript("window.focus();");
    } catch (Exception e) {
        throw new SeleniumPlusException("Failed to minimize current browser window" + e.getMessage());
    }
}

From source file:org.safs.selenium.webdriver.lib.SearchObject.java

License:Open Source License

/** 
 * Before doing any component search, we make sure we are in the correct frame.  
 * Frame information may or may not be within the provided recognition string.
 * @param recognitionString/*from   w w  w.j  av a2  s . co m*/
 */
protected static SwitchFramesResults _switchFrames(String recognitionString) {
    String debugmsg = StringUtils.debugmsg(SearchObject.class, "_swithcFrames");

    String[] st = StringUtils.getTokenArray(recognitionString, childSeparator, escapeChar);
    /* rsWithoutFrames: Recognition String may contain some Frame-RS, after handling the
     * frames, these Frame-RS are no longer useful, so they will be removed and the rest
     * RS will be kept in the list rsWithoutFrames
     */
    List<String> rsWithoutFrames = new ArrayList<String>();
    TargetLocator targetLocator = null;
    boolean haveSwichedFrame = false;

    //1. Handle the Frames Recognition String
    try {
        WebDriver webdriver = getWebDriver();
        lastVisitedURL = webdriver.getCurrentUrl();
        targetLocator = webdriver.switchTo();
        //very IMPORTANT step: Switch back to the top window or first frame
        targetLocator.defaultContent();
        boolean done = false;
        boolean retried = false;
        while (!done) {

            //Get information about the browser window by "javascript code",
            //as Selenium window object doesn't provide enough information.
            Window window = webdriver.manage().window();
            Object windowObject = BrowserWindow.getWindowObjectByJS(window);
            if (windowObject != null) {
                try {
                    lastBrowserWindow = new BrowserWindow(windowObject);
                    IndependantLog.debug(
                            debugmsg + " DOM window Object retrieved successfully.  Evaluating information...");
                } catch (Exception e) {
                    IndependantLog.warn(debugmsg + e.getMessage());
                    if (lastBrowserWindow == null) {
                        IndependantLog.error(
                                debugmsg + " lastBrowserWindow is null, create a default BrowserWindow.");
                        lastBrowserWindow = new BrowserWindow();
                    } else {
                        IndependantLog.debug(debugmsg + "Retaining the last Browser window object instead.");
                    }
                }
                done = true;
            } else {
                // CANAGL -- resolving problems in IE after "Login"
                // DEBUG Experimental -- IE not working the same as other browsers
                IndependantLog.debug(debugmsg + " DOM window Object could not be retrieved.");
                if (!retried) {
                    IndependantLog.debug(debugmsg + " retrying a new targetLocator WebDriver...");
                    webdriver = reconnectLastWebDriver();

                    IndependantLog.debug(debugmsg + " changing the last visited URL from '" + lastVisitedURL
                            + "' to '" + webdriver.getCurrentUrl() + "'");
                    lastVisitedURL = webdriver.getCurrentUrl();

                    targetLocator = webdriver.switchTo();
                    targetLocator.defaultContent();
                    retried = true;
                } else {
                    IndependantLog.debug(debugmsg + " retrying a new targetLocator FAILED.");
                    done = true;
                    throw new SeleniumPlusException(
                            "Suspected UnreachableBrowserException seeking Browser DOM window Object.");
                }
            }
        }

        //reset the frame before searching the frame element if it exists.
        FrameElement frameElement = null;
        WebElement frame = null;
        String frameRS = null;
        //search the frame element if RS contains frame-info
        for (String rst : st) {
            //pre-check if this RS contains anything about frame-RS
            frameRS = retrieveFrameRS(rst);

            if (frameRS != null) {
                //Get frame WebElement according to frame's recognition string
                frame = _getSwitchFrame(webdriver, frameRS);
                if (frame != null) {
                    frameElement = new FrameElement(frameElement, frame);
                    haveSwichedFrame = _switchFrame(webdriver, frame);

                    //Can we use frame as SearchContext for child frame? FrameID=parentFrame;\;FrameID=childFrame
                    //NO, frame WebElement can NOT be used as SearchContext, will cause Exception
                    //We should always use webdriver as the SearchContext to find frame WebElement

                    //don't break, if there is frame in frame, as FRAMENAME=parent;\\;FRAMENAME=child
                    //break;
                }

            } else {
                //IndependantLog.warn(debugmsg+" store normal recognition string '"+rst+"' for further processing.");
                rsWithoutFrames.add(rst);
            }
        }

        if (haveSwichedFrame)
            lastFrame = frameElement;

    } catch (Exception e) {
        IndependantLog.error(debugmsg + " during switching frame, met exception " + StringUtils.debugmsg(e));
    }

    //2. Before search an element, switch to the correct frame
    //   For the child component, we don't need to specify the frame-RS, they use the same frame-RS as
    //   their parent component.
    try {
        if (!haveSwichedFrame && targetLocator != null) {
            FrameElement frameElement = lastFrame;
            Stack<FrameElement> frameStack = new Stack<FrameElement>();
            while (frameElement != null) {
                frameStack.push(frameElement);
                frameElement = frameElement.getParentFrame();
            }
            while (!frameStack.isEmpty() && frameStack.peek() != null) {
                targetLocator.frame(frameStack.pop().getWebElement());
                haveSwichedFrame = true;
            }
        }
    } catch (Exception e) {
        if (e instanceof StaleElementReferenceException && pageHasChanged()) {
            IndependantLog.warn(
                    debugmsg + " switching to the previous frame 'lastFrame' failed! The page has changed!");
            //LeiWang: S1215754
            //if we click a link within a FRAME, as the link is in a FRAME, so the field 'lastFrame' will be assigned after clicking the link.
            //then the link will lead us to a second page, when we try to find something on that page, firstly we try to switch to 'lastFrame' and
            //get a StaleElementReferenceException (as we are in the second page, there is no such frame of the first page)
            //but we still want our program to find the web-element on the second page, so we will just set 'lastFrame' to null and let program continue.
            //            [FirstPage]
            //            FirstPage="FRAMEID=iframeResult"
            //            Link="xpath=/html/body/a"
            //
            //            [SecondPage]
            //            SecondPage="xpath=/html"
            //            return null;
        } else {
            IndependantLog.warn(debugmsg + " switching to the previous frame 'lastFrame' failed! Met exception "
                    + StringUtils.debugmsg(e));
        }
        //LeiWang: S1215778
        //If we fail to switch to 'lastFrame', which perhaps means that it is not useful anymore
        //we should reset it to null, otherwise it will cause errors, such as calculate the element's screen location
        IndependantLog.debug(debugmsg + " 'lastFrame' is not useful anymore, reset it to null.");
        lastFrame = null;
    }
    return new SwitchFramesResults().setRsWithoutFrames(rsWithoutFrames).setSwitchedFrames(haveSwichedFrame);
}

From source file:org.sonarqube.qa.util.pageobjects.Navigation.java

License:Open Source License

public static Navigation create(Orchestrator orchestrator) {
    WebDriver driver = SelenideConfig.configure(orchestrator);
    driver.manage().deleteAllCookies();
    clearStorage(d -> d.getLocalStorage().clear());
    clearStorage(d -> d.getSessionStorage().clear());
    clearStorage(d -> Selenide.clearBrowserLocalStorage());
    return Selenide.open("/", Navigation.class);
}

From source file:org.specrunner.webdriver.AbstractPluginOptions.java

License:Open Source License

@Override
protected void doEnd(IContext context, IResultSet result, WebDriver client) throws PluginException {
    doEnd(context, result, client, client.manage());
}

From source file:org.specrunner.webdriver.result.WritableWebDriver.java

License:Open Source License

/**
 * Dump a screen shot of web driver which implements
 * <code>TakesScreenshot</code>.
 * // w  ww .  j  a v  a 2 s  .  com
 * @param source
 *            The web driver source.
 * @param driver
 *            The web driver casted to screenshot object.
 * @throws IOException
 *             On writing errors.
 */
protected void dumpScreenshot(WebDriver source, TakesScreenshot driver) throws IOException {
    Window window = source.manage().window();
    Dimension d = null;
    Point p = null;
    try {
        d = window.getSize();
        p = window.getPosition();
    } catch (Exception e) {
        if (UtilLog.LOG.isInfoEnabled()) {
            UtilLog.LOG.info("Could not get size and position.");
        }
    }
    try {
        // write screen
        File scrFile = driver.getScreenshotAs(OutputType.FILE);
        tmpDump = File.createTempFile("srunnerw", getExtension(scrFile));
        tmpDump.delete();
        FileUtils.copyFile(scrFile, tmpDump);
        if (UtilLog.LOG.isDebugEnabled()) {
            UtilLog.LOG.debug("Saved page screen to temporary file " + tmpDump);
        }

        // write source
        tmpSource = File.createTempFile("srunnerw", ".html");
        tmpSource.delete();
        FileUtils.writeStringToFile(tmpSource, source.getPageSource());
        if (UtilLog.LOG.isDebugEnabled()) {
            UtilLog.LOG.debug("Saved page source to temporary file " + tmpSource);
        }

    } catch (WebDriverException e) {
        if (UtilLog.LOG.isInfoEnabled()) {
            UtilLog.LOG.info("Could not dump screenshot.");
        }
    } finally {
        if (d != null && p != null) {
            if (UtilLog.LOG.isInfoEnabled()) {
                UtilLog.LOG.info("Restore size and location.");
            }
            window.setPosition(p);
            window.setSize(d);
        }
    }
}

From source file:org.suren.autotest.web.framework.invoker.KaptchaInvoker.java

License:Apache License

/**
 * ???/*ww w . ja va  2  s  .  co  m*/
 * @param engine 
 * @param param data,http://localhost:8080/G2/captcha!getLastCode.do
 * @return ??
 */
public static String execute(SeleniumEngine engine, String param) {
    WebDriver driver = engine.getDriver();
    Options manage = driver.manage();

    String[] paramArray = param.split(",", 2);

    if (paramArray.length != 2) {
        throw new RuntimeException("Param format is error, should be 'data,url'");
    }

    String key = paramArray[0];
    String url = paramArray[1];

    Set<Cookie> cookies = manage.getCookies();
    List<AtCookie> atCookieList = new ArrayList<AtCookie>();
    for (Cookie cookie : cookies) {
        String name = cookie.getName();
        String value = cookie.getValue();

        AtCookie atCookie = new AtCookie();
        atCookie.setName(name);
        atCookie.setValue(value);
        atCookie.setPath(cookie.getPath());
        atCookie.setDomain(cookie.getDomain());

        atCookieList.add(atCookie);
    }

    String code = HttpApiUtil.getJsonValue(url, atCookieList, key);

    return code;
}

From source file:org.terasoluna.gfw.tutorial.selenium.WebDriverCreator.java

License:Apache License

/**
 * Start WebDriver with download function enabled.
 * <p>/*  w  w w. ja  va2  s.co m*/
 * Supports FireFox only<br>
 * </p>
 * @param downloadTempDirectory : Temporary storage directory for download
 * @return WebDriver instance with download function enabled
 */
public WebDriver createDownloadableWebDriver(String downloadTempDirectory) {
    for (String activeProfile : getApplicationContext().getEnvironment().getActiveProfiles()) {
        if ("chrome".equals(activeProfile) || "ie".equals(activeProfile) || "phantomJs".equals(activeProfile)) {
            throw new UnsupportedOperationException(
                    "It is not possible to run tests using the download function on browsers other than FireFox.");
        }
    }
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("browser.download.dir", downloadTempDirectory);
    profile.setPreference("browser.download.folderList", 2);
    profile.setPreference("browser.download.lastDir", downloadTempDirectory);
    profile.setPreference("browser.helperApps.alwaysAsk.force", false);
    profile.setPreference("browser.download.manager.showWhenStarting", false);
    profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
    profile.setPreference("pdfjs.disabled", true);
    profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
            "application/pdf, text/csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, text/plain");
    profile.setPreference("brouser.startup.homepage_override.mstone", "ignore");
    profile.setPreference("network.proxy.type", 0);

    WebDriver webDriver = new FirefoxDriver(profile);
    webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    return webDriver;
}

From source file:org.terasoluna.tourreservation.tourreserve.common.FunctionTestSupport.java

License:Apache License

/**
 * Starts a WebDriver<br>/*from  w  ww  . java2s.  c  o m*/
 * </p>
 * @return WebDriver web driver
 */
protected WebDriver createWebDriver() {
    WebDriver driver = null;
    for (String activeProfile : getApplicationContext().getEnvironment().getActiveProfiles()) {
        if ("chrome".equals(activeProfile)) {
            driver = new ChromeDriver();
            break;
        } else if ("firefox".equals(activeProfile)) {
            break;
        } else if ("ie".equals(activeProfile)) {
            driver = new InternetExplorerDriver();
            break;
        }
    }

    if (driver == null) {
        driver = new FirefoxDriver();
    }

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.get(applicationContextUrl + "?locale=" + locale.getLanguage());

    return driver;
}