org.openqa.selenium.Cookie Java Examples

The following examples show how to use org.openqa.selenium.Cookie. 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 File: CommonMethods.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
@Action(object = ObjectType.BROWSER, desc = "delete the cookie having name [<Data>].", input = InputType.YES)
public void deleteCookie() {
    try {
        String strCookieName = Data;
        Cookie oCookie = Driver.manage().getCookieNamed(strCookieName);
        if (oCookie != null) {
            Driver.manage().deleteCookie(oCookie);
            Report.updateTestLog(Action, "Cookie Name- '"
                    + strCookieName + "' is deleted", Status.DONE);
        } else {
            Report.updateTestLog(Action, "Cookie doesn't exist",
                    Status.FAIL);
        }
    } catch (Exception e) {
        Report.updateTestLog(Action, e.getMessage(), Status.FAIL);
        Logger.getLogger(CommonMethods.class.getName()).log(Level.SEVERE, null, e);
    }
}
 
Example #2
Source File: RemoteWebDriverUnitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canHandleGetCookieNamedCommand() throws IOException {
  CommandExecutor executor = prepareExecutorMock(
      echoCapabilities,
      valueResponder(Arrays.asList(
          ImmutableMap.of("name", "cookie1", "value", "value1"),
          ImmutableMap.of("name", "cookie2", "value", "value2"))));

  RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities());
  Cookie found = driver.manage().getCookieNamed("cookie2");

  assertThat(found).isEqualTo(new Cookie("cookie2", "value2"));
  verifyCommands(
      executor, driver.getSessionId(),
      new CommandPayload(DriverCommand.GET_ALL_COOKIES, emptyMap()));
}
 
Example #3
Source File: RemoteWebDriverUnitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canHandleGetCookiesCommand() throws IOException {
  CommandExecutor executor = prepareExecutorMock(
      echoCapabilities,
      valueResponder(Arrays.asList(
          ImmutableMap.of("name", "cookie1", "value", "value1", "sameSite", "Lax"),
          ImmutableMap.of("name", "cookie2", "value", "value2"))));

  RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities());
  Set<Cookie> cookies = driver.manage().getCookies();

  assertThat(cookies)
      .hasSize(2)
      .contains(
          new Cookie.Builder("cookie1", "value1").sameSite("Lax").build(),
          new Cookie("cookie2", "value2"));
  verifyCommands(
      executor, driver.getSessionId(),
      new CommandPayload(DriverCommand.GET_ALL_COOKIES, ImmutableMap.of()));
}
 
Example #4
Source File: JsonOutputTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToConvertACookie() {
  Date expiry = new Date();
  Cookie cookie = new Cookie("name", "value", "domain", "/path", expiry, true, true);

  String jsonStr = convert(cookie);

  JsonObject converted = new JsonParser().parse(jsonStr).getAsJsonObject();

  assertThat(converted.get("name").getAsString()).isEqualTo("name");
  assertThat(converted.get("value").getAsString()).isEqualTo("value");
  assertThat(converted.get("domain").getAsString()).isEqualTo("domain");
  assertThat(converted.get("path").getAsString()).isEqualTo("/path");
  assertThat(converted.get("secure").getAsBoolean()).isTrue();
  assertThat(converted.get("httpOnly").getAsBoolean()).isTrue();
  assertThat(converted.get("expiry").getAsLong())
      .isEqualTo(MILLISECONDS.toSeconds(expiry.getTime()));
}
 
Example #5
Source File: CookieManagerTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetCookiesAsHttpCookieStore()
{
    configureMockedWebDriver();
    Cookie seleniumCookie = createSeleniumCookie();
    mockGetCookies(seleniumCookie);
    CookieStore cookieStore = cookieManager.getCookiesAsHttpCookieStore();
    List<org.apache.http.cookie.Cookie> resultCookies = cookieStore.getCookies();
    assertEquals(1, resultCookies.size());
    org.apache.http.cookie.Cookie httpCookie = resultCookies.get(0);
    assertThat(httpCookie, instanceOf(BasicClientCookie.class));
    BasicClientCookie clientCookie = (BasicClientCookie) httpCookie;
    assertAll(
        () -> assertEquals(seleniumCookie.getDomain(), clientCookie.getDomain()),
        () -> assertEquals(seleniumCookie.getExpiry(), clientCookie.getExpiryDate()),
        () -> assertEquals(seleniumCookie.getName(), clientCookie.getName()),
        () -> assertEquals(seleniumCookie.getPath(), clientCookie.getPath()),
        () -> assertEquals(seleniumCookie.getValue(), clientCookie.getValue()),
        () -> assertEquals(seleniumCookie.isSecure(), clientCookie.isSecure()),
        () -> assertEquals(seleniumCookie.getDomain(), clientCookie.getAttribute(ClientCookie.DOMAIN_ATTR)),
        () -> assertEquals(seleniumCookie.getPath(), clientCookie.getAttribute(ClientCookie.PATH_ATTR))
    );
}
 
Example #6
Source File: CookieConverter.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
/**
 * Converts Selenium cookie to Apache http client.
 * @param browserCookie selenium cookie.
 * @return http client format.
 */
protected ClientCookie convertCookie(Cookie browserCookie) {
    BasicClientCookie cookie = new BasicClientCookie(browserCookie.getName(), browserCookie.getValue());
    String domain = browserCookie.getDomain();
    if (domain != null && domain.startsWith(".")) {
        // http client does not like domains starting with '.', it always removes it when it receives them
        domain = domain.substring(1);
    }
    cookie.setDomain(domain);
    cookie.setPath(browserCookie.getPath());
    cookie.setExpiryDate(browserCookie.getExpiry());
    cookie.setSecure(browserCookie.isSecure());
    if (browserCookie.isHttpOnly()) {
        cookie.setAttribute("httponly", "");
    }
    return cookie;
}
 
Example #7
Source File: AddCookie.java    From opentest with MIT License 5 votes vote down vote up
@Override
public void run() {
    super.run();

    String name = this.readStringArgument("name");
    String value = this.readStringArgument("value");
    String domain = this.readStringArgument("domain", null);
    String path = this.readStringArgument("path", null);
    Boolean isSecure = this.readBooleanArgument("isSecure", false);
    Boolean isHttpOnly = this.readBooleanArgument("isHttpOnly", false);

    Cookie cookie = new Cookie(name, value, domain, path, null, isSecure, isHttpOnly);
    driver.manage().addCookie(cookie);
}
 
Example #8
Source File: FirefoxCookiesWorkFineButChromeAddsAdditional.java    From webDriverExperiments with MIT License 5 votes vote down vote up
private void doTheActualCookieDeleteThenAddOnTheBrowser() {
    driver.get("http://compendiumdev.co.uk/selenium/" + "search.php");

    assertEquals("2 Cookies created on initial visit", 2, driver.manage().getCookies().size());

    // find cookie to cut n paste
    Cookie aCookie = driver.manage().
            getCookieNamed("seleniumSimplifiedSearchNumVisits");

    System.out.println("Going to work with this cookie:");
    System.out.println(aCookie.toString().replaceAll(";",";\n"));

    int cookieCount = driver.manage().getCookies().size();
    // delete cookie
    driver.manage().deleteCookie(aCookie);
    assertEquals("One less cookie expected", cookieCount-1, driver.manage().getCookies().size());

    // recreate the cookie works fine on Firefox, but fails on Chrome
    //driver.manage().addCookie(aCookie);


    // if I build the cookie from scratch then it fails on chrome when I add the domain
    driver.manage().addCookie(
            new Cookie.Builder(aCookie.getName(),
                    aCookie.getValue()).
                    path(aCookie.getPath()).
                    // enable line below to have test fail on chrome
                    // domain(aCookie.getDomain()).
                    expiresOn(aCookie.getExpiry()).
                    isHttpOnly(aCookie.isHttpOnly()).
                    isSecure(aCookie.isSecure()).
                    build());


    System.out.println(driver.manage().getCookies().toString().replaceAll(";",";\n"));
    assertEquals("Same number of cookies expected", cookieCount, driver.manage().getCookies().size());
}
 
Example #9
Source File: AddCookie.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Void call() {
  Cookie cookie = createCookie();

  getDriver().manage().addCookie(cookie);

  return null;
}
 
Example #10
Source File: Verifications.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
/**
 * ******************************************
 * Function to verify cookies by name
 * ******************************************
 */
@Action(object = ObjectType.BROWSER, desc = "Verify if cookie by name: [<Data>] is present ", input = InputType.YES)

public void verifyCookieByName() {
    try {

        String strCookieName = Data.split(":", 2)[0];
        String strCookieValue = Data.split(":", 2)[1];
        Cookie cookie = Driver.manage().getCookieNamed(strCookieName);
        if (cookie != null) {
            if ((strCookieValue.equals(cookie.getValue()))) {
                System.out.println(Action + " Passed");
                Report.updateTestLog(Action,
                        "Cookie value  is matched with the expected result",
                        Status.PASS);
            } else {
                Report.updateTestLog(Action, "Cookie value doesn't match with the expected result",
                        Status.FAIL);
            }
        } else {
            System.out.println(Action + " Failed");
            Report.updateTestLog(Action,
                    "Cookie with name [" + Data + "] is not available",
                    Status.FAIL);
        }
    } catch (Exception e) {
        Report.updateTestLog(Action, e.getMessage(),
                Status.FAIL);
        Logger.getLogger(Verifications.class.getName()).log(Level.SEVERE, null, e);
    }
}
 
Example #11
Source File: RestartCookieTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestartCookieBackwardsCompatible_Keycloak25() throws IOException {
    String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
        try {
            String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
            RealmModel realm = session.realms().getRealmByName("test");

            KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);

            String encodedToken = new JWSBuilder()
                    .kid(activeKey.getKid())
                    .content(cookieVal.getBytes("UTF-8"))
                    .hmac256(activeKey.getSecretKey());

            return encodedToken;


        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });

    oauth.openLoginForm();

    driver.manage().deleteAllCookies();
    driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));

    loginPage.login("foo", "bar");
    loginPage.assertCurrent();
    Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());

    events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails()
            .detail(Details.RESTART_AFTER_TIMEOUT, "true")
            .client((String) null)
            .assertEvent();
}
 
Example #12
Source File: ReadCookie.java    From opentest with MIT License 5 votes vote down vote up
@Override
public void run() {
    super.run();

    String name = this.readStringArgument("name");

    Cookie cookie = driver.manage().getCookieNamed(name);
    this.writeOutput("value", cookie.getValue());
}
 
Example #13
Source File: HtmlExporterUtils.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
     * 初始化配置 PhantomJS Driver.
     *
     * @param url         目标 URL
     * @param addedCookie 添加 cookie
     * @return 初始化过的 PhantomJS Driver
     */
    public static PhantomJSDriver prepare(String url, Cookie addedCookie, Integer width, Integer height) {
        // chrome driver maybe not necessary
        // download from https://sites.google.com/a/chromium.org/chromedriver/downloads
//        System.setProperty("webdriver.chrome.driver",
//                DirUtils.RESOURCES_PATH.concat(
//                        PropUtils.getInstance().getProperty("html.exporter.webdriver.chrome.driver")));

        DesiredCapabilities phantomCaps = DesiredCapabilities.chrome();
        phantomCaps.setJavascriptEnabled(true);
        PropUtils p = PropUtils.getInstance();
        phantomCaps.setCapability("phantomjs.page.settings.userAgent",
                p.getProperty("html.exporter.user.agent"));

        PhantomJSDriver driver = new PhantomJSDriver(phantomCaps);
        driver.manage().timeouts().implicitlyWait(Integer.parseInt(
                p.getProperty("html.exporter.driver.timeouts.implicitly.seconds")), TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(Integer.parseInt(
                p.getProperty("html.exporter.driver.timeouts.page.load.seconds")), TimeUnit.SECONDS);
        driver.manage().timeouts().setScriptTimeout(Integer.parseInt(
                p.getProperty("html.exporter.driver.timeouts.script.seconds")), TimeUnit.SECONDS);

        if (width == null || height == null) driver.manage().window().maximize();
        else driver.manage().window().setSize(new Dimension(width, height));

        if (addedCookie != null) driver.manage().addCookie(addedCookie);

        driver.get(url);
//        try {
//            // timeout is not work, so fix it by sleeping thread
//            Thread.sleep(Integer.valueOf(PropUtils.getInstance()
//                    .getProperty("html.exporter.driver.timeouts.implicitly.seconds")) * 1000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        return driver;
    }
 
Example #14
Source File: RemoteWebDriver.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public Set<Cookie> getCookies() {
  Object returned = execute(DriverCommand.GET_ALL_COOKIES).getValue();

  Set<Cookie> toReturn = new HashSet<>();

  if (!(returned instanceof Collection)) {
    return toReturn;
  }

  ((Collection<?>) returned).stream()
      .map(o -> (Map<String, Object>) o)
      .map(rawCookie -> {
        // JSON object keys are defined in
        // https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion.
        Cookie.Builder builder =
            new Cookie.Builder((String) rawCookie.get("name"), (String) rawCookie.get("value"))
                .path((String) rawCookie.get("path"))
                .domain((String) rawCookie.get("domain"))
                .isSecure(rawCookie.containsKey("secure") && (Boolean) rawCookie.get("secure"))
                .isHttpOnly(
                    rawCookie.containsKey("httpOnly") && (Boolean) rawCookie.get("httpOnly"))
                .sameSite((String) rawCookie.get("sameSite"));

        Number expiryNum = (Number) rawCookie.get("expiry");
        builder.expiresOn(expiryNum == null ? null : new Date(SECONDS.toMillis(expiryNum.longValue())));
        return builder.build();
      })
      .forEach(toReturn::add);

  return toReturn;
}
 
Example #15
Source File: AbstractHtmlEngine.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param name the name of the cookie. May not be null or an empty string.
 * @param value the cookie value. May not be null.
 * @param domain the domain the cookie is visible to.
 * @param path the path the cookie is visible to. If left blank or set to null, will be set to
 *        "/".
 * @param expiry the cookie's expiration date; may be null.
 * @param isSecure whether this cookie requires a secure connection.
 */
@PublicAtsApi
public void setCookie(
                       String name,
                       String value,
                       String domain,
                       String path,
                       Date expiry,
                       boolean isSecure ) {

    Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure);
    webDriver.manage().addCookie(cookie);
}
 
Example #16
Source File: AbstractHtmlEngine.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param cookieName the name of the cookie. May not be null or an empty string.
 * @param cookieValue the cookie value. May not be null.
 */
@PublicAtsApi
public void setCookie(
                       String cookieName,
                       String cookieValue ) {

    Cookie cookie = new Cookie(cookieName, cookieValue);
    webDriver.manage().addCookie(cookie);
}
 
Example #17
Source File: AuthUT.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testPageBehindCookieAuthentication() {
    try {
        Auth.clear();
        System.setProperty(Auth.SESSION_COOKIE, "auth=ok,path=/");
        final Cookie c = Auth.getAuthenticationCookie("http://127.0.0.1");
        bs.goToUrl("UNPROTECTED");
        Auth.loadAuthenticationCookie(c);
        bs.goToUrl("COOKIEPROTECTED");
        Assert.assertTrue("The requested page content must respond 'OK'.",
                Context.getDriver().getPageSource().contains("<head></head><body><pre style=\"word-wrap: break-word; white-space: pre-wrap;\">OK</pre></body>"));
    } catch (final Exception e) {
        Assert.fail("Exception thrown: " + e.getMessage());
    }
}
 
Example #18
Source File: RestartCookieTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestartCookieBackwardsCompatible_Keycloak19() throws IOException {
    String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
        try {
            String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
            RealmModel realm = session.realms().getRealmByName("test");

            KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);

            // There was no KID in the token in Keycloak 1.9.8
            String encodedToken = new JWSBuilder()
                    //.kid(activeKey.getKid())
                    .content(cookieVal.getBytes("UTF-8"))
                    .hmac256(activeKey.getSecretKey());

            return encodedToken;


        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });

    oauth.openLoginForm();

    driver.manage().deleteAllCookies();
    driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));

    loginPage.login("foo", "bar");
    loginPage.assertCurrent();
    Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());

    events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails()
            .detail(Details.RESTART_AFTER_TIMEOUT, "true")
            .client((String) null)
            .assertEvent();
}
 
Example #19
Source File: WebDriverService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getFromCookie(Session session, String cookieName, String cookieParameter) {
    Cookie cookie = session.getDriver().manage().getCookieNamed(cookieName);
    if (cookie != null) {
        if (cookieParameter.equals("name")) {
            return cookie.getName();
        }
        if (cookieParameter.equals("expiry")) {
            return cookie.getExpiry().toString();
        }
        if (cookieParameter.equals("value")) {
            return cookie.getValue();
        }
        if (cookieParameter.equals("domain")) {
            return cookie.getDomain();
        }
        if (cookieParameter.equals("path")) {
            return cookie.getPath();
        }
        if (cookieParameter.equals("isHttpOnly")) {
            return String.valueOf(cookie.isHttpOnly());
        }
        if (cookieParameter.equals("isSecure")) {
            return String.valueOf(cookie.isSecure());
        }
    } else {
        return "cookieNotFound";
    }
    return null;
}
 
Example #20
Source File: ManageBrowserCookieStepsTest.java    From akita with Apache License 2.0 5 votes vote down vote up
@Test
void saveCookieToVarTest() {
    Cookie cookie = new Cookie("cookieName", "123");
    when(webDriver.manage().getCookieNamed("cookieName")).thenReturn(cookie);
    dmbs.saveCookieToVar("cookieName", "varName");
    assertEquals(cookie, akitaScenario.getVar("varName"));
}
 
Example #21
Source File: HasCookieMatcherTest.java    From matchers-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFindExistingCookie() {
    WebDriver driver = mock(WebDriver.class);
    Options options = mock(Options.class);
    Cookie cookie = new Cookie(cookieName, "oki-doki");


    when(driver.manage()).thenReturn(options);
    when(options.getCookieNamed(eq(cookieName))).thenReturn(cookie);

    assertThat("Cookie not found!", driver, hasCookie(cookieName));
}
 
Example #22
Source File: CommonGTest.java    From bdt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCookieExistsSizeZero() throws Exception{
    String cookieName = "cookieFalse";
    org.openqa.selenium.Cookie cookie = new org.openqa.selenium.Cookie("cookieTest", "cookiePath", "cookieValue");
    Set<Cookie> setCookies = new HashSet<Cookie>();
    CommonG commong = new CommonG();
    commong.setSeleniumCookies(setCookies);
    assertThat(false).isEqualTo(commong.cookieExists(cookieName));
}
 
Example #23
Source File: HtmlExporter2File.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 将带有 chart、map 等动态图表的 html 转换为 图片(可以额外配置 cookie 的权限控制).
 *
 * @param url         目标 URL
 * @param addedCookie 添加 cookie
 * @return 图片文件
 */
@Override
public File convert2Image(String url, Cookie addedCookie, Integer width, Integer height) {
    PhantomJSDriver driver = null;
    try {
        driver = HtmlExporterUtils.prepare(url, addedCookie, width, height);
        return driver.getScreenshotAs(OutputType.FILE);
    } finally {
        HtmlExporterUtils.release(driver);
    }
}
 
Example #24
Source File: AemAuthCookieFactoryImpl.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * This method provides browser cookie for authenticating user to AEM instance
 *
 * @param url      URL to AEM instance, like http://localhost:4502
 * @param login    Username to use
 * @param password Password to use
 * @return Cookie for selenium WebDriver.
 */
@Override
public Cookie getCookie(String url, String login, String password) {
  if (!cookieJar.containsKey(url)) {
    HttpPost loginPost = new HttpPost(url
        + "/libs/granite/core/content/login.html/j_security_check");

    List<NameValuePair> nameValuePairs = new ArrayList<>();
    nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8"));
    nameValuePairs.add(new BasicNameValuePair("j_username", login));
    nameValuePairs.add(new BasicNameValuePair("j_password", password));
    nameValuePairs.add(new BasicNameValuePair("j_validate", "true"));

    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    try {
      loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context);
      loginResponse.close();
    } catch (IOException e) {
      LOG.error("Can't get AEM authentication cookie", e);
    } finally {
      loginPost.reset();
    }
    Cookie cookie = findAuthenticationCookie(cookieStore.getCookies());
    cookieJar.put(url, cookie);
  }
  return cookieJar.get(url);
}
 
Example #25
Source File: AbstractAuthTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void listCookies() {
    log.info("LIST OF COOKIES: ");
    for (Cookie c : driver.manage().getCookies()) {
        log.info(MessageFormat.format(" {1} {2} {0}",
                c.getName(), c.getDomain(), c.getPath(), c.getValue()));
    }
}
 
Example #26
Source File: RemoteWebDriverUnitTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void canHandleAddCookieCommand() throws IOException {
  CommandExecutor executor = prepareExecutorMock(echoCapabilities, nullResponder);

  Cookie cookie = new Cookie("x", "y");
  RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities());
  driver.manage().addCookie(cookie);

  verifyCommands(
      executor, driver.getSessionId(),
      new CommandPayload(DriverCommand.ADD_COOKIE, ImmutableMap.of("cookie", cookie)));
}
 
Example #27
Source File: HtmlExporter2BASE64.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 将带有 chart、map 等动态图表的 html 转换为 图片(可以额外配置 cookie 的权限控制).
 *
 * @param url         目标 URL
 * @param addedCookie 添加 cookie
 * @return 图片 string 字符串
 */
@Override
public String convert2Image(String url, Cookie addedCookie, Integer width, Integer height) {
    PhantomJSDriver driver = null;
    try {
        driver = HtmlExporterUtils.prepare(url, addedCookie, width, height);
        return driver.getScreenshotAs(OutputType.BASE64);
    } finally {
        HtmlExporterUtils.release(driver);
    }
}
 
Example #28
Source File: TestSetup.java    From restful-booker-platform with GNU General Public License v3.0 5 votes vote down vote up
void navigateToApplication(){
    if(System.getenv("TARGET") != null && System.getenv("TARGET").equals("production")){
        // We load the production page up initially to gain access to the site before
        // adding in the cookie to disabled the welcome popup. We finally have to refresh
        // the page to ensure the cookie is read and the popup is disabled.
        driver.navigate().to("https://automationintesting.online/#/admin");
        driver.manage().addCookie(new Cookie("welcome", "true"));
        driver.navigate().refresh();
    } else {
        driver.navigate().to("http://localhost:8080/#/admin");
    }
}
 
Example #29
Source File: HasCookieMatcher.java    From matchers-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void describeMismatchSafely(WebDriver item, Description mismatchDescription) {
    mismatchDescription.appendText("was only ");
    List<String> cookNames = new LinkedList<>();
    for (Cookie cook : item.manage().getCookies()) {
       cookNames.add(cook.getName());
    }
    mismatchDescription.appendValueList("[", ", ", "]", cookNames);
}
 
Example #30
Source File: CookiesPathTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleCookies() throws IOException {
    String requestURI = OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account";
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, 1);

    // create old cookie with wrong path
    BasicClientCookie wrongCookie = new BasicClientCookie(AuthenticationSessionManager.AUTH_SESSION_ID, AUTH_SESSION_VALUE);
    wrongCookie.setDomain(AUTH_SERVER_HOST);
    wrongCookie.setPath(OLD_COOKIE_PATH);
    wrongCookie.setExpiryDate(calendar.getTime());

    // obtain new cookies
    CookieStore cookieStore = getCorrectCookies(requestURI);
    cookieStore.addCookie(wrongCookie);

    Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(3));

    login(requestURI, cookieStore);

    // old cookie has been removed
    // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION
    Assert.assertThat(cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getName).collect(Collectors.toList()), 
            Matchers.hasItems("AUTH_SESSION_ID", "KEYCLOAK_IDENTITY", "KEYCLOAK_SESSION"));

    // does each cookie's path end with "/"
    cookieStore.getCookies().stream().filter(c -> !"OAuth_Token_Request_State".equals(c.getName())).map(org.apache.http.cookie.Cookie::getPath).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/")));

    // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value
    String authSessionId = cookieStore.getCookies().stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue();
    String KCSessionId = cookieStore.getCookies().stream().filter(c -> "KEYCLOAK_SESSION".equals(c.getName())).findFirst().get().getValue();
    String KCSessionSuffix = KCSessionId.split("/")[2];
    Assert.assertThat(authSessionId, Matchers.containsString(KCSessionSuffix));
}