List of usage examples for org.openqa.selenium Cookie getName
public String getName()
From source file:com.machinepublishers.jbrowserdriver.OptionsServer.java
License:Apache License
private void removeFromCookieStore(org.apache.http.cookie.Cookie cookie) { BasicClientCookie tmp = new BasicClientCookie(cookie.getName(), ""); tmp.setDomain(cookie.getDomain());//from w w w.j a v a2 s .c o m tmp.setPath(cookie.getPath()); tmp.setExpiryDate(new Date(0)); cookieStore.addCookie(tmp); }
From source file:com.machinepublishers.jbrowserdriver.OptionsServer.java
License:Apache License
/** * {@inheritDoc}//from w w w . j av a2 s.com */ @Override public void deleteCookieNamed(String name) { for (org.apache.http.cookie.Cookie cur : cookieStore.getCookies()) { if (cur.getName().equals(name)) { removeFromCookieStore(cur); } } }
From source file:com.machinepublishers.jbrowserdriver.OptionsServer.java
License:Apache License
/** * {@inheritDoc}//w w w . j a v a 2s. co m */ @Override public Cookie getCookieNamed(String name) { for (org.apache.http.cookie.Cookie cur : cookieStore.getCookies()) { if (cur.getName().equals(name)) { return convert(cur); } } return null; }
From source file:com.partnet.automation.HtmlView.java
License:Apache License
/** * Clicks, then handles the resulting alert. * <p>/* w w w .ja va 2 s.com*/ * This method uses the {@link HtmlView#clickElem(WebElement)} method. * * @param elm - element to be clicked * @param accept - true to accept alert, false to dismiss. * @param throwIfNoAlertPresent - true to throw exception if there is no alert present, false otherwise * @return the string of the alert message */ private String clickAndHandleAlert(WebElement elm, boolean accept, boolean throwIfNoAlertPresent) { String alertMsg = null; LOG.debug("{} alert created by clicking button {}", accept ? "accept" : "dismiss", elm); Browser browser = getBrowser(); // headless browsers need to inject javascript before the button is clicked // to handle the alert correctly if (browser.isHeadless()) { // webDriver.manage().deleteCookieNamed(ALERT_COOKIE_NAME); StringBuilder alertJs = new StringBuilder(); alertJs.append("window.alert = window.confirm = function(msg){ ") // .append( "var date = new Date();") // .append( "date.setDate(date.getDate() + 1);") // cookies don't like to store new lines. This becomes a problem when // taking a screenshot for HTMLUNIT, and // transferring the cookie to PhantomJs. // This prevents newlines from being injected into the cookie. Later // on, the return string containing these // newline keywords will be replaced with actual newlines. .append("msg = msg.replace(/(\\r\\n|\\n|\\r)/gm, '" + ALERT_NEW_LINE_REPLACE + "');") .append("document.cookie = '" + ALERT_COOKIE_NAME + "=' + msg + '';").append("return %s;") .append("};"); executeScript(String.format(alertJs.toString(), accept)); } clickElem(elm); if (browser.isHeadless()) { Cookie alertCookie = webDriver.manage().getCookieNamed(ALERT_COOKIE_NAME); for (Cookie cook : webDriver.manage().getCookies()) { System.err.print(cook.getName()); } if (alertCookie != null) { // replace all newline keywords, to get original message alertMsg = StringUtils.trimToNull(alertCookie.getValue()); if (alertMsg != null) alertMsg = alertMsg.replaceAll(ALERT_NEW_LINE_REPLACE, "\n"); LOG.debug("Headless browser msg: {}", alertMsg); } else { LOG.debug("Cookie where headless alert messages are stored is null!"); } if (StringUtils.isBlank(alertMsg)) { if (throwIfNoAlertPresent) { throw new NoAlertPresentException( String.format("No alert message found for headless browser %s!", browser)); } } } else { Alert alert; // IE needs to wait for the alert to appear because we are using native // events try { if (browser.isInternetExplorer()) { alert = waitForAlertToBePresent(); } else { alert = webDriver.switchTo().alert(); } alertMsg = alert.getText(); if (accept) { alert.accept(); } else { alert.dismiss(); } } catch (NoAlertPresentException | TimeoutException e) { if (throwIfNoAlertPresent) { throw e; } else { LOG.debug("No alert is present! return..."); } return null; } } LOG.debug("{} alert message: {}", accept ? "Accepted" : "Dismissed", alertMsg); return alertMsg; }
From source file:com.testmax.handler.SeleniumBaseHandler.java
License:CDDL license
@Before public synchronized void setUp() throws Exception { //set default driver if (this.isMultiThreaded) { this.libs = null; this.createLogFile(); this.varmap = BaseHandler.threadData.get(threadIndex); if (this.libs == null || this.libs.isEmpty()) { this.libs = this.parseTagLib(); }//from w ww. j a va 2s . c om } else { this.libs = this.parseTagLib(); this.varmap = BaseHandler.getVarMap(); this.threadIndex = this.varmap.get("datasetIndex"); } this.printMessage("####### SELENIUM TEST STARTED #################"); this.printMessage("####### Dataset:" + this.varmap.values()); this.timer = new PrintTime(); File file = null; //driver = new FirefoxDriver(); v_driver = getDeclaredVariable("driver"); if (v_driver == null || v_driver.isEmpty()) { v_driver = ConfigLoader.getConfig("SELENIUM_DRIVER"); if (v_driver == null || v_driver.isEmpty()) { v_driver = "firefox"; } } String driver_path = getDeclaredVariable("driver_path"); if (v_driver.equalsIgnoreCase("chrome")) { if (TestEngine.suite != null) { file = new File(driver_path != null && !driver_path.isEmpty() ? driver_path : chrome_driver_path); if (!file.exists()) { String chrome_path = TestEngine.suite.getWorkspace() + TestEngine.suite.getJobname() + "/lib/chromedriver.exe"; file = new File(chrome_path); if (!file.exists()) { file = new File(TestEngine.suite.getWorkspace() + "/lib/chromedriver.exe"); } } } else { file = new File(driver_path != null && !driver_path.isEmpty() ? driver_path : chrome_driver_path); } this.printMessage("Chrome Driver Path=" + file.getAbsolutePath()); System.setProperty("webdriver.chrome.driver", file.getAbsolutePath()); DesiredCapabilities capability = DesiredCapabilities.chrome(); //capability.setCapability("chrome.switches", Arrays.asList("--allow-running-insecure-content=true")); if (System.getProperty("os.name").toLowerCase().contains("mac")) { file = new File(ConfigLoader.getWmRoot() + "/lib/chromedriver_mac"); System.setProperty("webdriver.chrome.driver", file.getAbsolutePath()); capability.setCapability("platform", Platform.ANY); capability.setCapability("binary", "/Application/chrome"); //for linux "chrome.switches", "--verbose" capability.setCapability("chrome.switches", "--verbose"); driver = new ChromeDriver(capability); } else { driver = new ChromeDriver(capability); } } else if (v_driver.equalsIgnoreCase("ie")) { if (is64bit()) { file = new File(driver_path != null && !driver_path.isEmpty() ? driver_path : ie_driver_path64bit); } else { file = new File(driver_path != null && !driver_path.isEmpty() ? driver_path : ie_driver_path32bit); } this.printMessage("##### IE DRIVER PATH=" + file.getAbsolutePath()); System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); DesiredCapabilities capability = DesiredCapabilities.internetExplorer(); capability.setCapability("acceptSslCerts", true); capability.setCapability("platform", Platform.WINDOWS); capability.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true); if (is64bit()) { capability.setCapability("iedriver-version", "x64_2.41.0"); } //capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true); driver = new InternetExplorerDriver(capability); maxTimeToWait = maxTimeToWait * 5; this.isIE = true; } else if (v_driver.equalsIgnoreCase("firefox")) { /*file = new File("firebug-1.8.1.xpi"); FirefoxProfile firefoxProfile = new FirefoxProfile(); firefoxProfile.setPreference("security.mixed_content.block_active_content", false); firefoxProfile.setPreference("security.mixed_content.block_display_content", true); firefoxProfile.setPreference("browser.cache.disk.enable", true); firefoxProfile.addExtension(file); firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup screen driver = new FirefoxDriver(firefoxProfile); */ if (System.getProperty("os.name").toLowerCase().contains("mac")) { DesiredCapabilities capability = DesiredCapabilities.firefox(); capability.setCapability("platform", Platform.ANY); capability.setCapability("binary", "/Application/firefox"); //for linux //capability.setCapability("binary", "/ms/dist/fsf/PROJ/firefox/16.0.0/bin/firefox"); //for linux //capability.setCapability("binary", "C:\\Program Files\\Mozilla Firefox\\msfirefox.exe"); //for windows driver = new FirefoxDriver(capability); } else { // driver = new FirefoxDriver(); } } else if (v_driver.equalsIgnoreCase("safari")) { if (System.getProperty("os.name").toLowerCase().contains("mac")) { this.printMessage("#####STARTING Safri in Mac ####"); DesiredCapabilities capability = DesiredCapabilities.safari(); capability.setCapability("platform", Platform.ANY); capability.setCapability("binary", "/Application/safari"); //for linux driver = new SafariDriver(capability); } else { // Read Instruction for Safari Extension //http://rationaleemotions.wordpress.com/2012/05/25/working-with-safari-driver/ // Get certificate from https://docs.google.com/folder/d/0B5KGduKl6s6-ZGpPZlA0Rm03Nms/edit this.printMessage("#####STARTING Safri in Windows ####"); String safari_install_path = "C:\\Program Files (x86)\\Safari\\"; DesiredCapabilities capability = DesiredCapabilities.safari(); capability.setCapability("platform", Platform.ANY); capability.setCapability("binary", safari_install_path + "Safari.exe"); //for windows //capability.setCapability(SafariDriver.DATA_DIR_CAPABILITY, "C:\\Program Files (x86)\\Safari\\SafariData"); //System.setProperty("webdriver.safari.driver", safari_install_path+"SafariDriver.safariextension\\"); driver = new SafariDriver(capability); } } else if (v_driver.equalsIgnoreCase("htmlunit")) { DesiredCapabilities capability = DesiredCapabilities.htmlUnit(); capability.setJavascriptEnabled(true); //capability.setCapability("browserName","chrome"); //capability.setBrowserName(BrowserVersion.CHROME); driver = new HtmlUnitDriver(capability); } else { file = new File(driver_path != null && !driver_path.isEmpty() ? driver_path : chrome_driver_path); System.setProperty("webdriver.chrome.driver", file.getAbsolutePath()); driver = new ChromeDriver(); } baseUrl = ConfigLoader.getConfig("BASE_APPLICATION_URL"); baseUrl = baseUrl.replace("[env]", ConfigLoader.getConfig("QA_TEST_ENV")); for (Cookie cookie : driver.manage().getCookies()) { printMessage("name=" + cookie.getName()); printMessage("domain=" + cookie.getDomain()); printMessage("path=" + cookie.getPath()); printMessage("value=" + cookie.getValue()); } java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); if (this.varmap.get("browserwidth") != null) { try { browserwidth = new Integer(this.varmap.get("browserwidth")); } catch (Exception e) { browserwidth = 1020; } } driver.manage().window().setSize(new Dimension(browserwidth, (int) screenSize.getHeight())); String removecookie = getDeclaredVariable("removecookie"); if (this.isEmptyValue(removecookie) || removecookie.equalsIgnoreCase("yes")) { driver.manage().deleteAllCookies(); } driver.manage().timeouts().implicitlyWait(maxTimeToWait, TimeUnit.SECONDS); driverList.put(this.threadIndex, driver); this.resetTestResult(); }
From source file:com.zhao.crawler.util.CookieUtil.java
License:Open Source License
/** * csdn??cookies?/*from w ww. j a v a 2s. c o m*/ * * @param username * ?? * @param password * ? * @param geckodriverpath * gecko?https://github.com/mozilla/geckodriver * @param savecookiepath * cookies? * @throws Exception */ public static void firfoxDriverGetCookies(String username, String password, String geckodriverpath, String savecookiepath) throws Exception { // ??? System.setProperty("webdriver.gecko.driver", geckodriverpath); FirefoxDriver driver = new FirefoxDriver(); String baseUrl = "http://kaixin65.com/member.php?mod=logging&action=login&infloat=yes&handlekey=login&inajax=1&ajaxtarget=fwin_content_login"; // url driver.get(baseUrl); // ? driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); // ?? WebElement elemUsername = driver.findElement(By.name("username")); WebElement elemPassword = driver.findElement(By.name("password")); WebElement btn = driver.findElement(By.className("logging")); WebElement rememberMe = driver.findElement(By.id("rememberMe")); // ?? elemUsername.sendKeys(username); elemPassword.sendKeys(password); rememberMe.click(); // ??? btn.submit(); Thread.sleep(5000); driver.get("http://msg.csdn.net/"); Thread.sleep(5000); // ?cookies driver.manage().getCookies(); Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies(); System.out.println("Size: " + cookies.size()); Iterator<org.openqa.selenium.Cookie> itr = cookies.iterator(); CookieStore cookieStore = new BasicCookieStore(); while (itr.hasNext()) { Cookie cookie = itr.next(); BasicClientCookie bcco = new BasicClientCookie(cookie.getName(), cookie.getValue()); bcco.setDomain(cookie.getDomain()); bcco.setPath(cookie.getPath()); cookieStore.addCookie(bcco); } // ? ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(savecookiepath))); oos.writeObject(cookieStore); oos.close(); }
From source file:de.ppi.selenium.assertj.WebbrowserAssert.java
License:Apache License
/** * Check if a cookie with the given name exists. * * @param searchedCookies a list of cookies which should be found. * @return this// w ww. j av a2 s . c o m */ public WebbrowserAssert hasCookies(String... searchedCookies) { final Set<Cookie> cookies = actual.manage().getCookies(); final List<String> cookieNames = new ArrayList<>(); for (Cookie cookie : cookies) { cookieNames.add(cookie.getName()); } // assertThat(cookieNames).contains(searchedCookies); Iterables.instance().assertContains(info, cookieNames, searchedCookies); return this; }
From source file:de.tntinteractive.portalsammler.engine.FileDownloader.java
License:Open Source License
/** * Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state *//*from w w w .j a va 2s .co m*/ private BasicCookieStore mimicCookieState(final Set<Cookie> seleniumCookieSet) { final BasicCookieStore mimicWebDriverCookieStore = new BasicCookieStore(); for (final Cookie seleniumCookie : seleniumCookieSet) { final BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue()); duplicateCookie.setDomain(seleniumCookie.getDomain()); duplicateCookie.setSecure(seleniumCookie.isSecure()); duplicateCookie.setExpiryDate(seleniumCookie.getExpiry()); duplicateCookie.setPath(seleniumCookie.getPath()); mimicWebDriverCookieStore.addCookie(duplicateCookie); } return mimicWebDriverCookieStore; }
From source file:FacebookRequest.Facebook.java
public FacebookAccount login(String u, String p) throws IOException { FacebookAccount myFacebook = new FacebookAccount(); WebDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME, true); driver.get("https://m.facebook.com/"); driver.findElement(By.name("email")).sendKeys(u); driver.findElement(By.name("pass")).sendKeys(p); driver.findElement(By.name("login")).click(); String HTMLSource = driver.getPageSource(); Set<Cookie> cookies = driver.manage().getCookies(); driver.close();//from ww w . j a v a 2 s. co m Document doc = Jsoup.parse(HTMLSource); Elements doc_inputs = doc.select("input[name=fb_dtsg]"); Pattern DTSG_Pattern = Pattern.compile("(\\w{12}\\:\\w{12})"); if (doc_inputs.isEmpty()) return null; String DTSG = doc_inputs.first().attr("value"); if (!DTSG_Pattern.matcher(DTSG).find()) return null; myFacebook.setDTSH(DTSG); String myCookie = ""; for (Cookie cookie : cookies) myCookie = myCookie + cookie.getName() + "=" + cookie.getValue() + "; "; myFacebook.setCookie(myCookie); //System.out.println(myFacebook.getCookie()+"\n"+myFacebook.getDTSH()); return myFacebook; }
From source file:gov.nih.nci.firebird.commons.selenium2.util.FileDownloadUtils.java
License:Open Source License
private static BasicClientCookie translateCookie(Cookie webDriverCookie) { BasicClientCookie clientCookie = new BasicClientCookie(webDriverCookie.getName(), webDriverCookie.getValue()); clientCookie.setDomain(webDriverCookie.getDomain()); clientCookie.setExpiryDate(webDriverCookie.getExpiry()); clientCookie.setPath(webDriverCookie.getPath()); clientCookie.setSecure(webDriverCookie.isSecure()); return clientCookie; }