How to use toJson method of org.openqa.selenium.MutableCapabilities class

Best Selenium code snippet using org.openqa.selenium.MutableCapabilities.toJson

Source:HookGSpec.java Github

copy

Full Screen

...249 if (isLocal) {250 /**251 * Execute the tests using a local browser252 */253 this.getCommonSpec().getLogger().debug("Setting local driver with capabilities {}", mutableCapabilities.toJson().toString());254 commonspec.setDriver(driver);255 } else {256 /**257 * The user can provide the variables "platform", "version" and "platformName" in case the default capabilities need to be changed258 */259 if (System.getProperty("platform") != null) {260 mutableCapabilities.setCapability("platform", System.getProperty("platform"));261 }262 if (System.getProperty("version") != null) {263 mutableCapabilities.setCapability("version", System.getProperty("version"));264 }265 /*266 If the user includes the VM argument -DCAPABILITIES=/path/to/capabilities.json, the capabilities267 from that file will be used instead of the default ones268 */269 if (System.getProperty("CAPABILITIES") != null) {270 this.commonspec.getLogger().debug("Using capabilities from file: " + System.getProperty("CAPABILITIES"));271 mutableCapabilities = new MutableCapabilities();272 this.addCapabilitiesFromFile(System.getProperty("CAPABILITIES"), mutableCapabilities);273 }274 this.getCommonSpec().getLogger().debug("Setting RemoteWebDriver with capabilities {}", mutableCapabilities.toJson().toString());275 commonspec.setDriver(new RemoteWebDriver(new URL(System.getProperty("SELENIUM_GRID")), mutableCapabilities));276 }277 commonspec.getDriver().manage().timeouts().pageLoadTimeout(PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);278 commonspec.getDriver().manage().timeouts().implicitlyWait(IMPLICITLY_WAIT, TimeUnit.SECONDS);279 commonspec.getDriver().manage().timeouts().setScriptTimeout(SCRIPT_TIMEOUT, TimeUnit.SECONDS);280 }281 /**282 * If the feature has the @mobile annotation, creates a new Appium driver283 * before each scenario. By default, the system will try to create a set of default284 * capabilities for the driver. However, the user can set any of the285 * <a href="https://appium.io/docs/en/writing-running-appium/caps/">general capabilities</a> of Appium286 * (i.e. -Dapp=/path/to/app, -DplatformName=android, etc).287 *288 * The user can use the VM argument -DCAPABILITIES=/path/to/capabilities.json, to289 * override the default capabilities with the ones from the json file290 *291 * @param scenario Scenario292 * @throws MalformedURLException MalformedURLException293 */294 @Before(order = 20, value = "@mobile")295 public void AppiumSetup(Scenario scenario) throws IOException {296 if (scenario.getStatus().name().toLowerCase().matches("skipped")) {297 throw new SkipException("@mobile tag ignored since scenario was skipped");298 }299 ObjectMapper mapper = new ObjectMapper();300 MutableCapabilities capabilities = new DesiredCapabilities();301 String grid = System.getProperty("SELENIUM_GRID");302 String b = ThreadProperty.get("browser");303 if (grid == null) {304 grid = "http://127.0.0.1:4723/wd/hub";305 this.getCommonSpec().getLogger().warn("Appium server not specified!");306 this.getCommonSpec().getLogger().warn("Use VM argument -DSELENIUN_GRID=<url> to set the appium server. Using SELENIUN_GRID=" + grid);307 }308 /**309 * These Capabilities span multiple drivers.310 * If you need to pass more or more specific capabilities, use -DCAPABILITIES=/path/to/capabilities.json311 */312 String[] generalCaps = {"automationName", "platformName", "platformVersion", "deviceName", "app", "otherApps", "browserName", "newCommandTimeout", "language",313 "locale", "udid", "orientation", "autoWebview", "noReset", "fullReset", "eventTimings", "enablePerformanceLogging", "printPageSourceOnFindFailure", "clearSystemFiles"};314 for (String cap : generalCaps) {315 if (System.getProperty(cap) != null) {316 capabilities.setCapability(cap, System.getProperty(cap));317 }318 }319 if (capabilities.getCapability("platformName") == null) {320 commonspec.getLogger().warn("No platformName capability found, using Android......");321 capabilities.setCapability("platformName", "Android");322 }323 this.getCommonSpec().getLogger().debug("Setting MobileWebDriver with capabilities {}", capabilities.toJson().toString());324 switch (capabilities.getCapability("platformName").toString().toLowerCase()) {325 case "android":326 if (System.getProperty("automationName") != null) {327 capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, System.getProperty("automationName"));328 } else {329 commonspec.getLogger().warn("Using default automationName=UiAutomator2 for Android. Change this by using -DautomationName='<name>'");330 capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");331 }332 if (System.getProperty("deviceName") != null) {333 capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, System.getProperty("deviceName"));334 }335 /*336 If the user includes the VM argument -DCAPABILITIES=/path/to/capabilities.json, the capabilities337 from that file will be used instead of the default ones338 */339 if (System.getProperty("CAPABILITIES") != null) {340 this.commonspec.getLogger().debug("Using capabilities from file: " + System.getProperty("CAPABILITIES"));341 capabilities = new MutableCapabilities();342 this.addCapabilitiesFromFile(System.getProperty("CAPABILITIES"), capabilities);343 }344 commonspec.getLogger().debug("Building AndroidDriver with capabilities {}", capabilities.toJson().toString());345 commonspec.setDriver(new AndroidDriver(new URL(grid), capabilities));346 break;347 case "ios":348 if (System.getProperty("automationName") != null) {349 capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, System.getProperty("automationName"));350 } else {351 commonspec.getLogger().warn("Using default automationName=XCUITest for ios. Change this by using -DautomationName='<name>'");352 capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");353 }354 if (System.getProperty("deviceName") != null) {355 capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, System.getProperty("deviceName"));356 } else {357 commonspec.getLogger().warn("deviceName capability is required for ios!! trying to use deviceName='My iphone'. Change this by using -DdeviceName='<name>'");358 capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "My iphone");359 }360 /*361 If the user includes the VM argument -DCAPABILITIES=/path/to/capabilities.json, the capabilities362 from that file will be used instead of the default ones363 */364 if (System.getProperty("CAPABILITIES") != null) {365 this.commonspec.getLogger().debug("Using capabilities from file: " + System.getProperty("CAPABILITIES"));366 capabilities = new MutableCapabilities();367 this.addCapabilitiesFromFile(System.getProperty("CAPABILITIES"), capabilities);368 }369 commonspec.getLogger().debug("Building IOSDriver with capabilities {}", capabilities.toJson().toString());370 commonspec.setDriver(new IOSDriver(new URL(grid), capabilities));371 break;372 default:373 commonspec.getLogger().error("Unknown platformName: {}, only android/ios is allowed", capabilities.getCapability("platformName").toString());374 throw new WebDriverException("Unknown platformName: " + capabilities.getCapability("platformName").toString() + ", only android/ios is allowed");375 }376 }377 public void addCapabilitiesFromFile(String filePath, MutableCapabilities capabilities) throws IOException {378 Map<String, Object> capsMap;379 ObjectMapper mapper = new ObjectMapper();380 capsMap = mapper.readValue(Files.readAllBytes(Paths.get(filePath)), Map.class);381 for (Map.Entry<String, Object> entry : capsMap.entrySet()) {382 capabilities.setCapability(entry.getKey(), entry.getValue());383 }...

Full Screen

Full Screen

Source:GridStarter.java Github

copy

Full Screen

...412 launchConfig.setArgs(argsWithServlet);413 414 newConfFile = Paths.get(Utils.getRootdir(), "generatedHubConf.json").toFile();415 try {416 FileUtils.writeStringToFile(newConfFile, new Json().toJson(hubConfiguration.toJson()), StandardCharsets.UTF_8);417 } catch (IOException e) {418 throw new GridException("Cannot generate hub configuration file ", e);419 } 420 421 } else {422 try {423 GridNodeConfiguration nodeConf = new GridNodeConfiguration();424 nodeConf.capabilities = new ArrayList<>();425 426 nodeConf.proxy = "com.infotel.seleniumrobot.grid.CustomRemoteProxy";427 nodeConf.servlets = Arrays.asList(NODE_SERVLETS);428 nodeConf.nodeStatusCheckTimeout = 15; // wait only 15 secs429 nodeConf.enablePlatformVerification = false;430431 nodeConf.timeout = 540; // when test crash or is stopped, avoid blocking session. Keep it above socket timeout of HttpClient (6 mins for mobile)432 433 addMobileDevicesToConfiguration(nodeConf);434 addDesktopBrowsersToConfiguration(nodeConf);435 addBrowsersFromArguments(nodeConf);436 437 newConfFile = Paths.get(Utils.getRootdir(), "generatedNodeConf.json").toFile();438 439 FileUtils.writeStringToFile(newConfFile, new Json().toJson(nodeConf.toJson()), StandardCharsets.UTF_8);440 launchConfig.setConfigPath(newConfFile.getPath());441442 } catch (IOException e) {443 throw new GridException("Cannot generate node configuration file ", e);444 }445 }446 447 // rewrite args with new configuration448 List<String> newArgs = new CommandLineOptionHelper(launchConfig.getArgList()).removeAll("-browser");449450 newArgs.add(launchConfig.getHubRole() ? LaunchConfig.HUB_CONFIG : LaunchConfig.NODE_CONFIG);451 newArgs.add(newConfFile.getAbsolutePath());452 launchConfig.setArgs(newArgs);453 } ...

Full Screen

Full Screen

Source:RegistrationRequestTest.java Github

copy

Full Screen

...56 for (int i = 0; i < 5; i++) {57 DesiredCapabilities cap = new DesiredCapabilities(BrowserType.FIREFOX, String.valueOf(i), Platform.LINUX);58 req.getConfiguration().capabilities.add(cap);59 }60 String json = new Json().toJson(req.toJson());61 RegistrationRequest req2 = RegistrationRequest.fromJson(new Json().toType(json, MAP_TYPE));62 assertEquals(req.getName(), req2.getName());63 assertEquals(req.getDescription(), req2.getDescription());64 assertEquals(req.getConfiguration().role, req2.getConfiguration().role);65 assertEquals(req.getConfiguration().capabilities.size(),66 req2.getConfiguration().capabilities.size());67 assertEquals(req.getConfiguration().capabilities.get(0).getBrowserName(),68 req2.getConfiguration().capabilities.get(0).getBrowserName());69 assertEquals(req.getConfiguration().capabilities.get(0).getPlatform(),70 req2.getConfiguration().capabilities.get(0).getPlatform());71 }72 @Test73 public void basicCommandLineParam() {74 GridNodeConfiguration config = parseCliOptions(...

Full Screen

Full Screen

Source:SeleniumConfig.java Github

copy

Full Screen

...237 if (filePath.toFile().createNewFile()) {238 hubConfig.servlets = Arrays.asList(servlets.toArray(new String[0]));239 try(OutputStream fos = new FileOutputStream(filePath.toFile());240 OutputStream out = new BufferedOutputStream(fos)) {241 out.write(new Json().toJson(hubConfig).getBytes(StandardCharsets.UTF_8));242 }243 }244 return filePath;245 }246 247 /**248 * {@inheritDoc}249 */250 @Override251 public Path createNodeConfig(String capabilities, URL hubUrl) throws IOException {252 // get path to node configuration template253 String nodeConfigPath = getNodeConfigPath().toString();254 // create node configuration from template255 GridNodeConfiguration nodeConfig = GridNodeConfiguration.loadFromJSON(nodeConfigPath);256 257 // convert capabilities string to [JsonInput] object258 JsonInput input = new Json().newInput(new StringReader(JSON_HEAD + capabilities + JSON_TAIL));259 // convert [JsonInput] object to list of [MutableCapabilities] objects260 List<MutableCapabilities> capabilitiesList = GridNodeConfiguration.loadFromJSON(input).capabilities;261 // for each [MutableCapabilities] object262 for (MutableCapabilities theseCaps : capabilitiesList) {263 // apply specified node modifications (if any)264 theseCaps.merge(getModifications(theseCaps, NODE_MODS_SUFFIX));265 }266 267 // get configured node servlet collection268 Set<String> servlets = getNodeServlets();269 // merge with node template servlets270 servlets.addAll(nodeConfig.servlets);271 272 // strip extension to get template base path273 String configPathBase = nodeConfigPath.substring(0, nodeConfigPath.length() - 5);274 // get hash code of capabilities list, hub URL, and servlets as 8-digit hexadecimal string275 String hashCode = String.format("%08X", Objects.hash(capabilitiesList, hubUrl, servlets));276 // assemble node configuration file path with aggregated hash code277 Path filePath = Paths.get(configPathBase + "-" + hashCode + ".json");278 279 // if assembled path does not exist280 if (filePath.toFile().createNewFile()) {281 nodeConfig.hub = null;282 nodeConfig.capabilities = capabilitiesList;283 nodeConfig.hubHost = hubUrl.getHost();284 nodeConfig.hubPort = hubUrl.getPort();285 nodeConfig.servlets = Arrays.asList(servlets.toArray(new String[0]));286 try(OutputStream fos = new FileOutputStream(filePath.toFile());287 OutputStream out = new BufferedOutputStream(fos)) {288 out.write(new Json().toJson(nodeConfig).getBytes(StandardCharsets.UTF_8));289 }290 }291 return filePath;292 }293 294 /**295 * {@inheritDoc}296 */297 @Override298 public Capabilities[] getCapabilitiesForJson(String capabilities) {299 JsonInput input = new Json().newInput(new StringReader(JSON_HEAD + capabilities + JSON_TAIL));300 return GridNodeConfiguration.loadFromJSON(input).capabilities.toArray(new Capabilities[0]);301 }302 /**303 * {@inheritDoc}304 */305 @Override306 public Capabilities mergeCapabilities(Capabilities target, Capabilities change) {307 return target.merge(change);308 }309 310 /**311 * {@inheritDoc}312 */313 @Override314 public String toJson(Object obj) {315 return new Json().toJson(obj);316 }317}...

Full Screen

Full Screen

Source:WebDriverFactory.java Github

copy

Full Screen

...100 event = eval.getExecuteEvent(101 "open url", op -> op102 .addValue("value", url)103 .addValue("remoteUrl", config.getRemoteUrl())104 .addValue("capabilities", config.getCapabilities().toJson()));105 eval.logEvent(event);106 driver = getRemoteWebDriver(config.getRemoteUrl(), config.getCapabilities());107 }else{108 event = eval.getEventJson(TestEvaluator.TEST_EXECUTE,109 "open url", op -> op110 .addValue("value", url)111 .addValue("capabilities", config.getCapabilities().toJson()));112 eval.logEvent(event);113 driver = getWebDriver(config.getCapabilities());114 }115 try {116 driver.get(url);117 clickThroughCertErrorPage(driver);118 } catch (Throwable e){119 close(driver);120 throw new PageException(new DefaultWebTestContext(driver), JsonLogConsoleOut.formatEvent(event));121 }122 return driver;123 }124 public static void close(WebDriver driver) {125 if (driver == null) {126 return;127 }128 TestEvaluator.Now eval = new TestEvaluator.Now();129 eval.logEvent(TestEvaluator.TEST_EXECUTE,130 "close driver", op -> op131 .addValue("url", driver.getCurrentUrl()));132 try {133 driver.close();134 driver.quit();135 } catch (Throwable e) {136 log.trace("Exception caught closing WebDriver.", e);137 }138 }139 private static void clickThroughCertErrorPage(WebDriver driver) {140 if (driver.getPageSource().contains("overridelink")) {141 driver.findElement(By.id("overridelink")).click();142 }143 }144 public static WebDriver getWebDriver(MutableCapabilities capabilities) {145 String browser = capabilities.getBrowserName();146 if(!browserFactoryMap.containsKey(browser)){147 throw new RuntimeException("Error: Unknown browser type [" + browser + "]. "148 + "Available browser types are: " + Arrays.toString(browserFactoryMap.keySet().toArray(new String[0])));149 }150 try {151 WebDriver driver = browserFactoryMap.get(browser).apply(capabilities);152 driver.manage().timeouts().pageLoadTimeout(DEFAULT_PAGE_LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS);153 driver.manage().timeouts().implicitlyWait(DEFAULT_IMPLICITLY_WAIT_MILLISECONDS, TimeUnit.MILLISECONDS);154 driver.manage().timeouts().setScriptTimeout(DEFAULT_SCRIPT_TIMEOUT_SECONDS, TimeUnit.SECONDS);155 return driver;156 } catch (Exception ex){157 throw new RuntimeException("Error: Unable to open browser with type [" + browser + "]", ex);158 }159 }160 public static RemoteWebDriver getRemoteWebDriver(String remoteURL, Capabilities caps) {161 try {162 RemoteWebDriver driver = new RemoteWebDriver(new URL(remoteURL), caps);163 driver.setFileDetector(new LocalFileDetector());164 return driver;165 } catch (MalformedURLException e) {166 log.error("Could not open web driver to remote URL: " + remoteURL, e);167 throw new RuntimeException(e);168 }169 }170 private static WebDriver openChrome(MutableCapabilities capabilities) {171 WebDriverManager.chromedriver().setup();172 ChromeOptions options = loadChromeOptions(capabilities);173 ChromeDriverService driverService = ChromeDriverService.createDefaultService();174 ChromeDriver driver = new ChromeDriver(driverService, options);175 if(new Gson().toJson(capabilities.toJson()).contains("--headless")) {176 String command = new StringBuilder().append("{")177 .append("\"cmd\":\"Page.setDownloadBehavior\"").append(",")178 .append("\"params\":{")179 .append("\"downloadPath\":\"" + DOWNLOAD_DIRECTORY + "\"").append(",")180 .append("\"behavior\":\"allow\"").append("}")181 .append("}").toString();182 HttpClient httpClient = HttpClientBuilder.create().build();183 try {184 String u = driverService.getUrl().toString() + "/session/" + ((ChromeDriver) driver).getSessionId() + "/chromium/send_command";185 HttpPost request = new HttpPost(u);186 request.addHeader("content-type", "application/json");187 request.setEntity(new StringEntity(command));188 httpClient.execute(request);189 } catch (Exception ex) {...

Full Screen

Full Screen

Source:DriverFactory.java Github

copy

Full Screen

...215 String sessionId = driver.getSessionId().toString();216 Util.log("Started %s, session ID=%s.\n", new Date().toString(), sessionId);217 driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);218 driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);219 String jsonCaps = new Gson().toJson(driver.getCapabilities().asMap());220 Util.log("Capabilities: %s\n", jsonCaps);221 return driver;222 }223}...

Full Screen

Full Screen

Source:DefaultChromeCapabilitiesProviderImpl.java Github

copy

Full Screen

...77 Map<String, Object> prefs = new HashMap<>();78 prefs.put("download.default_directory", downloadsManager.getDownloadsDir());79 chromeOptions.setExperimentalOption("prefs", prefs);80 }81 reporter.debug("Default chrome options:\n%s", GSON.toJson(chromeOptions.asMap()));82 return chromeOptions;83 }84 private MutableCapabilities getChromeCapabilities() {85 ChromeOptions chromeOptions = getChromeOptions();86 LoggingPreferences logPrefs = new LoggingPreferences();87 if (properties.driver().areConsoleLogsEnabled()) {88 logPrefs.enable(LogType.BROWSER, properties.driver().browserLogsLevel);89 }90 if (properties.driver().shouldCollectPerfLogs()) {91 logPrefs.enable(LogType.PERFORMANCE, Level.ALL);92 }93 chromeOptions.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);94 setUnexpectedAlertBehaviour(chromeOptions);95 return chromeOptions;...

Full Screen

Full Screen

Source:DesiredCapabilitiesLoader.java Github

copy

Full Screen

...77 Properties props = new Properties();78 MutableCapabilities capabilities = capabilitiesClass.newInstance();79 props.load(new FileInputStream(capabilitiesFile));80 props.forEach((key, value) -> capabilities.setCapability(key.toString(), value));81 reporter.debug("Desired capabilities loaded from file [%s]:\n%s", capabilitiesFile, GSON.toJson(capabilities.asMap()));82 return capabilities;83 } catch (Exception ex) {84 reporter.debug("Could not load desired capabilities from file [" + capabilitiesFile + "]", ex);85 return new DesiredCapabilities();86 }87 }88 public Capabilities loadJsonFile(File capabilitiesFile, Class<? extends Capabilities> capabilitiesClass) {89 try {90 String json = FileUtils.readFileToString(capabilitiesFile, StandardCharsets.UTF_8);91 json = properties.replaceProperties(json).replace("\\", "\\\\");92 Capabilities capabilities = GSON.fromJson(json, capabilitiesClass);93 reporter.debug("Desired capabilities loaded from file [%s]:\n%s", capabilitiesFile, GSON.toJson(capabilities.asMap()));94 return capabilities;95 } catch (Exception ex) {96 reporter.debug("Could not load desired capabilities from file [" + capabilitiesFile + "]", ex);97 return null;98 }99 }100 public Capabilities loadEnvironmentProperties() {101 return loadEnvironmentProperties(CAPABILITIES_PROPERTY_PREFIX, DesiredCapabilities.class);102 }103 public Capabilities loadEnvironmentProperties(Class<? extends MutableCapabilities> capabilitiesClass) {104 return loadEnvironmentProperties(CAPABILITIES_PROPERTY_PREFIX, capabilitiesClass);105 }106 public Capabilities loadEnvironmentProperties(String prefix, Class<? extends MutableCapabilities> capabilitiesClass) {107 try {108 MutableCapabilities capabilities = capabilitiesClass.newInstance();109 Properties props = properties.getEnvironmentProperties(prefix);110 MutablePropertySources propSrcs = ((AbstractEnvironment) environment).getPropertySources();111 StreamSupport.stream(propSrcs.spliterator(), false)112 .filter(ps -> ps instanceof EnumerablePropertySource)113 .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())114 .flatMap(Arrays::<String>stream)115 .forEach(propName -> {116 if (propName.startsWith(prefix)) {117 capabilities.setCapability(StringUtils.substringAfter(propName, prefix), environment.getProperty(propName));118 }119 }120 );121 reporter.debug("Desired capabilities loaded from Environment properties with prefix [%s]:\n%s", prefix, GSON.toJson(capabilities.asMap()));122 return capabilities;123 } catch (Exception ex) {124 reporter.debug("Could not load desired capabilities from file with prefix[" + prefix + "]", ex);125 return null;126 }127 }128}...

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.MutableCapabilities;2public class MutableCapabilitiesToJson {3 public static void main(String[] args) {4 MutableCapabilities capabilities = new MutableCapabilities();5 capabilities.setCapability("browserName", "chrome");6 capabilities.setCapability("browserVersion", "87.0");7 capabilities.setCapability("selenoid:options", new MutableCapabilities());8 System.out.println(capabilities.toJson());9 }10}11{"browserName":"chrome","browserVersion":"87.0","selenoid:options":{}}

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.MutableCapabilities;2import org.openqa.selenium.chrome.ChromeOptions;3import org.openqa.selenium.remote.RemoteWebDriver;4public class MutableCapabilitiesExample {5 public static void main(String[] args) {6 MutableCapabilities mutableCapabilities = new MutableCapabilities();7 mutableCapabilities.setCapability("key", "value");8 ChromeOptions chromeOptions = new ChromeOptions();9 chromeOptions.setCapability("key", "value");10 RemoteWebDriver driver = new RemoteWebDriver(chromeOptions);11 System.out.println(driver.getCapabilities().getCapability("key"));12 System.out.println(mutableCapabilities.toJson());13 }14}15{"key":"value"}

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.MutableCapabilities;2import org.openqa.selenium.chrome.ChromeOptions;3import org.openqa.selenium.remote.DesiredCapabilities;4public class ConvertToJSON {5 public static void main(String[] args) {6 MutableCapabilities chromeOptions = new ChromeOptions();7 chromeOptions.setCapability("platformName", "Windows 10");8 chromeOptions.setCapability("browserName", "chrome");9 chromeOptions.setCapability("browserVersion", "latest");10 chromeOptions.setCapability("sauce:options", new MutableCapabilities());11 chromeOptions.setCapability("goog:chromeOptions", new MutableCapabilities());12 String json = chromeOptions.toJson();13 System.out.println(json);14 }15}16{17 "sauce:options":{},18 "goog:chromeOptions":{}19}

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1capabilities = new MutableCapabilities()2capabilities.setCapability("browserName", "chrome")3capabilities.setCapability("browserVersion", "latest")4capabilities.setCapability("platformName", "Windows 10")5println(capabilities.toJson())6capabilities = new MutableCapabilities()7capabilities.setCapability("browserName", "chrome")8capabilities.setCapability("browserVersion", "latest")9capabilities.setCapability("platformName", "Windows 10")10println(capabilities.toMap())11capabilities = new MutableCapabilities()12capabilities.setCapability("browserName", "chrome")13capabilities.setCapability("browserVersion", "latest")14capabilities.setCapability("platformName", "Windows 10")15println(capabilities.toCapabilities())16capabilities = new MutableCapabilities()17capabilities.setCapability("browserName", "chrome")18capabilities.setCapability("browserVersion", "latest")19capabilities.setCapability("platformName", "Windows 10")20println(capabilities.getCapability("browserName"))21capabilities = new MutableCapabilities()22capabilities.setCapability("browserName", "chrome")23capabilities.setCapability("browserVersion", "latest")24capabilities.setCapability("platformName", "Windows 10")25capabilities.setCapability("browserName", "firefox")26println(capabilities.getCapability("browserName"))27capabilities = new MutableCapabilities()28capabilities.setCapability("browserName", "chrome")29capabilities.setCapability("browserVersion", "latest")30capabilities.setCapability("platformName", "Windows 10")31println(capabilities.asMap())32capabilities = new MutableCapabilities()33capabilities.setCapability("browserName", "chrome")34capabilities.setCapability("browserVersion", "latest")35capabilities.setCapability("platformName", "Windows 10")36println(capabilities.asMap())

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1public class CapabilitiesToJSON {2 public static void main(String[] args) throws IOException {3 MutableCapabilities caps = new ChromeOptions();4 caps.setCapability("platform", "windows");5 caps.setCapability("version", "81");6 caps.setCapability("name", "My Test");7 caps.setCapability("build", "My Build");8 caps.setCapability("browserstack.local", "true");9 caps.setCapability("browserstack.video", "true");10 caps.setCapability("browserstack.selenium_version", "3.141.59");11 caps.setCapability("browserstack.debug", "true");12 String json = caps.toJson();13 System.out.println(json);14 File file = new File("C:\\Users\\user\\Desktop\\json.txt");15 FileWriter fr = new FileWriter(file);16 fr.write(json);17 fr.close();18 Scanner sc = new Scanner(file);19 String str = "";20 while (sc.hasNextLine()) {21 str += sc.nextLine();22 }23 System.out.println(str);24 MutableCapabilities caps1 = new MutableCapabilities();25 caps1.fromJson(str);26 System.out.println(caps1);27 RemoteWebDriver driver = new ChromeDriver(caps1);28 System.out.println(driver.getTitle());29 driver.quit();30 }31}32{"browserstack.debug":"true","browserstack.local":"true","browserstack.selenium_version":"3.141.59","browserstack.video":"true","browserName":"chrome","build":"My Build","name":"My Test","platform":"windows","version":"81"}33{"browserstack.debug":"true","browserstack.local":"true","browserstack.selenium_version":"3.141.59","browserstack.video":"true","browserName":"chrome","build":"My Build","

Full Screen

Full Screen

Selenium 4 Tutorial:

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.

Chapters:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful