Best Selenium code snippet using org.openqa.selenium.logging.Interface HasLogEvents
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:EventType.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.logging;18@FunctionalInterface19public interface EventType<X> {20  void consume(X event);21  default void initializeListener(HasLogEvents loggable) {22    // no-op23  }24}...Source:HasLogEvents.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.logging;18public interface HasLogEvents {19  <X> void onLogEvent(EventType<X> kind);20}...Interface HasLogEvents
Using AI Code Generation
1import org.openqa.selenium.logging.LogEntries;2import org.openqa.selenium.logging.LogEntry;3import org.openqa.selenium.logging.LogType;4import org.openqa.selenium.logging.LoggingPreferences;5import org.openqa.selenium.remote.CapabilityType;6import org.openqa.selenium.remote.DesiredCapabilities;7import org.openqa.selenium.remote.RemoteWebDriver;8import java.net.MalformedURLException;9import java.net.URL;10import java.util.logging.Level;11public class LogTest {12    public static void main(String[] args) throws MalformedURLException {13        LoggingPreferences logPrefs = new LoggingPreferences();14        logPrefs.enable(LogType.BROWSER, Level.ALL);15        DesiredCapabilities caps = DesiredCapabilities.chrome();16        caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);17        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);18        for (LogEntry entry : logEntries) {19            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());20        }21        driver.quit();22    }23}Interface HasLogEvents
Using AI Code Generation
1package selenium;2import java.util.List;3import java.util.logging.Level;4import org.openqa.selenium.By;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.chrome.ChromeDriver;8import org.openqa.selenium.logging.LogEntry;9import org.openqa.selenium.logging.LogType;10import org.openqa.selenium.logging.LoggingPreferences;11public class JSConsoleLog {12    public static void main(String[] args) {13        System.setProperty("webdriver.chrome.driver", "/Users/raghavendrav/Downloads/chromedriver");14        WebDriver driver = new ChromeDriver();15        LoggingPreferences logPrefs = new LoggingPreferences();16        logPrefs.enable(LogType.BROWSER, Level.ALL);17        List<LogEntry> log = driver.manage().logs().get(LogType.BROWSER).getAll();18        System.out.println(log.size());19        for(LogEntry l : log)20        {21            System.out.println(l.getMessage());22        }23        List<WebElement> links = driver.findElements(By.cssSelector("li[class='gf-li'] a"));24        System.out.println(links.size());25        for(WebElement link : links)26        {27            System.out.println(link.getText());28        }29    }30}31package selenium;32import java.util.List;33import java.util.logging.Level;34import org.openqa.selenium.By;35import org.openqa.selenium.WebDriver;36import org.openqa.selenium.WebElement;37import org.openqa.selenium.chrome.ChromeDriver;38import org.openqa.selenium.logging.LogEntry;39import org.openqa.selenium.logging.LogType;40import org.openqa.selenium.logging.LoggingPreferences;41public class JSConsoleLog {42    public static void main(String[] args) {43        System.setProperty("webdriver.chrome.driver", "/Users/raghavendrav/Downloads/chromedriver");44        WebDriver driver = new ChromeDriver();45        LoggingPreferences logPrefs = new LoggingPreferences();46        logPrefs.enable(LogType.BROWSER, Level.ALL);Interface HasLogEvents
Using AI Code Generation
1package com.automationrhapsody.selenium.logging;2import org.openqa.selenium.logging.LogEntry;3import org.openqa.selenium.logging.LogType;4import org.openqa.selenium.logging.LoggingPreferences;5import org.openqa.selenium.remote.CapabilityType;6import org.openqa.selenium.remote.DesiredCapabilities;7import org.openqa.selenium.remote.RemoteWebDriver;8import java.io.File;9import java.io.IOException;10import java.net.MalformedURLException;11import java.net.URL;12import java.util.List;13import java.util.logging.Level;14public class LogEventsExample {15    public static void main(String[] args) throws MalformedURLException, InterruptedException, IOException {16        DesiredCapabilities caps = DesiredCapabilities.chrome();17        caps.setCapability(CapabilityType.LOGGING_PREFS, getLoggingPreferences());18        List<LogEntry> logEntries = driver.manage().logs().get(LogType.BROWSER).getAll();19        for (LogEntry entry : logEntries) {20            System.out.println(entry);21        }22        driver.quit();23    }24    private static LoggingPreferences getLoggingPreferences() {25        LoggingPreferences logPrefs = new LoggingPreferences();26        logPrefs.enable(LogType.BROWSER, Level.ALL);27        return logPrefs;28    }29}30package com.automationrhapsody.selenium.logging;31import org.openqa.selenium.logging.LogEntry;32import org.openqa.selenium.logging.LogType;33import org.openqa.selenium.logging.LoggingPreferences;34import org.openqa.selenium.remote.CapabilityType;35import org.openqa.selenium.remote.DesiredCapabilities;36import org.openqa.selenium.remote.RemoteWebDriver;37import java.io.File;38import java.io.IOException;39import java.net.MalformedURLException;40import java.net.URL;41import java.util.List;42import java.util.logging.Level;43public class LogEventsExample {44    public static void main(String[] args) throws MalformedURLException, InterruptedException, IOException {45        DesiredCapabilities caps = DesiredCapabilities.chrome();46        caps.setCapability(CapabilityType.LOGGING_PREFS, getLoggingPreferences());Interface HasLogEvents
Using AI Code Generation
1import org.openqa.selenium.logging.LogType;2import org.openqa.selenium.logging.LogEntry;3import org.openqa.selenium.logging.LogEntries;4import org.openqa.selenium.logging.HasLogEvents;5import java.util.List;6import java.util.logging.Level;7import org.openqa.selenium.logging.LogType;8import org.openqa.selenium.logging.LogEntry;9import org.openqa.selenium.logging.LogEntries;10import org.openqa.selenium.logging.HasLogEvents;11import java.util.List;12import java.util.logging.Level;13import org.openqa.selenium.logging.LogType;14import org.openqa.selenium.logging.LogEntry;15import org.openqa.selenium.logging.LogEntries;16import org.openqa.selenium.logging.HasLogEvents;17import java.util.List;18import java.util.logging.Level;19import org.openqa.selenium.logging.LogType;20import org.openqa.selenium.logging.LogEntry;21import org.openqa.selenium.logging.LogEntries;22import org.openqa.selenium.logging.HasLogEvents;23import java.util.List;24import java.util.logging.Level;25import org.openqa.selenium.logging.LogType;26import org.openqa.selenium.logging.LogEntry;27import org.openqa.selenium.logging.LogEntries;28import org.openqa.selenium.logging.HasLogEvents;29import java.util.List;30import java.util.logging.Level;31import org.openqa.selenium.logging.LogType;32import org.openqa.selenium.logging.LogEntry;33import org.openqa.selenium.logging.LogEntries;34import org.openqa.selenium.logging.HasLogEvents;35import java.util.List;36import java.util.logging.Level;37import org.openqa.selenium.logging.LogType;38import org.openqa.selenium.logging.LogEntry;39import org.openqa.selenium.logging.LogEntries;40import org.openqa.selenium.logging.HasLogEvents;41import java.util.List;42import java.util.logging.Level;43import org.openqa.selenium.logging.LogType;44import org.openqa.selenium.logging.LogEntry;45import org.openqa.selenium.logging.LogEntries;46import org.openqa.selenium.logging.HasLogEvents;47import java.util.List;48import java.util.logging.Level;49import org.openqa.selenium.logging.LogType;50import org.openqa.selenium.logging.LogEntry;51import org.openqa.selenium.logging.LogEntries;52import org.openqa.selenium.logging.HasLogEvents;53import java.util.List;54import java.util.logging.Level;55import orgLambdaTest’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!!
