Best Selenium code snippet using org.openqa.selenium.Cookie.Builder.expiresOn
Source:CookieImplementationTest.java  
...252    driver.manage().deleteAllCookies();253    Cookie addedCookie =254        new Cookie.Builder("fish", "cod")255            .path("/common/animals")256            .expiresOn(someTimeInTheFuture())257            .build();258    driver.manage().addCookie(addedCookie);259    Set<Cookie> cookies = driver.manage().getCookies();260    Cookie retrievedCookie = null;261    for (Cookie temp : cookies) {262      if (addedCookie.equals(temp)) {263        retrievedCookie = temp;264        break;265      }266    }267    assertNotNull("Cookie was null", retrievedCookie);268    // Cookie.equals only compares name, domain and path269    assertEquals(addedCookie, retrievedCookie);270  }271  @Ignore(value = {ANDROID, IE, OPERA}, reason =272      "Selenium, which use JavaScript to retrieve cookies, cannot return expiry info; " +273          "Other suppressed browsers have not been tested.")274  @Test275  public void testRetainsCookieExpiry() {276    Cookie addedCookie =277        new Cookie.Builder("fish", "cod")278            .path("/common/animals")279            .expiresOn(someTimeInTheFuture())280            .build();281    driver.manage().addCookie(addedCookie);282    Cookie retrieved = driver.manage().getCookieNamed("fish");283    assertNotNull(retrieved);284    assertEquals(addedCookie.getExpiry(), retrieved.getExpiry());285  }286  @Ignore(ANDROID)287  @Test288  public void testSettingACookieThatExpiredInThePast() {289    long expires = System.currentTimeMillis() - 1000;290    Cookie cookie = new Cookie.Builder("expired", "yes").expiresOn(new Date(expires)).build();291    driver.manage().addCookie(cookie);292    cookie = driver.manage().getCookieNamed("fish");293    assertNull(294        "Cookie expired before it was set, so nothing should be returned: " + cookie, cookie);295  }296  @Test297  public void testCanSetCookieWithoutOptionalFieldsSet() {298    String key = generateUniqueKey();299    String value = "foo";300    Cookie cookie = new Cookie(key, value);301    assertCookieIsNotPresentWithName(key);302    driver.manage().addCookie(cookie);303    assertCookieHasValue(key, value);304  }...Source:CookieHandler.java  
...65    } else if ("delete".equals(action)) {66      String name = request.getQueryParameter("name");67      for (Cookie cookie : getCookies(request)) {68        if (!cookie.getName().equals(name)) {69          addCookie(response, new Cookie.Builder(name, "").path("/").expiresOn(new Date(0)).build());70        }71      }72      response.setContent(Contents.string(String.format(RESPONSE_STRING, "Cookie deleted", name), UTF_8));73    } else if ("deleteAll".equals(action)) {74      for (Cookie cookie : getCookies(request)) {75        addCookie(response, new Cookie.Builder(cookie.getName(), "").path("/").expiresOn(new Date(0)).build());76      }77      response.setContent(Contents.string(String.format(RESPONSE_STRING, "All cookies deleted", ""), UTF_8));78    } else {79      response.setContent(Contents.string(String.format(RESPONSE_STRING, "Unrecognized action", action), UTF_8));80    }81    return response;82  }83  private <X> void append(StringBuilder builder, X fromCookie, Function<X, String> value) {84    if (fromCookie == null) {85      return;86    }87    builder.append(value.apply(fromCookie)).append("; ");88  }89  private Collection<Cookie> getCookies(HttpRequest request) {90    return StreamSupport.stream(request.getHeaders("Cookie").spliterator(), false)91      .map(this::parse)92      .collect(Collectors.toList());93  }94  private void addCookie(HttpResponse response, Cookie cook) {95    StringBuilder cookie = new StringBuilder();96    // TODO: escape string as necessary97    String name = cook.getName();98    cookie.append(name)99      .append("=")100      .append(cook.getValue())101      .append("; ");102    append(cookie, cook.getDomain(), str -> "Domain=" + str);103    append(cookie, cook.getPath(), str -> "Path=" + str);104    append(cookie, cook.getExpiry(), date -> {105      ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC"));106      return "Expiry=" + RFC_1123_DATE_TIME.format(zonedDateTime);107    });108    append(cookie, cook.isSecure(), val -> "Secure");109    append(cookie, cook.isHttpOnly(), val -> "HttpOnly");110    response.addHeader("Set-Cookie", cookie.toString());111  }112  private Cookie parse(String cookieString) {113    String[] split = cookieString.split("=", 2);114    if (split.length < 2) {115      throw new IllegalStateException("Illegal cookie: " + cookieString);116    }117    int index = split[1].indexOf(";");118    if (index == -1) {119      return new Cookie(split[0], split[1]);120    }121    List<String> keysAndValues = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(split[1]);122    Cookie.Builder builder = new Cookie.Builder(split[0], keysAndValues.get(0));123    keysAndValues.stream()124      .skip(1)125      .forEach(keyAndValue -> {126        List<String> parts = Splitter.on("=").limit(2).trimResults().omitEmptyStrings().splitToList(keyAndValue);127        String key = parts.get(0).toLowerCase();128        switch (key) {129          case "domain":130            builder.domain(parts.get(1));131            break;132          case "expires":133            TemporalAccessor temporalAccessor = RFC_1123_DATE_TIME.parse(parts.get(1));134            builder.expiresOn(Date.from(Instant.from(temporalAccessor)));135            break;136          case "httponly":137            builder.isHttpOnly(true);138            break;139          case "path":140            builder.path(parts.get(1));141            break;142          case "secure":143            builder.isSecure(true);144            break;145          default:146            throw new RuntimeException("Unknown option: " + key);147        }148      });...Source:SessionUtil.java  
...44                Boolean httpOnly = m.getBoolean("httpOnly");45                builder.domain(domain).path(path).isSecure(secure).isHttpOnly(httpOnly);46                Long expiry = m.getLong("expiry");47                if (expiry != null) {48                    builder.expiresOn(new Date(expiry));49                }50                Cookie cookie = builder.build();51                driver.manage().addCookie(cookie);52            } catch (Exception e) {53                throw new RuntimeException(e);54            }55        });56        JSONArray lc = session.getJSONArray("lc");57        WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);58        LocalStorage localStorage = webStorage.getLocalStorage();59        lc.forEach(o -> {60            try {61                JSONObject item = (JSONObject) o;62                String key = item.getString("key");63                String value = item.getString("value");64                localStorage.setItem(key, value);65            } catch (Exception e) {66                throw new RuntimeException(e);67            }68        });69    }70    public static JSONObject getSessionV2(WebDriver driver) {71        JSONObject session = new JSONObject();72        Set<Cookie> set = driver.manage().getCookies();73        session.put("cookie", set);74        JSONObject lc = new JSONObject();75        WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);76        LocalStorage localStorage = webStorage.getLocalStorage();77        localStorage.keySet().forEach(c -> {78            lc.put(c, localStorage.getItem(c));79        });80        session.put("lc", lc);81        return session;82    }83    public static void setSessionV2(WebDriver driver, JSONObject session) {84        JSONArray cookies = session.getJSONArray("cookie");85        cookies.forEach(o -> {86            try {87                JSONObject m = (JSONObject) o;88                Cookie.Builder builder = new Cookie.Builder(m.getString("name"), m.getString("value"));89                String domain = m.getString("domain");90                String path = m.getString("path");91                Boolean secure = m.getBoolean("secure");92                Boolean httpOnly = m.getBoolean("httpOnly");93                builder.domain(domain).path(path).isSecure(secure).isHttpOnly(httpOnly);94                Long expiry = m.getLong("expiry");95                if (expiry != null) {96                    builder.expiresOn(new Date(expiry));97                }98                Cookie cookie = builder.build();99                driver.manage().addCookie(cookie);100            } catch (Exception e) {101                throw new RuntimeException(e);102            }103        });104        JSONObject lc = session.getJSONObject("lc");105        WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);106        LocalStorage localStorage = webStorage.getLocalStorage();107        lc.forEach((k, v) -> {108            localStorage.setItem(k, (String) v);109        });110    }...Source:SeleniumToRestAssuredTest.java  
...38        currentDate.set(Calendar.MINUTE, 0);39        currentDate.set(Calendar.SECOND, 0);40        currentDate.set(Calendar.HOUR_OF_DAY, 0);41        Cookie seleniumCookie = new Cookie.Builder("Cookie name", "Cookie value")42                                            .expiresOn(currentDate.getTime())43                                            .build();44        CookieAdapter cookieAdapter = new CookieAdapter(ExpiryType.EXPIRY);45        io.restassured.http.Cookie adaptedCookie = cookieAdapter.convertToRestAssured(seleniumCookie);46        Approvals.verify(adaptedCookie);47    }48    @Test49    public void convertCookieToMaxAgeTest(){50        Calendar futureDate = Calendar.getInstance();51        futureDate.set(2030, 01, 01);52        futureDate.set(Calendar.HOUR, 0);53        futureDate.set(Calendar.MINUTE, 0);54        futureDate.set(Calendar.SECOND, 0);55        futureDate.set(Calendar.HOUR_OF_DAY, 0);56        Calendar currentDate = Calendar.getInstance();57        long end = TimeUnit.MILLISECONDS.toSeconds(futureDate.getTimeInMillis());58        long start = TimeUnit.MILLISECONDS.toSeconds(currentDate.getTimeInMillis());59        int result = toIntExact(end - start);60        Cookie seleniumCookie = new Cookie.Builder("Cookie name", "Cookie value")61                .expiresOn(futureDate.getTime())62                .build();63        CookieAdapter cookieAdapter = new CookieAdapter(ExpiryType.MAXAGE);64        io.restassured.http.Cookie adaptedCookie = cookieAdapter.convertToRestAssured(seleniumCookie);65        assertThat(adaptedCookie.getMaxAge(), is(result));66    }67    @Test68    public void convertLiveCookieTest(){69        WebDriver driver = new ChromeDriver();70        driver.navigate().to("http://the-internet.herokuapp.com/");71        Cookie cookie = driver.manage().getCookieNamed("rack.session");72        CookieAdapter cookieAdapter = new CookieAdapter();73        io.restassured.http.Cookie adaptedCookie = cookieAdapter.convertToRestAssured(cookie);74        driver.quit();75        Approvals.verify(adaptedCookie.getClass());...Source:AddCookie.java  
...56    return new Cookie.Builder(name, value)57      .path(path)58      .domain(domain)59      .isSecure(secure)60      .expiresOn(expiry)61      .isHttpOnly(httpOnly)62      .build();63  }64  65  private boolean getBooleanFromRaw(String key) {66    if (rawCookie.containsKey(key)) {67      Object value = rawCookie.get(key);68      if ((value instanceof Boolean)) {69        return ((Boolean)value).booleanValue();70      }71      if ((value instanceof String)) {72        return ((String)value).equalsIgnoreCase("true");73      }74    }...Source:CookieAdapter.java  
...9        if(cookie.hasDomain()) {10            cookieBuilder.domain(cookie.getDomain());11        }12        if(cookie.hasExpiryDate()) {13            cookieBuilder.expiresOn(cookie.getExpiryDate());14        } else if(cookie.hasMaxAge()) {15            Calendar expiryDate = Calendar.getInstance();16            expiryDate.setTimeZone(TimeZone.getTimeZone("GMT"));17            expiryDate.add(Calendar.SECOND, cookie.getMaxAge());18            cookieBuilder.expiresOn(expiryDate.getTime());19        }20        if(cookie.hasPath()) {21            cookieBuilder.path(cookie.getPath());22        }23        if(cookie.hasComment()) {24            System.out.println("Selenium Cookie does not support addition of a comment");25        }26        if(cookie.hasVersion()) {27            System.out.println("Selenium Cookie does not support addition of a version");28        }29        cookieBuilder.isSecure(cookie.isSecured());30        cookieBuilder.isHttpOnly(cookie.isHttpOnly());31        return cookieBuilder.build();32    }...Source:selenium.java  
...40		System.out.println(cookie.getValue());41		driver.manage().addCookie(42		  new Cookie.Builder(cookie.getName(), "A_SHOW_MINICART")43		    .domain(cookie.getDomain())44		    .expiresOn(cookie.getExpiry())45		    .path(cookie.getPath())46		    .isSecure(cookie.isSecure())47		    .build()48		);49		50		*/51	}52}...Source:Cookie.java  
...5  private final String name;6  private final String value;7  private final String domain;8  private final String path;9  private final Date expiresOn;10  private final boolean httpOnly;11  private final boolean secure;12  public Cookie(13      @JsonProperty("name") final String name,14      @JsonProperty("value") final String value,15      @JsonProperty("domain") final String domain,16      @JsonProperty("path") final String path,17      @JsonProperty("expiresOn") final Date expiresOn,18      @JsonProperty("httpOnly") final boolean httpOnly,19      @JsonProperty("secure") final boolean secure20  ) {21    this.name = name;22    this.value = value;23    this.domain = domain;24    this.path = path;25    this.expiresOn = expiresOn;26    this.httpOnly = httpOnly;27    this.secure = secure;28  }29  public String getName() {30    return name;31  }32  public String getValue() {33    return value;34  }35  public String getDomain() {36    return domain;37  }38  public String getPath() {39    return path;40  }41  public Date getExpiresOn() {42    return expiresOn;43  }44  public boolean isHttpOnly() {45    return httpOnly;46  }47  public boolean isSecure() {48    return secure;49  }50  public org.openqa.selenium.Cookie toSeleniumCookie() {51    return new org.openqa.selenium.Cookie.Builder(name, value)52        .domain(domain)53        .path(path)54        .expiresOn(expiresOn)55        .isHttpOnly(httpOnly)56        .isSecure(secure)57        .build();58  }59}...expiresOn
Using AI Code Generation
1import org.openqa.selenium.Cookie;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.chrome.ChromeOptions;5import java.util.Date;6public class CookieExpiry {7    public static void main(String[] args) {8        System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\Downloads\\chromedriver_win32\\chromedriver.exe");9        ChromeOptions options = new ChromeOptions();10        options.addArguments("--disable-notifications");11        WebDriver driver = new ChromeDriver(options);12        driver.manage().window().maximize();13        driver.manage().addCookie(new Cookie.Builder("myCookie", "12345").expiresOn(new Date(2020, 12, 31)).build());14    }15}16import org.openqa.selenium.Cookie;17import org.openqa.selenium.WebDriver;18import org.openqa.selenium.chrome.ChromeDriver;19import org.openqa.selenium.chrome.ChromeOptions;20import java.util.Date;21public class CookieExpiry {22    public static void main(String[] args) {23        System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\Downloads\\chromedriver_win32\\chromedriver.exe");24        ChromeOptions options = new ChromeOptions();25        options.addArguments("--disable-notifications");26        WebDriver driver = new ChromeDriver(options);27        driver.manage().window().maximize();28        driver.manage().addCookie(new Cookie("myCookie", "12345", "www.google.com", "/", new Date(2020, 12, 31)));29    }30}expiresOn
Using AI Code Generation
1Cookie cookie = new Cookie.Builder("name", "value")2    .expiresOn(new Date(2025, 10, 10))3    .build();4driver.manage().addCookie(cookie);5Cookie cookie = new Cookie.Builder("name", "value")6    .isHttpOnly(true)7    .build();8driver.manage().addCookie(cookie);9Cookie cookie = new Cookie.Builder("name", "value")10    .isSecure(true)11    .build();12driver.manage().addCookie(cookie);13Cookie cookie = new Cookie.Builder("name", "value")14    .path("/path")15    .build();16driver.manage().addCookie(cookie);17Cookie cookie = new Cookie.Builder("name", "value")18    .sameSite("Lax")19    .build();20driver.manage().addCookie(cookie);21Cookie cookie = new Cookie.Builder("name", "value")22    .withDomain("selenium.dev")23    .build();24driver.manage().addCookie(cookie);25Cookie cookie = new Cookie.Builder("name", "value")26    .withExpiry(new Date(2025, 10, 10))27    .build();28driver.manage().addCookie(cookie);29Cookie cookie = new Cookie.Builder("name", "value")30    .withHttpOnly(true)31    .build();32driver.manage().addCookie(cookie);33Cookie cookie = new Cookie.Builder("name", "value")34    .withName("name")35    .build();36driver.manage().addCookie(cookie);37Cookie cookie = new Cookie.Builder("name", "value")38    .withPath("/path")39    .build();40driver.manage().addCookie(cookie);41Cookie cookie = new Cookie.Builder("name", "value")42    .withSecure(true)43    .build();44driver.manage().addexpiresOn
Using AI Code Generation
1public class CookieExpiresOn {2    public static void main(String[] args) {3        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Shubham\\Downloads\\chromedriver_win32\\chromedriver.exe");4        ChromeDriver driver = new ChromeDriver();5        driver.manage().window().maximize();6        Cookie.Builder builder = new Cookie.Builder("Selenium", "Selenium");7        Cookie cookie = builder.expiresOn(new Date(2020, 10, 10)).build();8        driver.manage().addCookie(cookie);9        driver.quit();10    }11}12Starting ChromeDriver 2.46.628388 (d8c2e3a3f6d1cbb7e0c8b5f7a9e5f5d5b7b5e5a5) on port 15123expiresOn
Using AI Code Generation
1Cookie cookie = new Cookie.Builder("cookieName", "cookieValue")2    .expiresOn(new Date(System.currentTimeMillis() + 10000))3    .build();4driver.manage().addCookie(cookie);5Assert.assertTrue(driver.manage().getCookieNamed("cookieName") != null);6Thread.sleep(10000);7Assert.assertTrue(driver.manage().getCookieNamed("cookieName") == null);LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
