Best Selenium code snippet using org.openqa.selenium.Interface HasAuthentication
Source:Site.java
1/*2 * To change this license header, choose License Headers in Project Properties.3 * To change this template file, choose Tools | Templates4 * and open the template in the editor.5 */6package sachin.bws.site;7import java.io.File;8import java.io.IOException;9import java.net.MalformedURLException;10import java.util.ArrayList;11import java.util.Collections;12import java.util.HashMap;13import java.util.List;14import java.util.Map;15import java.util.logging.Level;16import java.util.logging.Logger;17import org.apache.commons.codec.binary.Base64;18import org.apache.commons.io.FileUtils;19import org.json.JSONObject;20import org.jsoup.Connection.Response;21import org.jsoup.Jsoup;22import org.jsoup.nodes.Document;23import org.jsoup.nodes.Element;24import org.jsoup.select.Elements;25import org.openqa.selenium.OutputType;26import org.openqa.selenium.TakesScreenshot;27import org.openqa.selenium.WebDriver;28import sachin.bws.feature.Featurable;29import sachin.bws.selenium.WebDriverBuilder;30/**31 *32 * @author sku20233 */34public abstract class Site {35// private Featurable feature;36 protected String url;37 protected String username = "", password = "", urlWithAuth, statusMsg, host, branchModificationTime,startTime,endTime;38 protected String userAgent;39 protected List<String> errors;40 protected boolean authenticate = false, running, crawling;41 protected String brandName = "", culture = "", environment = "";42 protected int statusCode;43 protected String siteHTML;44// List<UrlLink> urlLinks;45 private boolean doCrawling = true;46 protected JSONObject siteJSON, paramJSON;47 protected int viewPortHeight, viewPortWidth;48 protected WebDriver driver;49 protected WebDriverBuilder builder;50 public abstract JSONObject getParamJSON();51 public WebDriverBuilder getWebDriverBuilder() {52 return builder;53 }54 public WebDriver getDriver() {55 return driver;56 }57 public void setWebDriver(WebDriver driver) {58 this.driver = driver;59 }60 public void setWebDriverBuilder(WebDriverBuilder builder) {61 this.builder = builder;62 }63 protected Site(String url) {64 this.errors = new ArrayList<>();65 this.url = url;66 }67 /**68 * to get branch versionof the site69 *70 * @return branch version as string71 * @throws java.lang.Exception72 */73 public String getBranchVersion() {74 if (!this.isRunning()) {75 return "";76 }77 String branchversion = "";78 Response res = null;79 String login = getUsername() + ":" + getPassword();80 String base64login = new String(Base64.encodeBase64(login.getBytes()));81 try {82 try {83 res = this.hasAuthentication() ? Jsoup.connect(URLCanonicalizer.getCanonicalURL(url) + "branchversion.txt").header("Authorization", "Basic " + base64login).followRedirects(true).timeout(180000).execute() : Jsoup.connect(URLCanonicalizer.getCanonicalURL(url) + "branchversion.txt").followRedirects(true).timeout(180000).execute();84 this.branchModificationTime = res.headers().containsKey("Last-Modified") ? res.header("Last-Modified") : "Unable to get information";85 } catch (Exception e) {86 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, e);87 errors.add(e.getMessage());88 }89 if (res == null || res.statusCode() != 200) {90 if (getSiteHTML().contains("brand.css")) {91 branchversion = getSiteHTML().substring(getSiteHTML().toString().indexOf("brand.css?v="), getSiteHTML().toString().indexOf("brand.css?v=") + 15).substring(12);92 }93 } else {94 branchversion = res.parse().text();95 }96 } catch (Exception ex) {97 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);98 errors.add(ex.getMessage());99 }100 return branchversion;101 }102 /**103 * to know if site is MOS or BWS-R or BWS-NR104 *105 * @return branch version as string106 */107 public String getSiteType() {108 try {109 if (!this.isRunning()) {110 return "";111 }112 if (url.contains("m.") || url.contains("m-")) {113 return "MOS site";114 }115 Document doc = Jsoup.parse(getSiteHTML());116 Elements elements = doc.getElementsByTag("meta");117 for (Element e : elements) {118 String name = e.attr("name");119 if (name.equalsIgnoreCase("viewport") && getSiteHTML().contains("<!DOCTYPE html>") && doc.body().hasAttr("data-layout")) {120 return "BWS Responsive Site";121 }122 }123 } catch (Exception ex) {124 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);125 }126 return "BWS non-responsive site";127 }128 /**129 * site config-dev in json format130 *131 * @return json object of config dev132 */133 public JSONObject getConfigAsJSON() {134 File file = HelperClass.getLatestSiteConfigFile(this.getUrl());135 return HelperClass.readJsonFromFile(file.getAbsolutePath());136 }137 public abstract boolean hasAuthentication();138 public abstract String getHost();139 public abstract int getViewPortHeight();140 public abstract int getViewPortWidth();141 public abstract String getUrl();142 public abstract String getUsername();143 public abstract String getUrlWithAuth();144 public abstract String getEnvironment();145 public abstract String getCulture();146 public abstract String getBrandName();147 public abstract String getUserAgent();148 public abstract boolean isCrawling();149 /**150 * to get site running status151 *152 * @return true if site is running153 */154 public boolean isRunning() {155 return running;156 }157 /**158 * to get site information as JSON object it contains159 * <li>BranchVersion</li>160 * <li>BrandName</li>161 * <li>Culture</li>162 * <li>Environment</li>163 * <li>SiteType</li>164 * <li>RunningStatus</li>165 * <li>StatusCode</li>166 * <li>HostName</li>167 * <li>StatusMsg</li>168 * <li>sitePubId</li>169 * <li>Screenshot</li>170 *171 * @return JSON object172 */173 public JSONObject getJsonSiteInfo() {174 Map<String, String> map = new HashMap<String, String>();175 map.put("BranchVersion", this.getBranchVersion());176 map.put("BrandName", this.getBrandName());177 map.put("Culture", this.getCulture());178 map.put("Environment", this.getEnvironment());179 map.put("SiteType", this.getSiteType());180 map.put("SiteUrl", this.getUrl());181 map.put("hostName", this.getHost());182 map.put("RunningStatus", isRunning() == true ? "Running" : "Not Running");183 map.put("StatusCode", Integer.toString(getStatusCode()));184 map.put("StatusMsg", getStatusMsg());185 map.put("buildTime", branchModificationTime);186 map.put("startTime", startTime);187// map.put("endTime", endTime);188 map.put("reportGenerationTime", HelperClass.generateUniqueString());189 try {190 map.put("outputAddress", HelperClass.readJsonFromFile(HelperClass.getDataFolderPath() + File.separator + "config.json").getString("outputAddressWithHostMachine") + this.getHost());191 map.put("sitePubId", HelperClass.readJsonFromFile(HelperClass.getLatestSiteConfigFile(this.getUrl()).getAbsolutePath()).getString("sitePubId"));192 map.put("Screenshot", HelperClass.getRelativePathToWebApp(takeScreenshoot(this.getUrl())));193 } catch (Exception ex) {194 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);195 errors.add(ex.getMessage());196 }197 return new JSONObject(map);198 }199 /**200 * method to take screenshot of a url and save it on local storage201 *202 * @param url url of the page to be captured203 * @return path of the saved pic204 */205 public String takeScreenshoot(String url) {206 String location = null;207 File saveTo = null;208 try {209 location = HelperClass.getScreenshotRepository(this.getHost());210 WebDriver driver = this.getDriver();211// driver.manage().window().maximize();212 driver.navigate().to(url);213 File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);214 saveTo = new File(location, HelperClass.generateUniqueName());215 FileUtils.copyFile(scrFile, saveTo);216 return saveTo.getAbsolutePath();217 } catch (MalformedURLException ex) {218 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);219 } catch (IOException ex) {220 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);221 }222 return "";223 }224 /**225 * method to take screenshot of a page and save it on local storage226 *227 * @param driver WebDriver object to take screen shot228 * @return path of the saved pic229 */230 public String takeScreenshoot(WebDriver driver) {231 String location = null;232 File saveTo = null;233 try {234 location = HelperClass.getScreenshotRepository(this.getHost());235 File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);236 saveTo = new File(location, HelperClass.generateUniqueName());237 FileUtils.copyFile(scrFile, saveTo);238 return saveTo.getAbsolutePath();239 } catch (MalformedURLException ex) {240 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);241 } catch (IOException ex) {242 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);243 }244 return "";245 }246 /**247 * method to get status message of the site response248 *249 * @return status message of site as string250 */251 public abstract String getStatusMsg();252 /**253 * method to get status code of the site response254 *255 * @return status code of site as integer256 */257 public abstract int getStatusCode();258 /**259 * method to get all links of the site after crawling260 *261 * @return List of UrlLink of the site262 */263 public List<UrlLink> getAllCrawledLinks() {264 List<UrlLink> list = null;265 if (!(new File(HelperClass.getCrawledDataRepository(this.getHost()), HelperClass.getCrawledDataFilename(this.getHost())).exists())) {266 crawling = true;267 }268 if (isCrawling() && doCrawling) {269 if (!this.isRunning()) {270 return Collections.synchronizedList(new ArrayList<>());271 }272 list = new Crawling(this).getUrlLinks();273 HelperClass.saveCrawlingData(list, this.getHost());274 doCrawling = false;275 } else {276 list = HelperClass.readCrawlingData(this.getHost());277 }278 return list;279 }280 /**281 * method to get all links of the site after crawling which gives 200 as282 * status code283 *284 * @return List of UrlLink of the site which gives 200 as status code285 */286 public List<UrlLink> getCrawledLinks() {287 List<UrlLink> urlLinks = new ArrayList<UrlLink>();288 List<UrlLink> list = getAllCrawledLinks();289 for (UrlLink link : list) {290 if (link.getStatusCode() == 200) {291 urlLinks.add(link);292 }293 }294 return urlLinks;295 }296 /**297 * method to get all links of the site after crawling from a saved location298 *299 * @return List of UrlLink of the site300 */301 public List<UrlLink> getSavedCrawledLinksFromFile() {302 return HelperClass.readCrawlingData(HelperClass.getCrawledDataFilename(this.getHost()));303 }304 /**305 * method to get all product detail pages links of the site306 *307 * @return List of UrlLink of the site308 */309 public List<UrlLink> getProductDetailPages() {310 List<UrlLink> urlLinks = getCrawledLinks();311 List<UrlLink> links = new ArrayList<UrlLink>();312 for (UrlLink link : urlLinks) {313 if (link.getTemplateName().toLowerCase().contains("productdetail")) {314 links.add(link);315 }316 }317 return links;318 }319 /**320 * method to get all product pages links of the site321 *322 * @return List of UrlLink of the site323 */324 public List<UrlLink> getProductPages() {325 List<UrlLink> urlLinks = getCrawledLinks();326 List<UrlLink> links = new ArrayList<UrlLink>();327 for (UrlLink link : urlLinks) {328 if (link.getTemplateName().toLowerCase().contains("product")) {329 links.add(link);330 }331 }332 return links;333 }334 /**335 * method to get all article detail pages links of the site336 *337 * @return List of UrlLink of the site338 */339 public List<UrlLink> getArticlePages() {340 List<UrlLink> urlLinks = getCrawledLinks();341 List<UrlLink> links = new ArrayList<UrlLink>();342 for (UrlLink link : urlLinks) {343 if (link.getTemplateName().toLowerCase().contains("article")) {344 links.add(link);345 }346 }347 return links;348 }349 /**350 * method to get all recipe detail pages links of the site351 *352 * @return List of UrlLink of the site353 */354 public List<UrlLink> getRecipePages() {355 List<UrlLink> urlLinks = getCrawledLinks();356 List<UrlLink> links = new ArrayList<UrlLink>();357 for (UrlLink link : urlLinks) {358 if (link.getTemplateName().toLowerCase().contains("recipe")) {359 links.add(link);360 }361 }362 return links;363 }364 /**365 * method to get all misc pages links of the site366 *367 * @return List of UrlLink of the site368 */369 public List<UrlLink> getMiscPages() {370 List<UrlLink> urlLinks = getCrawledLinks();371 List<UrlLink> links = new ArrayList<UrlLink>();372 for (UrlLink link : urlLinks) {373 if (!link.getTemplateName().toLowerCase().contains("product") && !link.getTemplateName().toLowerCase().contains("article") && !link.getTemplateName().toLowerCase().contains("recipe")) {374 links.add(link);375 }376 }377 return links;378 }379 /**380 * method to get all misc pages with their template name of the site381 *382 * @return JSON Object383 */384 public JSONObject getMiscTemplates() {385 Map<String, String> map = new HashMap<String, String>();386 List<UrlLink> links = getMiscPages();387 for (UrlLink link : links) {388 if (map.containsKey(link.getTemplateName())) {389 String urls = map.get(link.getTemplateName()) + "," + link.getUrl();390 map.put(link.getTemplateName(), urls);391 } else {392 map.put(link.getTemplateName(), link.getUrl());393 }394 }395 return new JSONObject(map);396 }397 /**398 * method to get all recipe pages with their template name of the site399 *400 * @return JSON Object401 */402 public JSONObject getRecipeTemplates() {403 Map<String, String> map = new HashMap<String, String>();404 List<UrlLink> links = getRecipePages();405 for (UrlLink link : links) {406 if (map.containsKey(link.getTemplateName())) {407 String urls = map.get(link.getTemplateName()) + "," + link.getUrl();408 map.put(link.getTemplateName(), urls);409 } else {410 map.put(link.getTemplateName(), link.getUrl());411 }412 }413 return new JSONObject(map);414 }415 /**416 * method to get all product pages with their template name of the site417 *418 * @return JSON Object419 */420 public JSONObject getProductTemplates() {421 Map<String, String> map = new HashMap<String, String>();422 List<UrlLink> links = getProductPages();423 for (UrlLink link : links) {424 if (map.containsKey(link.getTemplateName())) {425 String urls = map.get(link.getTemplateName()).concat("," + link.getUrl());426 map.put(link.getTemplateName(), urls);427 } else {428 map.put(link.getTemplateName(), link.getUrl());429 }430 }431 return new JSONObject(map);432 }433 /**434 * method to get all pages with their template name of the site435 *436 * @return JSON Object437 */438 public JSONObject getAllTemplates() {439 List<UrlLink> urlLinks = getCrawledLinks();440 Map<String, String> map = new HashMap<String, String>();441 for (UrlLink link : urlLinks) {442 if (map.containsKey(link.getTemplateName())) {443 String urls = map.get(link.getTemplateName()) + "," + link.getUrl();444 map.put(link.getTemplateName(), urls);445 } else {446 map.put(link.getTemplateName(), link.getUrl());447 }448 }449 return new JSONObject(map);450 }451 /**452 * method to get all article pages with their template name of the site453 *454 * @return JSON Object455 */456 public JSONObject getArticleTemplates() {457 Map<String, String> map = new HashMap<String, String>();458 List<UrlLink> links = getArticlePages();459 for (UrlLink link : links) {460 if (map.containsKey(link.getTemplateName())) {461 String urls = map.get(link.getTemplateName()) + "," + link.getUrl();462 map.put(link.getTemplateName(), urls);463 } else {464 map.put(link.getTemplateName(), link.getUrl());465 }466 }467 return new JSONObject(map);468 }469 /**470 * method to get all article detail pages.471 *472 * @return List of UrlLink of the site473 */474 public List<UrlLink> getArticleDetailPages() {475 List<UrlLink> urlLinks = getCrawledLinks();476 List<UrlLink> links = new ArrayList<UrlLink>();477 for (UrlLink link : urlLinks) {478 if (link.getTemplateName().toLowerCase().contains("articledetail")) {479 links.add(link);480 }481 }482 return links;483 }484 /**485 * method to get all Recipe detail pages.486 *487 * @return List of UrlLink of the site488 */489 public List<UrlLink> getRecipeDetailPages() {490 List<UrlLink> urlLinks = getCrawledLinks();491 List<UrlLink> links = new ArrayList<UrlLink>();492 for (UrlLink link : urlLinks) {493 if (link.getTemplateName().toLowerCase().contains("recipedetail") || link.getTemplateName().toLowerCase().contains("recipe-detail")) {494 links.add(link);495 }496 }497 return links;498 }499 /**500 * method to get all article category pages.501 *502 * @return List of UrlLink of the site503 */504 public List<UrlLink> getArticleCategoryPages() {505 List<UrlLink> urlLinks = getCrawledLinks();506 List<UrlLink> links = new ArrayList<UrlLink>();507 for (UrlLink link : urlLinks) {508 if (link.getTemplateName().toLowerCase().contains("articlecategory")) {509 links.add(link);510 }511 }512 return links;513 }514 /**515 * method to get all product category pages.516 *517 * @return List of UrlLink of the site518 */519 public List<UrlLink> getProductCategoryPages() {520 List<UrlLink> urlLinks = getCrawledLinks();521 List<UrlLink> links = new ArrayList<UrlLink>();522 for (UrlLink link : urlLinks) {523 if (link.getTemplateName().toLowerCase().contains("productcategory")) {524 links.add(link);525 }526 }527 return links;528 }529 /**530 * site pages with their template names.531 *532 * @return json object533 */534 public JSONObject getOutputWithTemplates() {535 Map<String, JSONObject> map = new HashMap<String, JSONObject>();536 map.put("siteInfo", getJsonSiteInfo());537 try {538 map.put("product", getProductTemplates());539 map.put("article", getArticleTemplates());540 map.put("recipe", getRecipeTemplates());541 map.put("misc", getMiscTemplates());542 } catch (Exception ex) {543 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);544 }545 JSONObject json = new JSONObject(map);546 HelperClass.writeJSONoutputWithTemplateToFile(json, this.getHost());547 return json;548 }549 /**550 *551 *552 * @return if true, site is responsive site553 */554 public boolean isResponsive() {555 return this.getSiteType().equalsIgnoreCase("BWS Responsive Site");556 }557 /**558 *559 *560 * @return if true, site is MOS site561 */562 public boolean isMOS() {563 return this.getSiteType().equalsIgnoreCase("MOS site");564 }565 /**566 *567 *568 * @return if true, site is non-responsive site569 */570 public boolean isNonResponsive() {571 return this.getSiteType().equalsIgnoreCase("BWS non-responsive site");572 }573 /**574 * method to test functionality on site575 *576 * @param functionality object of the functionality class which implements577 * Featurable interface578 * @return JSON Object of all the Functionality information579 */580 public JSONObject testFeature(Featurable functionality) {581 JSONObject json = new JSONObject();582 if (!this.isRunning()) {583 return json;584 }585 try {586 System.out.println(functionality.getClass().getSimpleName());587 json = functionality.getJsonResult();588 } catch (Exception ex) {589 Logger.getLogger(Site.class.getName()).log(Level.SEVERE, null, ex);590 }591 return json;592 }593 /**594 * method to test functionality on site595 *596 * @return HTML of site source597 */598 public abstract String getSiteHTML();599 /**600 * method to test functionality on site601 *602 * @return List of error messages603 */604 public abstract List<String> getErrors();605 public abstract JSONObject getSiteJSON();606 public abstract String getPassword();607}...
Source:ChromiumDriver.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.chromium;18import com.google.common.collect.ImmutableMap;19import org.openqa.selenium.BuildInfo;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.Credentials;22import org.openqa.selenium.HasAuthentication;23import org.openqa.selenium.WebDriver;24import org.openqa.selenium.WebDriverException;25import org.openqa.selenium.devtools.CdpInfo;26import org.openqa.selenium.devtools.CdpVersionFinder;27import org.openqa.selenium.devtools.Connection;28import org.openqa.selenium.devtools.DevTools;29import org.openqa.selenium.devtools.HasDevTools;30import org.openqa.selenium.devtools.noop.NoOpCdpInfo;31import org.openqa.selenium.html5.LocalStorage;32import org.openqa.selenium.html5.Location;33import org.openqa.selenium.html5.LocationContext;34import org.openqa.selenium.html5.SessionStorage;35import org.openqa.selenium.html5.WebStorage;36import org.openqa.selenium.interactions.HasTouchScreen;37import org.openqa.selenium.interactions.TouchScreen;38import org.openqa.selenium.internal.Require;39import org.openqa.selenium.logging.EventType;40import org.openqa.selenium.logging.HasLogEvents;41import org.openqa.selenium.mobile.NetworkConnection;42import org.openqa.selenium.remote.CommandExecutor;43import org.openqa.selenium.remote.FileDetector;44import org.openqa.selenium.remote.RemoteTouchScreen;45import org.openqa.selenium.remote.RemoteWebDriver;46import org.openqa.selenium.remote.html5.RemoteLocationContext;47import org.openqa.selenium.remote.html5.RemoteWebStorage;48import org.openqa.selenium.remote.http.HttpClient;49import org.openqa.selenium.remote.mobile.RemoteNetworkConnection;50import java.net.URI;51import java.util.Map;52import java.util.Optional;53import java.util.function.Predicate;54import java.util.function.Supplier;55import java.util.logging.Logger;56/**57 * A {@link WebDriver} implementation that controls a Chromium browser running on the local machine.58 * This class is provided as a convenience for easily testing the Chromium browser. The control server59 * which each instance communicates with will live and die with the instance.60 * <p>61 * To avoid unnecessarily restarting the ChromiumDriver server with each instance, use a62 * {@link RemoteWebDriver} coupled with the desired WebDriverService, which is managed63 * separately.64 * <p>65 * Note that unlike ChromiumDriver, RemoteWebDriver doesn't directly implement66 * role interfaces such as {@link LocationContext} and {@link WebStorage}.67 * Therefore, to access that functionality, it needs to be68 * {@link org.openqa.selenium.remote.Augmenter augmented} and then cast69 * to the appropriate interface.70 */71public class ChromiumDriver extends RemoteWebDriver implements72 HasAuthentication,73 HasDevTools,74 HasLogEvents,75 HasTouchScreen,76 LocationContext,77 NetworkConnection,78 WebStorage {79 private static final Logger LOG = Logger.getLogger(ChromiumDriver.class.getName());80 private final RemoteLocationContext locationContext;81 private final RemoteWebStorage webStorage;82 private final TouchScreen touchScreen;83 private final RemoteNetworkConnection networkConnection;84 private final Optional<Connection> connection;85 private final Optional<DevTools> devTools;86 protected ChromiumDriver(CommandExecutor commandExecutor, Capabilities capabilities, String capabilityKey) {87 super(commandExecutor, capabilities);88 locationContext = new RemoteLocationContext(getExecuteMethod());89 webStorage = new RemoteWebStorage(getExecuteMethod());90 touchScreen = new RemoteTouchScreen(getExecuteMethod());91 networkConnection = new RemoteNetworkConnection(getExecuteMethod());92 HttpClient.Factory factory = HttpClient.Factory.createDefault();93 connection = ChromiumDevToolsLocator.getChromeConnector(94 factory,95 getCapabilities(),96 capabilityKey);97 CdpInfo cdpInfo = new CdpVersionFinder().match(getCapabilities().getBrowserVersion())98 .orElseGet(() -> {99 LOG.warning(100 String.format(101 "Unable to find version of CDP to use for %s. You may need to " +102 "include a dependency on a specific version of the CDP using " +103 "something similar to " +104 "`org.seleniumhq.selenium:selenium-devtools-v86:%s` where the " +105 "version (\"v86\") matches the version of the chromium-based browser " +106 "you're using and the version number of the artifact is the same " +107 "as Selenium's.",108 capabilities.getBrowserVersion(),109 new BuildInfo().getReleaseLabel()));110 return new NoOpCdpInfo();111 });112 devTools = connection.map(conn -> new DevTools(cdpInfo::getDomains, conn));113 }114 @Override115 public void setFileDetector(FileDetector detector) {116 throw new WebDriverException(117 "Setting the file detector only works on remote webdriver instances obtained " +118 "via RemoteWebDriver");119 }120 @Override121 public <X> void onLogEvent(EventType<X> kind) {122 Require.nonNull("Event type", kind);123 kind.initializeListener(this);124 }125 @Override126 public void register(Predicate<URI> whenThisMatches, Supplier<Credentials> useTheseCredentials) {127 Require.nonNull("Check to use to see how we should authenticate", whenThisMatches);128 Require.nonNull("Credentials to use when authenticating", useTheseCredentials);129 getDevTools().createSessionIfThereIsNotOne();130 getDevTools().getDomains().network().addAuthHandler(whenThisMatches, useTheseCredentials);131 }132 @Override133 public LocalStorage getLocalStorage() {134 return webStorage.getLocalStorage();135 }136 @Override137 public SessionStorage getSessionStorage() {138 return webStorage.getSessionStorage();139 }140 @Override141 public Location location() {142 return locationContext.location();143 }144 @Override145 public void setLocation(Location location) {146 locationContext.setLocation(location);147 }148 @Override149 public TouchScreen getTouch() {150 return touchScreen;151 }152 @Override153 public ConnectionType getNetworkConnection() {154 return networkConnection.getNetworkConnection();155 }156 @Override157 public ConnectionType setNetworkConnection(ConnectionType type) {158 return networkConnection.setNetworkConnection(type);159 }160 /**161 * Launches Chrome app specified by id.162 *163 * @param id Chrome app id.164 */165 public void launchApp(String id) {166 execute(ChromiumDriverCommand.LAUNCH_APP, ImmutableMap.of("id", id));167 }168 /**169 * Execute a Chrome Devtools Protocol command and get returned result. The170 * command and command args should follow171 * <a href="https://chromedevtools.github.io/devtools-protocol/">chrome172 * devtools protocol domains/commands</a>.173 */174 public Map<String, Object> executeCdpCommand(String commandName, Map<String, Object> parameters) {175 Require.nonNull("Command name", commandName);176 Require.nonNull("Parameters", parameters);177 @SuppressWarnings("unchecked")178 Map<String, Object> toReturn = (Map<String, Object>) getExecuteMethod().execute(179 ChromiumDriverCommand.EXECUTE_CDP_COMMAND,180 ImmutableMap.of("cmd", commandName, "params", parameters));181 return ImmutableMap.copyOf(toReturn);182 }183 @Override184 public DevTools getDevTools() {185 return devTools.orElseThrow(() -> new WebDriverException("Unable to create DevTools connection"));186 }187 public String getCastSinks() {188 Object response = getExecuteMethod().execute(ChromiumDriverCommand.GET_CAST_SINKS, null);189 return response.toString();190 }191 public String getCastIssueMessage() {192 Object response = getExecuteMethod().execute(ChromiumDriverCommand.GET_CAST_ISSUE_MESSAGE, null);193 return response.toString();194 }195 public void selectCastSink(String deviceName) {196 getExecuteMethod().execute(ChromiumDriverCommand.SET_CAST_SINK_TO_USE, ImmutableMap.of("sinkName", deviceName));197 }198 public void startTabMirroring(String deviceName) {199 getExecuteMethod().execute(ChromiumDriverCommand.START_CAST_TAB_MIRRORING, ImmutableMap.of("sinkName", deviceName));200 }201 public void stopCasting(String deviceName) {202 getExecuteMethod().execute(ChromiumDriverCommand.STOP_CASTING, ImmutableMap.of("sinkName", deviceName));203 }204 public void setPermission(String name, String value) {205 getExecuteMethod().execute(ChromiumDriverCommand.SET_PERMISSION,206 ImmutableMap.of("descriptor", ImmutableMap.of("name", name), "state", value));207 }208 @Override209 public void quit() {210 connection.ifPresent(Connection::close);211 super.quit();212 }213}...
Source:HasAuthentication.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium;18import org.openqa.selenium.internal.Require;19import java.net.URI;20import java.util.function.Predicate;21import java.util.function.Supplier;22/**23 * Indicates that a driver supports authenticating to a website in some way.24 *25 * @see Credentials26 * @see UsernameAndPassword27 */28public interface HasAuthentication {29 /**30 * Registers a check for whether a set of {@link Credentials} should be31 * used for a particular site, identified by its URI. If called multiple32 * times, the credentials will be checked in the order they've been added33 * and the first one to match will be used.34 */35 void register(Predicate<URI> whenThisMatches, Supplier<Credentials> useTheseCredentials);36 /**37 * As {@link #register(Predicate, Supplier)} but attempts to apply the38 * credentials for any request for authorization.39 */40 default void register(Supplier<Credentials> alwaysUseTheseCredentials) {41 Require.nonNull("Credentials", alwaysUseTheseCredentials);42 register(uri -> true, alwaysUseTheseCredentials);43 }44}...
Interface HasAuthentication
Using AI Code Generation
1import org.openqa.selenium.HasAuthentication;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.chrome.ChromeOptions;5public class AuthenticationTest {6 public static void main(String[] args) {7 ChromeOptions options = new ChromeOptions();8 WebDriver driver = new ChromeDriver(options);9 ((HasAuthentication) driver).setAuthenticationCredentials("username", "password");10 ((HasAuthentication) driver).getAuthentication();11 }12}
Interface HasAuthentication
Using AI Code Generation
1package com.selenium;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4public class ChromeBrowser {5public static void main(String[] args) {6System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");7WebDriver driver = new ChromeDriver();8driver.manage().window().maximize();9String title = driver.getTitle();10System.out.println(title);11if(title.equals("Google"))12{13System.out.println("correct title");14}15{16System.out.println("in-correct title");17}18String url = driver.getCurrentUrl();19System.out.println(url);20if(url.contains("google"))21{22System.out.println("correct url");23}24{25System.out.println("in-correct url");26}27String pageSource = driver.getPageSource();28System.out.println(pageSource);29driver.close();30}31}
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!!