Best Selenium code snippet using org.openqa.selenium.Cookie.getExpiry
Source:CookieTest.java  
...63        Assert.assertEquals("test", cookie.getName());64        Assert.assertEquals("test", cookie.getValue());65        Assert.assertEquals(".localhost", cookie.getDomain());66        Assert.assertEquals("/", cookie.getPath());67        Assert.assertTrue(((cookie.getExpiry()) != null));68        Assert.assertEquals(false, cookie.isSecure());69        org.openqa.selenium.Cookie cookie2 = driver.manage().getCookieNamed("test2");70        Assert.assertEquals("test2", cookie2.getName());71        Assert.assertEquals("test2", cookie2.getValue());72        Assert.assertEquals(".localhost", cookie2.getDomain());73        Assert.assertEquals("/", cookie2.getPath());74        Assert.assertEquals(false, cookie2.isSecure());75        Assert.assertTrue(((cookie2.getExpiry()) == null));76    }77    @Test78    public void gettingAllCookiesOnANonCookieSettingPage() {79        server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);80        goToPage();81        Assert.assertEquals(0, getCookies().length);82    }83    @Test84    public void deletingAllCookies() {85        server.setHttpHandler("GET", CookieTest.COOKIE_SETTING_CALLBACK);86        goToPage();87        driver.manage().deleteAllCookies();88        Assert.assertEquals(0, getCookies().length);89    }90    @Test91    public void deletingOneCookie() {92        server.setHttpHandler("GET", CookieTest.COOKIE_SETTING_CALLBACK);93        goToPage();94        driver.manage().deleteCookieNamed("test");95        org.openqa.selenium.Cookie[] cookies = getCookies();96        Assert.assertEquals(1, cookies.length);97        Assert.assertEquals("test2", cookies[0].getName());98    }99    @Test100    public void addingACookie() {101        server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);102        goToPage();103        driver.manage().addCookie(new org.openqa.selenium.Cookie("newCookie", "newValue", ".localhost", "/", null, false, false));104        org.openqa.selenium.Cookie[] cookies = getCookies();105        Assert.assertEquals(1, cookies.length);106        Assert.assertEquals("newCookie", cookies[0].getName());107        Assert.assertEquals("newValue", cookies[0].getValue());108        Assert.assertEquals(".localhost", cookies[0].getDomain());109        Assert.assertEquals("/", cookies[0].getPath());110        Assert.assertEquals(false, cookies[0].isSecure());111        Assert.assertEquals(false, cookies[0].isHttpOnly());112    }113    @Test114    public void modifyingACookie() {115        server.setHttpHandler("GET", CookieTest.COOKIE_SETTING_CALLBACK);116        goToPage();117        driver.manage().addCookie(new org.openqa.selenium.Cookie("test", "newValue", "localhost", "/", null, false));118        org.openqa.selenium.Cookie[] cookies = getCookies();119        Assert.assertEquals(2, cookies.length);120        Assert.assertEquals("test", cookies[1].getName());121        Assert.assertEquals("newValue", cookies[1].getValue());122        Assert.assertEquals(".localhost", cookies[1].getDomain());123        Assert.assertEquals("/", cookies[1].getPath());124        Assert.assertEquals(false, cookies[1].isSecure());125        Assert.assertEquals("test2", cookies[0].getName());126        Assert.assertEquals("test2", cookies[0].getValue());127        Assert.assertEquals(".localhost", cookies[0].getDomain());128        Assert.assertEquals("/", cookies[0].getPath());129        Assert.assertEquals(false, cookies[0].isSecure());130    }131    @Test132    public void shouldRetainCookieInfo() {133        server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);134        goToPage();135        // Added cookie (in a sub-path - allowed)136        org.openqa.selenium.Cookie addedCookie = // < now + 100sec137        new org.openqa.selenium.Cookie.Builder("fish", "cod").expiresOn(new Date(((System.currentTimeMillis()) + (100 * 1000)))).path("/404").domain("localhost").build();138        driver.manage().addCookie(addedCookie);139        // Search cookie on the root-path and fail to find it140        org.openqa.selenium.Cookie retrieved = driver.manage().getCookieNamed("fish");141        Assert.assertNull(retrieved);142        // Go to the "/404" sub-path (to find the cookie)143        goToPage("404");144        retrieved = driver.manage().getCookieNamed("fish");145        Assert.assertNotNull(retrieved);146        // Check that it all matches147        Assert.assertEquals(addedCookie.getName(), retrieved.getName());148        Assert.assertEquals(addedCookie.getValue(), retrieved.getValue());149        Assert.assertEquals(addedCookie.getExpiry(), retrieved.getExpiry());150        Assert.assertEquals(addedCookie.isSecure(), retrieved.isSecure());151        Assert.assertEquals(addedCookie.getPath(), retrieved.getPath());152        Assert.assertTrue(retrieved.getDomain().contains(addedCookie.getDomain()));153    }154    @Test(expected = InvalidCookieDomainException.class)155    public void shouldNotAllowToCreateCookieOnDifferentDomain() {156        goToPage();157        // Added cookie (in a sub-path)158        org.openqa.selenium.Cookie addedCookie = // < now + 100sec159        new org.openqa.selenium.Cookie.Builder("fish", "cod").expiresOn(new Date(((System.currentTimeMillis()) + (100 * 1000)))).path("/404").domain("github.com").build();160        driver.manage().addCookie(addedCookie);161    }162    @Test163    public void shouldAllowToDeleteCookiesEvenIfNotSet() {164        WebDriver d = getDriver();165        d.get("https://github.com/");166        // Clear all cookies167        Assert.assertTrue(((d.manage().getCookies().size()) > 0));168        d.manage().deleteAllCookies();169        Assert.assertEquals(d.manage().getCookies().size(), 0);170        // All cookies deleted, call deleteAllCookies again. Should be a no-op.171        d.manage().deleteAllCookies();172        d.manage().deleteCookieNamed("non_existing_cookie");173        Assert.assertEquals(d.manage().getCookies().size(), 0);174    }175    @Test176    public void shouldAllowToSetCookieThatIsAlreadyExpired() {177        WebDriver d = getDriver();178        d.get("https://github.com/");179        // Clear all cookies180        Assert.assertTrue(((d.manage().getCookies().size()) > 0));181        d.manage().deleteAllCookies();182        Assert.assertEquals(d.manage().getCookies().size(), 0);183        // Added cookie that expires in the past184        org.openqa.selenium.Cookie addedCookie = // < now - 1 second185        new org.openqa.selenium.Cookie.Builder("expired", "yes").expiresOn(new Date(((System.currentTimeMillis()) - 1000))).build();186        d.manage().addCookie(addedCookie);187        org.openqa.selenium.Cookie cookie = d.manage().getCookieNamed("expired");188        Assert.assertNull(cookie);189    }190    @Test(expected = Exception.class)191    public void shouldThrowExceptionIfAddingCookieBeforeLoadingAnyUrl() {192        // NOTE: At the time of writing, this test doesn't pass with FirefoxDriver.193        // ChromeDriver is fine instead.194        String xval = "123456789101112";// < detro: I buy you a beer if you guess what am I quoting here195        WebDriver d = getDriver();196        // Set cookie, without opening any page: should throw an exception197        d.manage().addCookie(new org.openqa.selenium.Cookie("x", xval));198    }199    @Test200    public void shouldBeAbleToCreateCookieViaJavascriptOnGoogle() {201        String ckey = "cookiekey";202        String cval = "cookieval";203        WebDriver d = getDriver();204        d.get("http://www.google.com");205        JavascriptExecutor js = ((JavascriptExecutor) (d));206        // Of course, no cookie yet(!)207        org.openqa.selenium.Cookie c = d.manage().getCookieNamed(ckey);208        Assert.assertNull(c);209        // Attempt to create cookie on multiple Google domains210        js.executeScript((((((((((((((((((((((("javascript:(" + (("function() {" + "   cook = document.cookie;") + "   begin = cook.indexOf('")) + ckey) + "=');") + "   var val;") + "   if (begin !== -1) {") + "       var end = cook.indexOf(\";\",begin);") + "       if (end === -1)") + "           end=cook.length;") + "       val=cook.substring(begin+11,end);") + "   }") + "   val = ['") + cval) + "'];") + "   if (val) {") + "       var d=Array('com','co.jp','ca','fr','de','co.uk','it','es','com.br');") + "       for (var i = 0; i < d.length; i++) {") + "           document.cookie = '") + ckey) + "='+val+';path=/;domain=.google.'+d[i]+'; ';") + "       }") + "   }") + "})();"));211        c = d.manage().getCookieNamed(ckey);212        Assert.assertNotNull(c);213        Assert.assertEquals(cval, c.getValue());214        // Set cookie as empty215        js.executeScript(((((("javascript:(" + ((("function() {" + "   var d = Array('com','co.jp','ca','fr','de','co.uk','it','cn','es','com.br');") + "   for(var i = 0; i < d.length; i++) {") + "       document.cookie='")) + ckey) + "=;path=/;domain=.google.'+d[i]+'; ';") + "   }") + "})();"));216        c = d.manage().getCookieNamed(ckey);217        Assert.assertNotNull(c);218        Assert.assertEquals("", c.getValue());219    }220    @Test221    public void addingACookieWithDefaults() {222        server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);223        goToPage();224        long startTime = new Date().getTime();225        driver.manage().addCookie(new org.openqa.selenium.Cookie("newCookie", "newValue"));226        org.openqa.selenium.Cookie[] cookies = getCookies();227        Assert.assertEquals(1, cookies.length);228        Assert.assertEquals("newCookie", cookies[0].getName());229        Assert.assertEquals("newValue", cookies[0].getValue());230        Assert.assertEquals(".localhost", cookies[0].getDomain());231        Assert.assertEquals("/", cookies[0].getPath());232        Assert.assertEquals(false, cookies[0].isSecure());233        Assert.assertEquals(false, cookies[0].isHttpOnly());234        // expiry > 19 years in the future235        Assert.assertTrue(((startTime + 599184000000L) <= (cookies[0].getExpiry().getTime())));236    }237}...Source:CookiesExercisesTestWorkOnOpera.java  
...17import static junit.framework.Assert.fail;1819// this is different from CookiesExercisesTest,20// this has additional synchronisation to allow it to work on Opera21// but it seems opera doesn't add cookies if date is in the past, but that is what the getExpiry on a cookie in Opera returns22public class CookiesExercisesTestWorkOnOpera {232425    private static WebDriver driver;26    public static final String SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS = "seleniumSimplifiedSearchNumVisits";27    private WebElement queryInput;28    private WebElement submitButton;2930    @Before31    public void setup(){3233        driver = Driver.get("http://compendiumdev.co.uk/selenium/" +34                        "search.php");3536        //seleniumSimplifiedSearchLastVisit37        //seleniumSimplifiedSearchNumVisits38        //seleniumSimplifiedLastSearch3940        //clear any cookies so it is41        // always the first time we have been here42        driver.manage().deleteAllCookies();4344        refreshPageObjects();4546    }4748    private void refreshPageObjects(){49        queryInput = driver.findElement(By.name("q"));50        submitButton = driver.findElement(By.name("btnG"));51    }5253    @Test54    public void doASearchAndCheckForCookies(){5556        queryInput.clear();57        queryInput.sendKeys("Cookie Test");58        submitButton.click();5960        Set<Cookie> cookies = driver.manage().getCookies();61        for(Cookie aCookie : cookies){62            if(aCookie.getName().contentEquals(SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS)){63                assertEquals(   "Should be my first visit",64                                String.valueOf(1),65                                aCookie.getValue());66            }67        }68    }6970    @Test71    public void getCookieDirectly(){7273        queryInput.clear();74        queryInput.sendKeys("Cookie Test");75        submitButton.click();7677        waitForResultsToDisplay();7879        Cookie aCookie = driver.manage().getCookieNamed(SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS);8081        assertEquals(   "Should be my first visit",82                        1,83                        Integer.parseInt(aCookie.getValue()));84    }8586    public void waitForResultsToDisplay(){87        // need to do this otherwise Opera races ahead and throws null pointer exceptions on the cookies88        new WebDriverWait(driver,10).until(ExpectedConditions.presenceOfElementLocated(By.id("resultList")));89        waitForCookieNamed(SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS);90    }9192    private Cookie waitForCookieNamed(String cookieName) {93        return new WebDriverWait(driver,10).until(cookieExistsNamed(cookieName));94    }95969798    private ExpectedCondition<Cookie> cookieExistsNamed(final String cookieName) {99        return new ExpectedCondition<Cookie>() {100            @Override101            public Cookie apply(WebDriver input) {102                return input.manage().getCookieNamed(cookieName);103            }104        };105    }106107108    private Cookie waitForCookieWithValue(String cookieName, String cookieValue) {109        return new WebDriverWait(driver,10).until(cookieWithValueExists(cookieName, cookieValue));110    }111112    private ExpectedCondition<Cookie> cookieWithValueExists(final String cookieName, final String cookieValue){113        return new ExpectedCondition<Cookie>(){114115            @Override116            public Cookie apply(WebDriver input) {117                Cookie cookie = waitForCookieNamed(cookieName);118                if(cookie!=null){119                    if(cookie.getValue().equals(cookieValue)){120                        return cookie;121                    }122                }123                return null;124            };125        };126    }127128129130131132    @Test133    public void changeCookieVisitsCount(){134135        queryInput.clear();136        queryInput.sendKeys("Cookie Test");137        submitButton.click();138139        waitForResultsToDisplay();140141        Cookie aCookie = driver.manage().142                                getCookieNamed(SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS);143144        assertEquals(   "Should be my first visit",145                        1,146                        Integer.parseInt(aCookie.getValue()));147148        // clone cookie and set value to what I want149        Cookie aNewCookie = null;150        if(Driver.currentDriver == Driver.BrowserName.OPERA){151            // Opera does not return the correct expiry date for cookies152            // so work around it153            aNewCookie = new Cookie( aCookie.getName(),154                String.valueOf(42),155                aCookie.getDomain(),156                aCookie.getPath(),157                null,158                aCookie.isSecure());159        }else{160            aNewCookie = new Cookie( aCookie.getName(),161                    String.valueOf(42),162                    aCookie.getDomain(),163                    aCookie.getPath(),164                    aCookie.getExpiry(),165                    aCookie.isSecure());166        }167168        int cookieCount = driver.manage().getCookies().size();169        driver.manage().deleteCookie(aCookie);170        driver.manage().addCookie(aNewCookie);171        assertEquals("we added the cookie correctly", cookieCount, driver.manage().getCookies().size());172173        // do this after cookie processing otherwise Opera throws a stale element exception174        refreshPageObjects();175176        queryInput.clear();177        queryInput.sendKeys("Cookie Changed Test");178        submitButton.click();179180        waitForResultsToDisplay();181        waitForCookieWithValue(SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS, "43");182183        aCookie = driver.manage().getCookieNamed(SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS);184        assertEquals("I should be a frequent visitor", 43, Integer.parseInt(aCookie.getValue()));185    }186187    @Test188    public void changeCookieVisitsCountUsingCookieBuilder(){189190        queryInput.clear();191        queryInput.sendKeys("Cookie Test");192        submitButton.click();193194        waitForResultsToDisplay();195196        Cookie aCookie = driver.manage().getCookieNamed(SELENIUM_SIMPLIFIED_SEARCH_NUM_VISITS);197        assertEquals("Should be my first visit", 1, Integer.parseInt(aCookie.getValue()));198199200201        Cookie aNewCookie = null;202        // clone cookie and set value to what I want203        if(Driver.currentDriver == Driver.BrowserName.OPERA){204            // opera driver returns the wrong expiry date for the cookie - it returns  Sat Jan 17 02:23:04 GMT 1970205            // but actual value was 2013/12/18 16:36206            // therefore we can't use the expiry date207            aNewCookie = new Cookie.Builder( aCookie.getName(), String.valueOf(29))208                                    .domain(aCookie.getDomain())209                                    .path( aCookie.getPath())210                                    /*.expiresOn(aCookie.getExpiry())*/211                                    .isSecure(aCookie.isSecure()).build();212213            if(!aCookie.getExpiry().toString().contains("GMT 1970")){214                fail("Opera Driver may be returning the correct date for cookies now " + aCookie.getExpiry());215            }216217        }else{218            aNewCookie = new Cookie.Builder( aCookie.getName(), String.valueOf(29))219                    .domain(aCookie.getDomain())220                    .path( aCookie.getPath())221                    .expiresOn(aCookie.getExpiry())222                    .isSecure(aCookie.isSecure()).build();223        }224225        int cookieCount = driver.manage().getCookies().size();226        driver.manage().deleteCookie(aCookie);227        driver.manage().addCookie(aNewCookie);228        assertEquals("we added the cookie correctly", cookieCount, driver.manage().getCookies().size());229230        refreshPageObjects();231232        queryInput.clear();233        queryInput.sendKeys("Cookie Changed Test");234        submitButton.click();235
...Source:Test.java  
...64	}65		66		67		org.openqa.selenium.Cookie cookie1 = driver.manage().getCookieNamed("ACCOUNT_CHOOSER");68		Date Exp = cookie1.getExpiry();69		System.out.println(Exp);70		//Calendar cal = Calendar.getInstance();71		//cal.add(Calendar.DATE, -1);72		73		//driver.manage().deleteCookieNamed("ACCOUNT_CHOOSER");74		//driver.manage().deleteCookieNamed("GAPS");75		//driver.manage().deleteAllCookies();76		77		78		System.out.println("Deleted Cookies");79		System.out.println("");80		System.out.println("");81		System.out.println("");82		System.out.println("");83		Set<org.openqa.selenium.Cookie> cookiesList2 =  driver.manage().getCookies();84		for(org.openqa.selenium.Cookie getcookies :cookiesList2) {85		    System.out.println(getcookies);86		    System.out.println("");87		88		// TODO Auto-generated method stub8990	}91		driver.navigate().refresh();92		//driver.manage().addCookie((cookie1));93		//driver.manage().addCookie((org.openqa.selenium.Cookie) cookiesList1);94		Thread.sleep(5000);95		 for(org.openqa.selenium.Cookie cookie : allCookies) {96	            driver.manage().addCookie(cookie);97	            98		driver.navigate().refresh();99		driver.get("https://gmail.com/");100		101		System.out.println("Final Cookies");102		103		Set<org.openqa.selenium.Cookie> cookiesList3 =  driver.manage().getCookies();104		for(org.openqa.selenium.Cookie getcookies :cookiesList3) {105		    System.out.println(getcookies);106		    System.out.println("");107	}*/108109		110		File file = new File("Cookies.data");							111        try		112        {		113            // Delete old file if exists114			file.delete();		115            file.createNewFile();			116            FileWriter fileWrite = new FileWriter(file);							117            BufferedWriter Bwrite = new BufferedWriter(fileWrite);							118            // loop for getting the cookie information 		119            for(org.openqa.selenium.Cookie ck : driver.manage().getCookies())							120            {		121                Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));																									122                Bwrite.newLine();			123        }		124            Bwrite.flush();			125            Bwrite.close();			126            fileWrite.close();			127        }catch(Exception ex)					128        {		129            ex.printStackTrace();			130        }		131		}132	}
...Source:WebDriver81CookiesTest.java  
...92			Cookie aNewCookie = new Cookie( aCookie.getName(),93					String.valueOf(42),94					aCookie.getDomain(),95					aCookie.getPath(),96					aCookie.getExpiry(),aCookie.isSecure());97			98			driver.manage().deleteCookie(aCookie);99			driver.manage().addCookie(aNewCookie);100			101			searchBox.clear();102			searchBox.sendKeys("New Cookie Test");103			searchButton.click();104			105			aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");106			assertEquals("This should be my first visit", "43", aCookie.getValue());107			108		}109		110		@Test111		public void webDriverUpdateCookieBuilder() {112			113			searchBox.clear();114			searchBox.sendKeys("Cookie Test");115			searchButton.click();116			117			refreshSearchPage();118			119			Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");120			assertEquals("This should be my first visit", "1", aCookie.getValue());121			122			// Clone Cookie and set Value to what is wanted123			Cookie aNewCookie = new Cookie.Builder( aCookie.getName(), String.valueOf(29))124					.domain(aCookie.getDomain())125					.path(aCookie.getPath())126					.expiresOn(aCookie.getExpiry())127					.isSecure(aCookie.isSecure()).build();128			129			driver.manage().deleteCookie(aCookie);130			driver.manage().addCookie(aNewCookie);131			132			searchBox.clear();133			searchBox.sendKeys("Another Cookie Test");134			searchButton.click();135			136			aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");137			assertEquals("This should be my first visit", "30", aCookie.getValue());138			139		}140		
...Source:CookieAdapter.java  
...20        }21        if(cookie.getDomain() != null){22            newCookie.domain(cookie.getDomain());23        }24        if(cookie.getExpiryDate() != null){25            newCookie.expiresOn(cookie.getExpiryDate());26        }27        if(cookie.isHttpOnly()){28            newCookie.isHttpOnly(cookie.isHttpOnly());29        }30        if(cookie.getMaxAge() != -1){31            Calendar currentDate = Calendar.getInstance();32            currentDate.setTimeZone(TimeZone.getTimeZone("GMT"));33            currentDate.add(Calendar.SECOND, cookie.getMaxAge());34            newCookie.expiresOn(currentDate.getTime());35        }36        if(cookie.getPath() != null){37            newCookie.path(cookie.getPath());38        }39        if(cookie.isSecured()){40            newCookie.isSecure(cookie.isSecured());41        }42        if(cookie.getVersion() != -1){43            System.out.println("NOTE: The cookie taken from RestAssured has a version attribute of '" + cookie.getVersion() + "'. Selenium doesn't support the addition of version so this has been discarded");44        }45        return newCookie.build();46    }47    public Cookie convertToRestAssured(org.openqa.selenium.Cookie cookie) {48        Cookie.Builder newCookie = new Cookie.Builder(cookie.getName(), cookie.getValue());49        if(cookie.getDomain() != null){50            newCookie.setDomain(cookie.getDomain());51        }52        if(cookie.getExpiry() != null){53            if(expiryType.equals(ExpiryType.EXPIRY)){54                newCookie.setExpiryDate(cookie.getExpiry());55            } else if(expiryType.equals(ExpiryType.MAXAGE)){56                Calendar futureDate = Calendar.getInstance();57                futureDate.setTime(cookie.getExpiry());58                Calendar currentDate = Calendar.getInstance();59                long end = TimeUnit.MILLISECONDS.toSeconds(futureDate.getTimeInMillis());60                long start = TimeUnit.MILLISECONDS.toSeconds(currentDate.getTimeInMillis());61                int result = toIntExact(end - start);62                newCookie.setMaxAge(result);63            }64        }65        if(cookie.isHttpOnly()){66            newCookie.setHttpOnly(cookie.isHttpOnly());67        }68        if(cookie.isSecure()){69            newCookie.setSecured(cookie.isSecure());70        }71        if(cookie.getPath() != null){...Source:AddCookies.java  
...33			file1.createNewFile();34			FileWriter fw=new FileWriter(file1);35			BufferedWriter bw=new BufferedWriter(fw);36			for(Cookie ck:wd.manage().getCookies()) {37				bw.write((ck.getName()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()+";"+ck.getValue()));38				bw.newLine();39			}40			bw.close();41			fw.close();42		}43		catch(Exception e) {44			System.out.println(e);45	}46	  47	  //DELETING COOKIES----------------------------------------48	  wd.manage().deleteCookieNamed("aditya");49	  File f1=new File("C:\\Users\\aditya_ku\\Documents\\deletedcookies.data");50	  51	  try {52			f1.createNewFile();53			FileWriter fa=new FileWriter(f1);54			BufferedWriter ba=new BufferedWriter(fa);55			for(Cookie ck:wd.manage().getCookies()) {56				ba.write((ck.getName()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()+";"+ck.getValue()));57				ba.newLine();58			}59			ba.close();60			fa.close();61		}62		catch(Exception e) {63			System.out.println(e);64	  65	  66  }67}}...Source:DeleteCookie.java  
...24		  for(Cookie C:allCookie)25		  {26			  System.out.println("Cookie name is:"+C.getName());27			  System.out.println("Cookie Domain is:"+C.getDomain());28			  System.out.println("Cookie Expiry is"+C.getExpiry());29			  System.out.println("Cookie value is:"+C.getValue());30			  System.out.println("Cookie Path is"+C.getPath());31			  32		  }33		  driver.manage().deleteAllCookies();34		  System.out.println("Cookies Deleted");35		  Set<Cookie> allCookie2=driver.manage().getCookies();36		  System.out.println("Hi");37		  System.out.println(allCookie2.size());38		  for(Cookie C:allCookie2)39		  {40			  System.out.println("After logout");41			  System.out.println("Cookie name is:"+C.getName());42			  System.out.println("Cookie Domain is:"+C.getDomain());43			  System.out.println("Cookie Expiry is"+C.getExpiry());44			  System.out.println("Cookie value is:"+C.getValue());45			  System.out.println("Cookie Path is"+C.getPath());46			  47		  }48		  driver.findElement(By.linkText("SQL")).click();49		  driver.navigate().refresh();50		  51	  }52		  else53		  {54			  System.out.println("login failed");55		  }56  }57	  ...Source:SetBufferCookies.java  
...31FileWriter fos = new FileWriter(f);32BufferedWriter bos = new BufferedWriter(fos);33for(Cookie ck : driver.manage().getCookies()) {34bos.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()35+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));36System.out.println(ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure());37bos.newLine();38}39bos.flush();40bos.close();41fos.close();42}catch(Exception ex){43ex.printStackTrace();44}45}46}
...getExpiry
Using AI Code Generation
1package com.edureka.selenium;2import org.openqa.selenium.By;3import org.openqa.selenium.Cookie;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.chrome.ChromeOptions;8import java.util.Date;9import java.util.Set;10public class CookieManager {11    public static void main(String[] args) {12        System.setProperty("webdriver.chrome.driver", "C:\\Users\\edureka\\Downloads\\chromedriver_win32\\chromedriver.exe");13        ChromeOptions options = new ChromeOptions();14        options.setExperimentalOption("useAutomationExtension", false);15        WebDriver driver = new ChromeDriver(options);16        driver.manage().window().maximize();17        driver.findElement(By.linkText("Log In")).click();18        driver.findElement(By.id("si_popup_email")).sendKeys("getExpiry
Using AI Code Generation
1Cookie cookie = driver.manage().getCookieNamed("cookieName");2System.out.println(cookie.getExpiry());3Cookie cookie = driver.manage().getCookieNamed("cookieName");4System.out.println(cookie.getDomain());5Cookie cookie = driver.manage().getCookieNamed("cookieName");6System.out.println(cookie.getPath());7Cookie cookie = driver.manage().getCookieNamed("cookieName");8System.out.println(cookie.isSecure());9Cookie cookie = driver.manage().getCookieNamed("cookieName");10System.out.println(cookie.isHttpOnly());11Cookie cookie = driver.manage().getCookieNamed("cookieName");12System.out.println(cookie.toString());13Cookie cookie = driver.manage().getCookieNamed("cookieName");14System.out.println(cookie.equals(cookie));15Cookie cookie = driver.manage().getCookieNamed("cookieName");16System.out.println(cookie.hashCode());17Cookie cookie = driver.manage().getCookieNamed("cookieName");18System.out.println(cookie.compareTo(cookie));19Cookie cookie = driver.manage().getCookieNamed("cookieName");20System.out.println(cookie.getName());21Cookie cookie = driver.manage().getCookieNamed("cookieName");22System.out.println(cookie.getValue());23Cookie cookie = driver.manage().getCookieNamed("cookieName");24cookie.setValue("newValue");25Cookie cookie = driver.manage().getCookieNamed("cookieName");26cookie.setExpiry(new Date());27Cookie cookie = driver.manage().getCookieNamed("cookieName");28cookie.setDomain("newDomain");29Cookie cookie = driver.manage().getCookieNamed("cookieName");30cookie.setPath("newPath");getExpiry
Using AI Code Generation
1package test;2import java.util.Set;3import java.util.concurrent.TimeUnit;4import org.openqa.selenium.By;5import org.openqa.selenium.Cookie;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.chrome.ChromeDriver;8public class Cookies {9public static void main(String[] args) {10    System.setProperty("webdriver.chrome.driver", "C:\\Users\\Acer\\Downloads\\chromedriver_win32\\chromedriver.exe");11    WebDriver driver = new ChromeDriver();12    driver.manage().window().maximize();13    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);14    driver.findElement(By.id("email")).sendKeys("getExpiry
Using AI Code Generation
1import org.openqa.selenium.Cookie;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4public class GetCookieExpiryDate {5    public static void main(String[] args) {6        System.setProperty("webdriver.chrome.driver", "C:\\Users\\username\\Downloads\\chromedriver_win32\\chromedriver.exe");7        WebDriver driver = new ChromeDriver();8        Cookie name = driver.manage().getCookieNamed("NID");9        System.out.println(name.getExpiry());10        driver.quit();11    }12}getExpiry
Using AI Code Generation
1Date expiry = driver.manage().getCookieNamed("myCookie").getExpiry();2boolean isExpirySet = driver.manage().getCookieNamed("myCookie").isExpirySet();3String domain = driver.manage().getCookieNamed("myCookie").getDomain();4String path = driver.manage().getCookieNamed("myCookie").getPath();5boolean isSecure = driver.manage().getCookieNamed("myCookie").isSecure();6boolean isHttpOnly = driver.manage().getCookieNamed("myCookie").isHttpOnly();7Date expiry = driver.manage().getCookieNamed("myCookie").getExpiry();8boolean isExpirySet = driver.manage().getCookieNamed("myCookie").isExpirySet();9String domain = driver.manage().getCookieNamed("myCookie").getDomain();10String path = driver.manage().getCookieNamed("myCookie").getPath();11boolean isSecure = driver.manage().getCookieNamed("myCookie").isSecure();getExpiry
Using AI Code Generation
1Cookie cookie = driver.manage().getCookieNamed("cookieName");2System.out.println(expiry);3JavascriptExecutor js = (JavascriptExecutor) driver;4String expiryDate = (String) js.executeScript("return document.cookie;");5System.out.println(expiryDate);6cookieName=cookieValue; expires=Tue, 01 Jan 2019 00:00:00 GMT; path=/; domain=example.com7File file = new File("path to cookies.txt file");8FileReader fileReader = new FileReader(file);9BufferedReader bufferedReader = new BufferedReader(fileReader);10String line;11while ((line = bufferedReader.readLine()) != null) {12    if (line.contains("cookieName")) {13        String[] cookieDetails = line.split("\t");14        String expiryDate = cookieDetails[4];15        System.out.println(expiryDate);16    }17}18bufferedReader.close();19fileReader.close();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!!
