Example usage for org.openqa.selenium WebDriver getCurrentUrl

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

Introduction

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

Prototype

String getCurrentUrl();

Source Link

Document

Get a string representing the current URL that the browser is looking at.

Usage

From source file:org.orcid.integration.blackbox.api.OauthAuthorizationPageTest.java

License:Open Source License

@Test
public void stateParamIsPersistentAndReurnedWhenAlreadyLoggedInTest()
        throws JSONException, InterruptedException, URISyntaxException {
    WebDriver webDriver = new FirefoxDriver();
    webDriver.get(webBaseUrl + "/userStatus.json?logUserOut=true");
    webDriver.get(webBaseUrl + "/my-orcid");
    // Sign in//from   w  w w  .j a  va2  s .com
    SigninTest.signIn(webDriver, user1UserName, user1Password);
    // Go to the authroization page
    webDriver.get(String.format(
            "%s/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s&state=%s", webBaseUrl,
            client1ClientId, SCOPES, client1RedirectUri, STATE_PARAM));
    By userIdElementLocator = By.id("authorize");
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS))
            .until(ExpectedConditions.presenceOfElementLocated(userIdElementLocator));
    WebElement authorizeButton = webDriver.findElement(By.id("authorize"));
    authorizeButton.click();
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            return d.getTitle().equals("ORCID Playground");
        }
    });

    String currentUrl = webDriver.getCurrentUrl();
    Matcher matcher = STATE_PARAM_PATTERN.matcher(currentUrl);
    assertTrue(matcher.find());
    String stateParam = matcher.group(1);
    assertFalse(PojoUtil.isEmpty(stateParam));
    assertEquals(STATE_PARAM, stateParam);
    webDriver.close();
}

From source file:org.orcid.integration.blackbox.api.OauthAuthorizationPageTest.java

License:Open Source License

@Test
public void invalidRedirectUriAllowsLoginThenShowErrorTest() throws InterruptedException {
    String invalidRedirectUri = "http://www.orcid.org/worng/redirect/uri";
    webDriver.get(String.format(//from w w  w .j a v  a 2 s  .  c o  m
            "%s/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s&state=%s", webBaseUrl,
            client1ClientId, SCOPES, invalidRedirectUri, STATE_PARAM));
    By switchFromLinkLocator = By.id("in-register-switch-form");
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS))
            .until(ExpectedConditions.presenceOfElementLocated(switchFromLinkLocator));
    WebElement switchFromLink = webDriver.findElement(switchFromLinkLocator);
    switchFromLink.click();

    // Fill the form
    By userIdElementLocator = By.id("userId");
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS))
            .until(ExpectedConditions.presenceOfElementLocated(userIdElementLocator));
    WebElement userIdElement = webDriver.findElement(userIdElementLocator);
    userIdElement.sendKeys(user1UserName);
    WebElement passwordElement = webDriver.findElement(By.id("password"));
    passwordElement.sendKeys(user1Password);
    WebElement submitButton = webDriver.findElement(By.id("authorize-button"));
    submitButton.click();

    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            return d.getCurrentUrl().contains("/oauth/error/redirect-uri-mismatch");
        }
    });

    String currentUrl = webDriver.getCurrentUrl();
    assertTrue("URL is:" + currentUrl, currentUrl.contains("/oauth/error/redirect-uri-mismatch"));
    assertTrue("URL is:" + currentUrl, currentUrl.contains("client_id=" + client1ClientId));
    assertTrue("URL is:" + currentUrl, currentUrl.contains("response_type=code"));
    assertTrue("URL is:" + currentUrl, currentUrl.contains("redirect_uri=" + invalidRedirectUri));
    assertTrue("URL is:" + currentUrl, currentUrl.contains("scope="));
}

From source file:org.orcid.integration.blackbox.api.OauthAuthorizationPageTest.java

License:Open Source License

/**
 * Test that asking for different scopes generates different tokens
 * /*www .j  ava 2 s. c  o  m*/
 * IMPORTANT NOTE: For this test to run, the user should not have tokens for
 * any of the following scopes: - FUNDING_CREATE - AFFILIATIONS_CREATE -
 * ORCID_WORKS_UPDATE
 * */
@Test
public void testDifferentScopesGeneratesDifferentAccessTokens() throws InterruptedException, JSONException {
    revokeApplicationsAccess(client1ClientId);
    // First get the authorization code
    webDriver.get(String.format("%s/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s",
            webBaseUrl, client1ClientId, ScopePathType.FUNDING_CREATE.getContent(), client1RedirectUri));
    By switchFromLinkLocator = By.id("in-register-switch-form");
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS))
            .until(ExpectedConditions.presenceOfElementLocated(switchFromLinkLocator));
    WebElement switchFromLink = webDriver.findElement(switchFromLinkLocator);
    switchFromLink.click();

    // Fill the form
    By userIdElementLocator = By.id("userId");
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS))
            .until(ExpectedConditions.presenceOfElementLocated(userIdElementLocator));
    WebElement userIdElement = webDriver.findElement(userIdElementLocator);
    userIdElement.sendKeys(user1UserName);
    WebElement passwordElement = webDriver.findElement(By.id("password"));
    passwordElement.sendKeys(user1Password);
    WebElement submitButton = webDriver.findElement(By.id("authorize-button"));
    submitButton.click();

    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            return d.getTitle().equals("ORCID Playground");
        }
    });

    String currentUrl = webDriver.getCurrentUrl();
    Matcher matcher = AUTHORIZATION_CODE_PATTERN.matcher(currentUrl);
    assertTrue(matcher.find());
    String authorizationCode = matcher.group(1);
    assertFalse(PojoUtil.isEmpty(authorizationCode));

    ClientResponse tokenResponse = getClientResponse(client1ClientId, client1ClientSecret,
            ScopePathType.FUNDING_CREATE.getContent(), client1RedirectUri, authorizationCode);
    assertEquals(200, tokenResponse.getStatus());
    String body = tokenResponse.getEntity(String.class);
    JSONObject jsonObject = new JSONObject(body);
    String accessToken = (String) jsonObject.get("access_token");
    assertNotNull(accessToken);
    assertFalse(PojoUtil.isEmpty(accessToken));

    // Then, ask again for permissions over other scopes. Note that the user
    // is already logged in
    String url = String.format("%s/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s",
            webBaseUrl, client1ClientId, ScopePathType.AFFILIATIONS_CREATE.getContent(), client1RedirectUri);
    webDriver.get(url);

    By authorizeElementLocator = By.id("authorize");
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS))
            .until(ExpectedConditions.presenceOfElementLocated(authorizeElementLocator));
    WebElement authorizeButton = webDriver.findElement(authorizeElementLocator);
    authorizeButton.click();

    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            return d.getCurrentUrl().contains("code=");
        }
    });

    currentUrl = webDriver.getCurrentUrl();
    matcher = AUTHORIZATION_CODE_PATTERN.matcher(currentUrl);
    assertTrue(matcher.find());
    authorizationCode = matcher.group(1);
    assertFalse(PojoUtil.isEmpty(authorizationCode));

    tokenResponse = getClientResponse(client1ClientId, client1ClientSecret,
            ScopePathType.AFFILIATIONS_CREATE.getContent(), client1RedirectUri, authorizationCode);
    assertEquals(200, tokenResponse.getStatus());
    body = tokenResponse.getEntity(String.class);
    jsonObject = new JSONObject(body);
    String otherAccessToken = (String) jsonObject.get("access_token");
    assertNotNull(otherAccessToken);
    assertFalse(PojoUtil.isEmpty(otherAccessToken));

    assertFalse(otherAccessToken.equals(accessToken));

    // Repeat the process again with other scope
    webDriver.get(String.format("%s/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s",
            webBaseUrl, client1ClientId, ScopePathType.ORCID_WORKS_UPDATE.getContent(), client1RedirectUri));

    authorizeElementLocator = By.id("authorize");
    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS))
            .until(ExpectedConditions.presenceOfElementLocated(authorizeElementLocator));
    authorizeButton = webDriver.findElement(authorizeElementLocator);
    authorizeButton.click();

    (new WebDriverWait(webDriver, DEFAULT_TIMEOUT_SECONDS)).until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver d) {
            return d.getCurrentUrl().contains("code=");
        }
    });

    currentUrl = webDriver.getCurrentUrl();
    matcher = AUTHORIZATION_CODE_PATTERN.matcher(currentUrl);
    assertTrue(matcher.find());
    authorizationCode = matcher.group(1);
    assertFalse(PojoUtil.isEmpty(authorizationCode));

    tokenResponse = getClientResponse(client1ClientId, client1ClientSecret,
            ScopePathType.ORCID_WORKS_UPDATE.getContent(), client1RedirectUri, authorizationCode);
    assertEquals(200, tokenResponse.getStatus());
    body = tokenResponse.getEntity(String.class);
    jsonObject = new JSONObject(body);
    String otherAccessToken2 = (String) jsonObject.get("access_token");
    assertNotNull(otherAccessToken2);
    assertFalse(PojoUtil.isEmpty(otherAccessToken2));

    assertFalse(otherAccessToken2.equals(accessToken));
    assertFalse(otherAccessToken2.equals(otherAccessToken));
}

From source file:org.qe4j.web.OpenWebDriverTest.java

License:Open Source License

@Test
public void getCurrentUrl() throws IOException {
    Properties properties = getProperties();
    WebDriver driver = new OpenWebDriver(properties);
    driver.get(URL);/*from ww  w .ja  va2 s. co  m*/
    Assert.assertEquals(driver.getCurrentUrl(), URL, "current url");
}

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  ava 2s .c  om
 */
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.seasar.robot.client.http.WebDriverClient.java

License:Apache License

@Override
public ResponseData execute(final RequestData request) {
    WebDriver webDriver = null;
    try {//  ww  w. j av a  2  s.c om
        webDriver = webDriverPool.borrowObject();

        Map<String, String> paramMap = null;
        String url = request.getUrl();
        String metaData = request.getMetaData();
        if (StringUtil.isNotBlank(metaData)) {
            paramMap = parseParamMap(metaData);
        }

        if (!url.equals(webDriver.getCurrentUrl())) {
            webDriver.get(url);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Base URL: " + url + "\nContent: " + webDriver.getPageSource());
        }

        if (paramMap != null) {
            final String processorName = paramMap.get(UrlAction.URL_ACTION);
            final UrlAction urlAction = urlActionMap.get(processorName);
            if (urlAction == null) {
                throw new RobotSystemException("Unknown processor: " + processorName);
            }
            urlAction.navigate(webDriver, paramMap);
        }

        final String source = webDriver.getPageSource();

        final ResponseData responseData = new ResponseData();

        responseData.setUrl(webDriver.getCurrentUrl());
        responseData.setMethod(request.getMethod().name());
        responseData.setContentLength(source.length());

        final String charSet = getCharSet(webDriver);
        responseData.setCharSet(charSet);
        responseData.setHttpStatusCode(getStatusCode(webDriver));
        responseData.setLastModified(getLastModified(webDriver));
        responseData.setMimeType(getContentType(webDriver));

        responseData.setResponseBody(new ByteArrayInputStream(source.getBytes(charSet)));

        for (final UrlAction urlAction : urlActionMap.values()) {
            urlAction.collect(url, webDriver, responseData);
        }

        return responseData;
    } catch (final Exception e) {
        throw new RobotSystemException("Failed to access " + request.getUrl(), e);
    } finally {
        if (webDriver != null) {
            try {
                webDriverPool.returnObject(webDriver);
            } catch (final Exception e) {
                logger.warn("Failed to return a returned object.", e);
            }
        }
    }
}

From source file:org.springframework.security.config.web.server.FormLoginTests.java

License:Apache License

@Test
public void authenticationSuccess() {
    SecurityWebFilterChain securityWebFilter = this.http.authorizeExchange().anyExchange().authenticated().and()
            .formLogin().authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/custom"))
            .and().build();/* w  w  w .  j a  v  a2  s . c o  m*/

    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();

    WebDriver driver = WebTestClientHtmlUnitDriverBuilder.webTestClientSetup(webTestClient).build();

    DefaultLoginPage loginPage = DefaultLoginPage.to(driver).assertAt();

    HomePage homePage = loginPage.loginForm().username("user").password("password").submit(HomePage.class);

    assertThat(driver.getCurrentUrl()).endsWith("/custom");
}

From source file:org.springframework.security.config.web.server.OAuth2LoginTests.java

License:Apache License

@Test
public void defaultLoginPageWithSingleClientRegistrationThenRedirect() {
    this.spring.register(OAuth2LoginWithSingleClientRegistrations.class).autowire();

    WebTestClient webTestClient = WebTestClientBuilder
            .bindToWebFilters(new GitHubWebFilter(), this.springSecurity).build();

    WebDriver driver = WebTestClientHtmlUnitDriverBuilder.webTestClientSetup(webTestClient).build();

    driver.get("http://localhost/");

    assertThat(driver.getCurrentUrl()).startsWith("https://github.com/login/oauth/authorize");
}

From source file:org.springframework.springfaces.integrationtest.selenium.WebDriverUtils.java

License:Apache License

/**
 * Decorate the specified {@link WebElement} with a version that will {@link #waitOnUrlChange(WebDriver, String)
 * wait for a URL change} after each call. Particularly useful when dealing with AJAX driven redirect.
 * <p>/* w ww  .j  av a2 s  .c  o m*/
 * For example: <code>
 * waitOnUrlChange(searchButton).click();
 * </code>
 * @param webDriver the web driver
 * @param source the source element
 * @return a decorated {@link WebElement}
 * @see #waitOnUrlChange(WebDriver,String)
 */
public static WebElement waitOnUrlChange(final WebDriver webDriver, final WebElement source) {
    Assert.notNull(webDriver, "WebDriver must not be null");
    Assert.notNull(source, "Source must not be null");
    final String url = webDriver.getCurrentUrl();
    Object proxy = Proxy.newProxyInstance(source.getClass().getClassLoader(),
            new Class<?>[] { WebElement.class }, new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return method.invoke(source, args);
                    } finally {
                        waitOnUrlChange(webDriver, url);
                    }
                }
            });
    return (WebElement) proxy;
}

From source file:org.springframework.springfaces.integrationtest.selenium.WebDriverUtils.java

License:Apache License

/**
 * Wait until the current URL changes from the specified URL.
 * @param webDriver the web driver// w  ww.  java2s.  c  om
 * @param fromUrl the current URL that must change before this method continues
 * @see #waitOnUrlChange(WebDriver,WebElement)
 */
public static void waitOnUrlChange(final WebDriver webDriver, final String fromUrl) {
    Assert.notNull(webDriver, "WebDriver must not be null");
    Assert.notNull(fromUrl, "FromUrl must not be null");
    new Wait("Expected change of URL from " + fromUrl) {
        @Override
        public boolean until() {
            return !webDriver.getCurrentUrl().equals(fromUrl);
        }
    };
}