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

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

Source:JsonTest.java Github

copy

Full Screen

...71 public void canRoundTripNumbers() {72 Map<String, Object> original = ImmutableMap.of(73 "options", ImmutableMap.of("args", ImmutableList.of(1L, "hello")));74 Json json = new Json();75 String converted = json.toJson(original);76 Object remade = json.toType(converted, MAP_TYPE);77 assertEquals(original, remade);78 }79 @Test80 public void roundTripAFirefoxOptions() {81 Map<String, Object> caps = ImmutableMap.of(82 "moz:firefoxOptions", ImmutableMap.of(83 "prefs", ImmutableMap.of("foo.bar", 1)));84 String json = new Json().toJson(caps);85 assertFalse(json, json.contains("1.0"));86 try (JsonInput input = new Json().newInput(new StringReader(json))) {87 json = new Json().toJson(input.read(Json.MAP_TYPE));88 assertFalse(json, json.contains("1.0"));89 }90 }91 @Test92 public void shouldCoerceAListOfCapabilitiesIntoSomethingMutable() {93 // This is needed since Grid expects each of the capabilities to be mutable94 List<Capabilities> expected = ImmutableList.of(95 new ImmutableCapabilities("cheese", "brie"),96 new ImmutableCapabilities("peas", 42L));97 Json json = new Json();98 String raw = json.toJson(expected);99 List<Capabilities> seen = json.toType(raw, new TypeToken<List<Capabilities>>(){}.getType());100 assertEquals(expected, seen);101 assertTrue(seen.get(0) instanceof MutableCapabilities);102 }103 @Test104 public void shouldUseBeanSettersToPopulateFields() {105 Map<String, String> map = ImmutableMap.of("name", "fishy");106 Json json = new Json();107 String raw = json.toJson(map);108 BeanWithSetter seen = json.toType(raw, BeanWithSetter.class);109 assertEquals("fishy", seen.theName);110 }111 public static class BeanWithSetter {112 String theName;113 public void setName(String name) {114 theName = name;115 }116 }117 @Test118 public void shouldAllowUserToPopulateFieldsDirectly() {119 Map<String, String> map = ImmutableMap.of("theName", "fishy");120 Json json = new Json();121 String raw = json.toJson(map);122 BeanWithSetter seen = json.toType(raw, BeanWithSetter.class, PropertySetting.BY_FIELD);123 assertEquals("fishy", seen.theName);124 }125 @Test126 public void testCanConstructASimpleString() {127 String text = new Json().toType("cheese", String.class);128 assertThat(text, is("cheese"));129 }130 @SuppressWarnings("unchecked")131 @Test132 public void testCanPopulateAMap() {133 JsonObject toConvert = new JsonObject();134 toConvert.addProperty("cheese", "brie");135 toConvert.addProperty("foodstuff", "cheese");136 Map<String, String> map = new Json().toType(toConvert.toString(), Map.class);137 assertThat(map.size(), is(2));138 assertThat(map, hasEntry("cheese", "brie"));139 assertThat(map, hasEntry("foodstuff", "cheese"));140 }141 @Test142 public void testCanPopulateAMapThatContainsNull() {143 JsonObject toConvert = new JsonObject();144 toConvert.add("foo", JsonNull.INSTANCE);145 Map<?,?> converted = new Json().toType(toConvert.toString(), Map.class);146 assertEquals(1, converted.size());147 assertTrue(converted.containsKey("foo"));148 assertNull(converted.get("foo"));149 }150 @Test151 public void testCanPopulateASimpleBean() {152 JsonObject toConvert = new JsonObject();153 toConvert.addProperty("value", "time");154 SimpleBean bean = new Json().toType(toConvert.toString(), SimpleBean.class);155 assertThat(bean.getValue(), is("time"));156 }157 @Test158 public void testWillSilentlyDiscardUnusedFieldsWhenPopulatingABean() {159 JsonObject toConvert = new JsonObject();160 toConvert.addProperty("value", "time");161 toConvert.addProperty("frob", "telephone");162 SimpleBean bean = new Json().toType(toConvert.toString(), SimpleBean.class);163 assertThat(bean.getValue(), is("time"));164 }165 @Test166 public void testShouldSetPrimitiveValuesToo() {167 JsonObject toConvert = new JsonObject();168 toConvert.addProperty("magicNumber", 3);169 Map<?,?> map = new Json().toType(toConvert.toString(), Map.class);170 assertEquals(3L, map.get("magicNumber"));171 }172 @Test173 public void testShouldPopulateFieldsOnNestedBeans() {174 JsonObject toConvert = new JsonObject();175 toConvert.addProperty("name", "frank");176 JsonObject child = new JsonObject();177 child.addProperty("value", "lots");178 toConvert.add("bean", child);179 ContainingBean bean = new Json().toType(toConvert.toString(), ContainingBean.class);180 assertThat(bean.getName(), is("frank"));181 assertThat(bean.getBean().getValue(), is("lots"));182 }183 @Test184 public void testShouldProperlyFillInACapabilitiesObject() {185 DesiredCapabilities capabilities =186 new DesiredCapabilities("browser", CapabilityType.VERSION, Platform.ANY);187 capabilities.setJavascriptEnabled(true);188 String text = new Json().toJson(capabilities);189 Capabilities readCapabilities = new Json().toType(text, DesiredCapabilities.class);190 assertEquals(capabilities, readCapabilities);191 }192 @Test193 public void testShouldUseAMapToRepresentComplexObjects() {194 JsonObject toModel = new JsonObject();195 toModel.addProperty("thing", "hairy");196 toModel.addProperty("hairy", "true");197 Map<?,?> modelled = (Map<?,?>) new Json().toType(toModel.toString(), Object.class);198 assertEquals(2, modelled.size());199 }200 @Test201 public void testShouldConvertAResponseWithAnElementInIt() {202 String json =203 "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}";204 Response converted = new Json().toType(json, Response.class);205 Map<?,?> value = (Map<?,?>) converted.getValue();206 assertEquals("three", value.get("id"));207 }208 @Test209 public void testShouldBeAbleToCopeWithStringsThatLookLikeBooleans() {210 String json =211 "{\"value\":\"false\",\"context\":\"foo\",\"sessionId\":\"1210083863107\"}";212 try {213 new Json().toType(json, Response.class);214 } catch (Exception e) {215 e.printStackTrace();216 fail("This should have worked");217 }218 }219 @Test220 public void testShouldBeAbleToSetAnObjectToABoolean() {221 String json =222 "{\"value\":true,\"context\":\"foo\",\"sessionId\":\"1210084658750\"}";223 Response response = new Json().toType(json, Response.class);224 assertThat(response.getValue(), is(true));225 }226 @Test227 public void testCanHandleValueBeingAnArray() {228 String[] value = {"Cheese", "Peas"};229 Response response = new Response();230 response.setSessionId("bar");231 response.setValue(value);232 response.setStatus(1512);233 String json = new Json().toJson(response);234 Response converted = new Json().toType(json, Response.class);235 assertEquals("bar", response.getSessionId());236 assertEquals(2, ((List<?>) converted.getValue()).size());237 assertEquals(1512, response.getStatus().intValue());238 }239 @Test240 public void testShouldConvertObjectsInArraysToMaps() {241 Date date = new Date();242 Cookie cookie = new Cookie("foo", "bar", "localhost", "/rooted", date, true, true);243 String rawJson = new Json().toJson(Collections.singletonList(cookie));244 List<?> list = new Json().toType(rawJson, List.class);245 Object first = list.get(0);246 assertTrue(first instanceof Map);247 Map<?,?> map = (Map<?,?>) first;248 assertMapEntry(map, "name", "foo");249 assertMapEntry(map, "value", "bar");250 assertMapEntry(map, "domain", "localhost");251 assertMapEntry(map, "path", "/rooted");252 assertMapEntry(map, "secure", true);253 assertMapEntry(map, "httpOnly", true);254 assertMapEntry(map, "expiry", TimeUnit.MILLISECONDS.toSeconds(date.getTime()));255 }256 private void assertMapEntry(Map<?,?> map, String key, Object expected) {257 assertTrue("Missing key: " + key, map.containsKey(key));258 assertEquals("Wrong value for key: " + key + ": " + map.get(key).getClass().getName(),259 expected, map.get(key));260 }261 @Test262 public void testShouldConvertAnArrayBackIntoAnArray() {263 Exception e = new Exception();264 String converted = new Json().toJson(e);265 Map<?,?> reconstructed = new Json().toType(converted, Map.class);266 List<?> trace = (List<?>) reconstructed.get("stackTrace");267 assertTrue(trace.get(0) instanceof Map);268 }269 @Test270 public void testShouldBeAbleToReconsituteASessionId() {271 String json = new Json().toJson(new SessionId("id"));272 SessionId sessionId = new Json().toType(json, SessionId.class);273 assertEquals("id", sessionId.toString());274 }275 @Test276 public void testShouldBeAbleToConvertACommand() {277 SessionId sessionId = new SessionId("session id");278 Command original = new Command(279 sessionId,280 DriverCommand.NEW_SESSION,281 ImmutableMap.of("food", "cheese"));282 String raw = new Json().toJson(original);283 Command converted = new Json().toType(raw, Command.class);284 assertEquals(sessionId.toString(), converted.getSessionId().toString());285 assertEquals(original.getName(), converted.getName());286 assertEquals(1, converted.getParameters().keySet().size());287 assertEquals("cheese", converted.getParameters().get("food"));288 }289 @Test290 public void testShouldConvertCapabilitiesToAMapAndIncludeCustomValues() {291 Capabilities caps = new ImmutableCapabilities("furrfu", "fishy");292 String raw = new Json().toJson(caps);293 Capabilities converted = new Json().toType(raw, Capabilities.class);294 assertEquals("fishy", converted.getCapability("furrfu"));295 }296 @Test297 public void testShouldParseCapabilitiesWithLoggingPreferences() {298 JsonObject prefs = new JsonObject();299 prefs.addProperty("browser", "WARNING");300 prefs.addProperty("client", "DEBUG");301 prefs.addProperty("driver", "ALL");302 prefs.addProperty("server", "OFF");303 JsonObject caps = new JsonObject();304 caps.add(CapabilityType.LOGGING_PREFS, prefs);305 Capabilities converted = new Json().toType(caps.toString(), Capabilities.class);306 LoggingPreferences lp =...

Full Screen

Full Screen

Source:BeanToJsonConverter.java Github

copy

Full Screen

...36 }37 try38 {39 JsonElement json = convertObject(object);40 return new GsonBuilder().disableHtmlEscaping().serializeNulls().create().toJson(json);41 } catch (Exception e) {42 throw new WebDriverException("Unable to convert: " + object, e);43 }44 }45 46 public JsonElement convertObject(Object object)47 {48 if (object == null) {49 return JsonNull.INSTANCE;50 }51 try52 {53 return convertObject(object, 5);54 } catch (Exception e) {55 throw new WebDriverException("Unable to convert: " + object, e);56 }57 }58 59 private JsonElement convertObject(Object toConvert, int maxDepth) throws Exception60 {61 if (toConvert == null) {62 return JsonNull.INSTANCE;63 }64 65 if ((toConvert instanceof Boolean)) {66 return new JsonPrimitive((Boolean)toConvert);67 }68 69 if ((toConvert instanceof CharSequence)) {70 return new JsonPrimitive(String.valueOf(toConvert));71 }72 73 if ((toConvert instanceof Number)) {74 return new JsonPrimitive((Number)toConvert);75 }76 77 if ((toConvert instanceof Level)) {78 return new JsonPrimitive(LogLevelMapping.getName((Level)toConvert));79 }80 81 if ((toConvert.getClass().isEnum()) || ((toConvert instanceof Enum))) {82 return new JsonPrimitive(toConvert.toString());83 }84 85 if ((toConvert instanceof LoggingPreferences)) {86 LoggingPreferences prefs = (LoggingPreferences)toConvert;87 JsonObject converted = new JsonObject();88 for (String logType : prefs.getEnabledLogTypes()) {89 converted.addProperty(logType, LogLevelMapping.getName(prefs.getLevel(logType)));90 }91 return converted;92 }93 94 if ((toConvert instanceof SessionLogs)) {95 return convertObject(((SessionLogs)toConvert).getAll(), maxDepth - 1);96 }97 98 if ((toConvert instanceof LogEntries)) {99 return convertObject(((LogEntries)toConvert).getAll(), maxDepth - 1);100 }101 JsonObject converted;102 if ((toConvert instanceof Map)) {103 Map<String, Object> map = (Map)toConvert;104 if ((map.size() == 1) && (map.containsKey("w3c cookie"))) {105 return convertObject(map.get("w3c cookie"));106 }107 108 converted = new JsonObject();109 for (Map.Entry<String, Object> entry : map.entrySet()) {110 converted.add((String)entry.getKey(), convertObject(entry.getValue(), maxDepth - 1));111 }112 return converted;113 }114 115 if ((toConvert instanceof JsonElement)) {116 return (JsonElement)toConvert;117 }118 119 if ((toConvert instanceof Collection)) {120 JsonArray array = new JsonArray();121 for (Object o : (Collection)toConvert) {122 array.add(convertObject(o, maxDepth - 1));123 }124 return array;125 }126 127 if (toConvert.getClass().isArray()) {128 JsonArray converted = new JsonArray();129 int length = Array.getLength(toConvert);130 for (int i = 0; i < length; i++) {131 converted.add(convertObject(Array.get(toConvert, i), maxDepth - 1));132 }133 return converted;134 }135 136 if ((toConvert instanceof SessionId)) {137 JsonObject converted = new JsonObject();138 converted.addProperty("value", toConvert.toString());139 return converted;140 }141 142 if ((toConvert instanceof Date)) {143 return new JsonPrimitive(Long.valueOf(TimeUnit.MILLISECONDS.toSeconds(((Date)toConvert).getTime())));144 }145 146 if ((toConvert instanceof File)) {147 return new JsonPrimitive(((File)toConvert).getAbsolutePath());148 }149 150 Method toMap = getMethod(toConvert, "toMap");151 if (toMap == null) {152 toMap = getMethod(toConvert, "asMap");153 }154 if (toMap != null) {155 try {156 return convertObject(toMap.invoke(toConvert, new Object[0]), maxDepth - 1);157 } catch (ReflectiveOperationException e) {158 throw new WebDriverException(e);159 }160 }161 162 Method toJson = getMethod(toConvert, "toJson");163 if (toJson != null) {164 try {165 Object res = toJson.invoke(toConvert, new Object[0]);166 if ((res instanceof JsonElement)) {167 return (JsonElement)res;168 }169 170 if ((res instanceof Map))171 return convertObject(res);172 if ((res instanceof Collection))173 return convertObject(res);174 if ((res instanceof String)) {175 try {176 return new JsonParser().parse((String)res);177 } catch (JsonParseException e) {178 return new JsonPrimitive((String)res);179 }...

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Cookie;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4public class CookieToJson {5 public static void main(String[] args) {6 WebDriver driver = new FirefoxDriver();7 Cookie cookie = driver.manage().getCookieNamed("PREF");8 String json = cookie.toJson();9 System.out.println(json);10 }11}12{"name":"PREF","value":"ID=8f8cfe6b5a6e0e6b:U=2f2f1e9d9f7c0a0e:FF=0:LD=en:TM=1454906808:LM=1454906808:S=Q9kxjzZTgJZ0vzC0","domain":".google.com","path":"/","expiry":null,"isSecure":false,"isHttpOnly":false}

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");2String cookieJson = cookie.toJson();3System.out.println(cookieJson);4Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");5Cookie.Builder builder = new Cookie.Builder(cookie.getName(), cookie.getValue());6builder.domain(cookie.getDomain());7builder.path(cookie.getPath());8builder.expiry(cookie.getExpiry());9builder.isHttpOnly(cookie.isHttpOnly());10builder.isSecure(cookie.isSecure());11Cookie newCookie = builder.build();12System.out.println(newCookie);13Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");14Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiry(), cookie.isSecure(), cookie.isHttpOnly());15System.out.println(newCookie);16Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");17String cookieString = cookie.toString();18System.out.println(cookieString);19Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");20Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiry(), cookie.isSecure(), cookie.isHttpOnly());21System.out.println(newCookie);22Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");23String cookieString = cookie.toString();24System.out.println(cookieString);25Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");26Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiry(), cookie.isSecure(), cookie.isHttpOnly());27System.out.println(newCookie);28Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");29String cookieString = cookie.toString();30System.out.println(cookieString);31Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");32Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getPath(), cookie.getExpiry(), cookie.isSecure(), cookie.isHttpOnly());33System.out.println(newCookie);34Cookie cookie = driver.manage().getCookieNamed("JSESSIONID");

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1import groovy.json.JsonSlurper2import groovy.json.JsonOutput3def jsonSlurper = new JsonSlurper()4def json = jsonSlurper.parseText(prev.getResponseDataAsString())5def cookie = new org.openqa.selenium.Cookie('cookieName', cookieValue)6def cookieJson = JsonOutput.toJson(cookie)7prev.setCookie(cookieJson)8prev.setCookie('cookieName=' + cookieValue)9prev.setCookie(cookieValue)10prev.setCookie(cookieValue + '; cookieName=cookieValue')11prev.setCookie(cookieValue + '; cookieName=cookieValue; path=/')12prev.setCookie(cookieValue + '; cookieName=cookieValue; path=/; domain=example.com')13prev.setCookie(cookieValue + '; cookieName=cookieValue; path=/; domain=example.com; secure')14prev.setCookie(cookieValue + '; cookieName=cookieValue; path=/; domain=example.com; secure; httpOnly')15prev.setCookie(cookieValue + '; cookieName=cookieValue; path=/; domain=example.com; secure; httpOnly; sameSite=Lax')16prev.setCookie(cookieValue + '; cookieName=cookieValue; path=/; domain=example.com; secure; httpOnly; sameSite=Lax; maxAge=86400')17prev.setCookie(cookieValue + '; cookieName=cookieValue; path=/; domain=example.com; secure; httpOnly; sameSite=Lax; maxAge=86400; expiry=2021-01-01T00:00:00Z')18prev.setCookie(cookieValue + '; cookieName=cookieValue

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1import java.io.FileReader2import java.io.FileWriter3import java.io.IOException4import org.openqa.selenium.Cookie5import org.openqa.selenium.WebDriver6import org.openqa.selenium.chrome.ChromeDriver7import com.google.gson.Gson8public class CookieToJson {9 public static void main(String[] args) {10 System.setProperty("webdriver.chrome.driver", "C:\\Users\\vicky\\Downloads\\chromedriver_win32\\chromedriver.exe");11 WebDriver driver = new ChromeDriver();12 Cookie cookie = driver.manage().getCookieNamed("1P_JAR");13 Gson gson = new Gson();14 String json = gson.toJson(cookie);15 try {16 FileWriter writer = new FileWriter("cookie.txt");17 writer.write(json);18 writer.close();19 } catch (IOException e) {20 e.printStackTrace();21 }22 Cookie cookie2 = null;23 try {24 FileReader reader = new FileReader("cookie.txt");25 cookie2 = gson.fromJson(reader, Cookie.class);26 } catch (IOException e) {27 e.printStackTrace();28 }29 System.out.println(cookie2.getName());30 System.out.println(cookie2.getValue());31 System.out.println(cookie2.getDomain());32 System.out.println(cookie2.getPath());33 System.out.println(cookie2.getExpiry());34 System.out.println(cookie2.isSecure());35 driver.close();36 }37}

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