Best Selenium code snippet using org.openqa.selenium.Enum Proxy.ProxyType
Source:JsonTest.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.json;18import static org.hamcrest.Matchers.hasEntry;19import static org.hamcrest.Matchers.instanceOf;20import static org.hamcrest.Matchers.is;21import static org.hamcrest.core.IsEqual.equalTo;22import static org.junit.Assert.assertEquals;23import static org.junit.Assert.assertFalse;24import static org.junit.Assert.assertNotNull;25import static org.junit.Assert.assertNull;26import static org.junit.Assert.assertThat;27import static org.junit.Assert.assertTrue;28import static org.junit.Assert.fail;29import static org.openqa.selenium.json.Json.MAP_TYPE;30import com.google.common.collect.ImmutableList;31import com.google.common.collect.ImmutableMap;32import com.google.common.reflect.TypeToken;33import com.google.gson.JsonNull;34import com.google.gson.JsonObject;35import org.junit.Test;36import org.openqa.selenium.Capabilities;37import org.openqa.selenium.Cookie;38import org.openqa.selenium.ImmutableCapabilities;39import org.openqa.selenium.MutableCapabilities;40import org.openqa.selenium.Platform;41import org.openqa.selenium.Proxy;42import org.openqa.selenium.logging.LogType;43import org.openqa.selenium.logging.LoggingPreferences;44import org.openqa.selenium.remote.CapabilityType;45import org.openqa.selenium.remote.Command;46import org.openqa.selenium.remote.DesiredCapabilities;47import org.openqa.selenium.remote.DriverCommand;48import org.openqa.selenium.remote.ErrorCodes;49import org.openqa.selenium.remote.Response;50import org.openqa.selenium.remote.SessionId;51import java.io.StringReader;52import java.util.Collections;53import java.util.Date;54import java.util.List;55import java.util.Map;56import java.util.concurrent.TimeUnit;57import java.util.logging.Level;58public class JsonTest {59 @Test60 public void canReadBooleans() {61 assertTrue(new Json().toType("true", Boolean.class));62 assertFalse(new Json().toType("false", Boolean.class));63 }64 @Test65 public void canReadANumber() {66 assertEquals(Long.valueOf(42), new Json().toType("42", Number.class));67 assertEquals(Integer.valueOf(42), new Json().toType("42", Integer.class));68 assertEquals(Double.valueOf(42), new Json().toType("42", Double.class));69 }70 @Test71 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 =307 (LoggingPreferences) converted.getCapability(CapabilityType.LOGGING_PREFS);308 assertNotNull(lp);309 assertEquals(Level.WARNING, lp.getLevel(LogType.BROWSER));310 assertEquals(Level.FINE, lp.getLevel(LogType.CLIENT));311 assertEquals(Level.ALL, lp.getLevel(LogType.DRIVER));312 assertEquals(Level.OFF, lp.getLevel(LogType.SERVER));313 }314 @Test315 public void testShouldNotParseQuotedJsonObjectsAsActualJsonObjects() {316 JsonObject inner = new JsonObject();317 inner.addProperty("color", "green");318 inner.addProperty("number", 123);319 JsonObject outer = new JsonObject();320 outer.addProperty("inner", inner.toString());321 String jsonStr = outer.toString();322 Object convertedOuter = new Json().toType(jsonStr, Map.class);323 assertThat(convertedOuter, instanceOf(Map.class));324 Object convertedInner = ((Map<?,?>) convertedOuter).get("inner");325 assertNotNull(convertedInner);326 assertThat(convertedInner, instanceOf(String.class));327 assertThat(convertedInner.toString(), equalTo(inner.toString()));328 }329 @Test330 public void shouldBeAbleToConvertASelenium3CommandToASelenium2Command() {331 SessionId expectedId = new SessionId("thisisakey");332 JsonObject rawJson = new JsonObject();333 // In selenium 2, the sessionId is an object. In selenium 3, it's a straight string.334 rawJson.addProperty("sessionId", expectedId.toString());335 rawJson.addProperty("name", "some command");336 rawJson.add("parameters", new JsonObject());337 String stringified = rawJson.toString();338 Command converted = new Json().toType(stringified, Command.class);339 assertEquals(expectedId, converted.getSessionId());340 }341 @Test342 public void testShouldCallFromJsonMethodIfPresent() {343 JsonAware res = new Json().toType("converted", JsonAware.class);344 assertEquals("\"converted\"", res.convertedValue);345 }346 // Test for issue 8187347 @Test348 public void testDecodingResponseWithNumbersInValueObject() {349 Response response = new Json().toType(350 "{\"status\":0,\"value\":{\"width\":96,\"height\":46.19140625}}",351 Response.class);352 @SuppressWarnings("unchecked")353 Map<String, Number> value = (Map<String, Number>) response.getValue();354 assertEquals(96, value.get("width").intValue());355 assertEquals(46, value.get("height").intValue());356 assertEquals(46.19140625, value.get("height").doubleValue(), 0.00001);357 }358 @Test359 public void testShouldRecognizeNumericStatus() {360 Response response = new Json().toType(361 "{\"status\":0,\"value\":\"cheese\"}",362 Response.class);363 assertEquals(0, response.getStatus().intValue());364 assertEquals(new ErrorCodes().toState(0), response.getState());365 String value = (String) response.getValue();366 assertEquals("cheese", value);367 }368 @Test369 public void testShouldRecognizeStringStatus() {370 Response response = new Json().toType(371 "{\"status\":\"success\",\"value\":\"cheese\"}",372 Response.class);373 assertEquals(0, response.getStatus().intValue());374 assertEquals(new ErrorCodes().toState(0), response.getState());375 String value = (String) response.getValue();376 assertEquals("cheese", value);377 }378 @Test379 public void testShouldConvertInvalidSelectorError() {380 Response response = new Json().toType(381 "{\"state\":\"invalid selector\",\"message\":\"invalid xpath selector\"}",382 Response.class);383 assertEquals(32, response.getStatus().intValue());384 assertEquals(new ErrorCodes().toState(32), response.getState());385 }386 @Test387 public void testShouldRecognizeStringState() {388 Response response = new Json()389 .toType(390 "{\"state\":\"success\",\"value\":\"cheese\"}",391 Response.class);392 assertEquals("success", response.getState());393 assertEquals(0, response.getStatus().intValue());394 String value = (String) response.getValue();395 assertEquals("cheese", value);396 }397 @Test398 public void testNoStatusShouldBeNullInResponseObject() {399 Response response = new Json().toType("{\"value\":\"cheese\"}", Response.class);400 assertNull(response.getStatus());401 }402 @Test403 public void canConvertAnEnumWithALowerCaseValue() {404 Proxy.ProxyType type = new Json().toType("pac", Proxy.ProxyType.class);405 assertEquals(Proxy.ProxyType.PAC, type);406 }407 public static class SimpleBean {408 private String value;409 public String getValue() {410 return value;411 }412 public void setValue(String value) {413 this.value = value;414 }415 }416 public static class ContainingBean {417 private String name;418 private SimpleBean bean;419 public String getName() {420 return name;421 }422 public void setName(String name) {423 this.name = name;424 }425 public SimpleBean getBean() {426 return bean;427 }428 public void setBean(SimpleBean bean) {429 this.bean = bean;430 }431 }432 public static class JsonAware {433 private String convertedValue;434 public JsonAware(String convertedValue) {435 this.convertedValue = convertedValue;436 }437 public static JsonAware fromJson(String json) {438 return new JsonAware(json);439 }440 }441}...
Source:JsonToBeanConverterTest.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.json;18import static org.hamcrest.Matchers.equalTo;19import static org.hamcrest.Matchers.hasEntry;20import static org.hamcrest.Matchers.instanceOf;21import static org.hamcrest.Matchers.is;22import static org.junit.Assert.assertEquals;23import static org.junit.Assert.assertFalse;24import static org.junit.Assert.assertNotNull;25import static org.junit.Assert.assertNull;26import static org.junit.Assert.assertThat;27import static org.junit.Assert.assertTrue;28import static org.junit.Assert.fail;29import com.google.gson.JsonArray;30import com.google.gson.JsonNull;31import com.google.gson.JsonObject;32import com.google.gson.JsonPrimitive;33import org.junit.Assert;34import org.junit.Test;35import org.junit.runner.RunWith;36import org.junit.runners.JUnit4;37import org.openqa.selenium.Capabilities;38import org.openqa.selenium.Cookie;39import org.openqa.selenium.ImmutableCapabilities;40import org.openqa.selenium.Platform;41import org.openqa.selenium.Proxy;42import org.openqa.selenium.logging.LogType;43import org.openqa.selenium.logging.LoggingPreferences;44import org.openqa.selenium.remote.CapabilityType;45import org.openqa.selenium.remote.Command;46import org.openqa.selenium.remote.DesiredCapabilities;47import org.openqa.selenium.remote.DriverCommand;48import org.openqa.selenium.remote.ErrorCodes;49import org.openqa.selenium.remote.Response;50import org.openqa.selenium.remote.SessionId;51import java.util.Collections;52import java.util.Date;53import java.util.HashMap;54import java.util.List;55import java.util.Map;56import java.util.concurrent.TimeUnit;57import java.util.logging.Level;58@RunWith(JUnit4.class)59public class JsonToBeanConverterTest {60 @Test61 public void testCanConstructASimpleString() throws Exception {62 String text = new JsonToBeanConverter().convert(String.class, "cheese");63 assertThat(text, is("cheese"));64 }65 @SuppressWarnings("unchecked")66 @Test67 public void testCanPopulateAMap() throws Exception {68 JsonObject toConvert = new JsonObject();69 toConvert.addProperty("cheese", "brie");70 toConvert.addProperty("foodstuff", "cheese");71 Map<String, String> map = new JsonToBeanConverter().convert(Map.class, toConvert.toString());72 assertThat(map.size(), is(2));73 assertThat(map, hasEntry("cheese", "brie"));74 assertThat(map, hasEntry("foodstuff", "cheese"));75 }76 @Test77 public void testCanPopulateAMapThatContainsNull() throws Exception {78 JsonObject toConvert = new JsonObject();79 toConvert.add("foo", JsonNull.INSTANCE);80 Map<?,?> converted = new JsonToBeanConverter().convert(Map.class, toConvert.toString());81 assertEquals(1, converted.size());82 assertTrue(converted.containsKey("foo"));83 assertNull(converted.get("foo"));84 }85 @Test86 public void testCanPopulateASimpleBean() throws Exception {87 JsonObject toConvert = new JsonObject();88 toConvert.addProperty("value", "time");89 SimpleBean bean = new JsonToBeanConverter().convert(SimpleBean.class, toConvert.toString());90 assertThat(bean.getValue(), is("time"));91 }92 @Test93 public void testWillSilentlyDiscardUnusedFieldsWhenPopulatingABean() throws Exception {94 JsonObject toConvert = new JsonObject();95 toConvert.addProperty("value", "time");96 toConvert.addProperty("frob", "telephone");97 SimpleBean bean = new JsonToBeanConverter().convert(SimpleBean.class, toConvert.toString());98 assertThat(bean.getValue(), is("time"));99 }100 @Test101 public void testShouldSetPrimitiveValuesToo() throws Exception {102 JsonObject toConvert = new JsonObject();103 toConvert.addProperty("magicNumber", 3);104 Map<?,?> map = new JsonToBeanConverter().convert(Map.class, toConvert.toString());105 assertEquals(3L, map.get("magicNumber"));106 }107 @Test108 public void testShouldPopulateFieldsOnNestedBeans() throws Exception {109 JsonObject toConvert = new JsonObject();110 toConvert.addProperty("name", "frank");111 JsonObject child = new JsonObject();112 child.addProperty("value", "lots");113 toConvert.add("bean", child);114 ContainingBean bean =115 new JsonToBeanConverter().convert(ContainingBean.class, toConvert.toString());116 assertThat(bean.getName(), is("frank"));117 assertThat(bean.getBean().getValue(), is("lots"));118 }119 @Test120 public void testShouldProperlyFillInACapabilitiesObject() throws Exception {121 DesiredCapabilities capabilities =122 new DesiredCapabilities("browser", CapabilityType.VERSION, Platform.ANY);123 capabilities.setJavascriptEnabled(true);124 String text = new BeanToJsonConverter().convert(capabilities);125 Capabilities readCapabilities =126 new JsonToBeanConverter().convert(DesiredCapabilities.class, text);127 assertEquals(capabilities, readCapabilities);128 }129 @Test130 public void testShouldBeAbleToInstantiateBooleans() throws Exception {131 JsonArray array = new JsonArray();132 array.add(new JsonPrimitive(true));133 array.add(new JsonPrimitive(false));134 boolean first = new JsonToBeanConverter().convert(Boolean.class, array.get(0));135 boolean second = new JsonToBeanConverter().convert(Boolean.class, array.get(1));136 assertTrue(first);137 assertFalse(second);138 }139 @Test140 public void testShouldUseAMapToRepresentComplexObjects() throws Exception {141 JsonObject toModel = new JsonObject();142 toModel.addProperty("thing", "hairy");143 toModel.addProperty("hairy", "true");144 Map<?,?> modelled = (Map<?,?>) new JsonToBeanConverter().convert(145 Object.class,146 toModel.toString());147 assertEquals(2, modelled.size());148 }149 @Test150 public void testShouldConvertAResponseWithAnElementInIt() throws Exception {151 String json =152 "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}";153 Response154 converted = new JsonToBeanConverter().convert(Response.class, json);155 Map<?,?> value = (Map<?,?>) converted.getValue();156 assertEquals("three", value.get("id"));157 }158 @Test159 public void testConvertABlankStringAsAStringEvenWhenAskedToReturnAnObject() throws Exception {160 Object o = new JsonToBeanConverter().convert(Object.class, "");161 assertTrue(o instanceof String);162 }163 @Test164 public void testShouldBeAbleToCopeWithStringsThatLookLikeBooleans() throws Exception {165 String json =166 "{\"value\":\"false\",\"context\":\"foo\",\"sessionId\":\"1210083863107\"}";167 try {168 new JsonToBeanConverter().convert(Response.class, json);169 } catch (Exception e) {170 e.printStackTrace();171 fail("This should have worked");172 }173 }174 @Test175 public void testShouldBeAbleToSetAnObjectToABoolean() throws Exception {176 String json =177 "{\"value\":true,\"context\":\"foo\",\"sessionId\":\"1210084658750\"}";178 Response response = new JsonToBeanConverter().convert(Response.class, json);179 assertThat((Boolean) response.getValue(), is(true));180 }181 @Test182 public void testCanHandleValueBeingAnArray() throws Exception {183 String[] value = {"Cheese", "Peas"};184 Response response = new Response();185 response.setSessionId("bar");186 response.setValue(value);187 response.setStatus(1512);188 String json = new BeanToJsonConverter().convert(response);189 Response converted = new JsonToBeanConverter().convert(Response.class, json);190 assertEquals("bar", response.getSessionId());191 assertEquals(2, ((List<?>) converted.getValue()).size());192 assertEquals(1512, response.getStatus().intValue());193 }194 @Test195 public void testShouldConvertObjectsInArraysToMaps() throws Exception {196 Date date = new Date();197 Cookie cookie = new Cookie("foo", "bar", "localhost", "/rooted", date, true, true);198 String rawJson = new BeanToJsonConverter().convert(Collections.singletonList(cookie));199 List<?> list = new JsonToBeanConverter().convert(List.class, rawJson);200 Object first = list.get(0);201 assertTrue(first instanceof Map);202 Map<?,?> map = (Map<?,?>) first;203 assertMapEntry(map, "name", "foo");204 assertMapEntry(map, "value", "bar");205 assertMapEntry(map, "domain", "localhost");206 assertMapEntry(map, "path", "/rooted");207 assertMapEntry(map, "secure", true);208 assertMapEntry(map, "httpOnly", true);209 assertMapEntry(map, "expiry", TimeUnit.MILLISECONDS.toSeconds(date.getTime()));210 }211 private void assertMapEntry(Map<?,?> map, String key, Object expected) {212 assertTrue("Missing key: " + key, map.containsKey(key));213 assertEquals("Wrong value for key: " + key + ": " + map.get(key).getClass().getName(),214 expected, map.get(key));215 }216 @Test217 public void testShouldConvertAnArrayBackIntoAnArray() throws Exception {218 Exception e = new Exception();219 String converted = new BeanToJsonConverter().convert(e);220 Map<?,?> reconstructed = new JsonToBeanConverter().convert(Map.class, converted);221 List<?> trace = (List<?>) reconstructed.get("stackTrace");222 assertTrue(trace.get(0) instanceof Map);223 }224 @Test225 public void testShouldBeAbleToReconsituteASessionId() throws Exception {226 String json = new BeanToJsonConverter().convert(new SessionId("id"));227 SessionId sessionId = new JsonToBeanConverter().convert(SessionId.class, json);228 assertEquals("id", sessionId.toString());229 }230 @Test231 public void testShouldBeAbleToConvertACommand() throws Exception {232 SessionId sessionId = new SessionId("session id");233 Command original = new Command(sessionId, DriverCommand.NEW_SESSION,234 new HashMap<String, String>() {235 {236 put("food", "cheese");237 }238 });239 String raw = new BeanToJsonConverter().convert(original);240 Command converted = new JsonToBeanConverter().convert(Command.class, raw);241 assertEquals(sessionId.toString(), converted.getSessionId().toString());242 assertEquals(original.getName(), converted.getName());243 assertEquals(1, converted.getParameters().keySet().size());244 assertEquals("cheese", converted.getParameters().get("food"));245 }246 @Test247 public void testShouldConvertCapabilitiesToAMapAndIncludeCustomValues() throws Exception {248 Capabilities caps = new ImmutableCapabilities("furrfu", "fishy");249 String raw = new BeanToJsonConverter().convert(caps);250 Capabilities converted = new JsonToBeanConverter().convert(Capabilities.class, raw);251 assertEquals("fishy", converted.getCapability("furrfu"));252 }253 @Test254 public void testShouldParseCapabilitiesWithLoggingPreferences() throws Exception {255 JsonObject prefs = new JsonObject();256 prefs.addProperty("browser", "WARNING");257 prefs.addProperty("client", "DEBUG");258 prefs.addProperty("driver", "ALL");259 prefs.addProperty("server", "OFF");260 JsonObject caps = new JsonObject();261 caps.add(CapabilityType.LOGGING_PREFS, prefs);262 Capabilities converted = new JsonToBeanConverter()263 .convert(Capabilities.class, caps.toString());264 LoggingPreferences lp =265 (LoggingPreferences) converted.getCapability(CapabilityType.LOGGING_PREFS);266 assertNotNull(lp);267 assertEquals(Level.WARNING, lp.getLevel(LogType.BROWSER));268 assertEquals(Level.FINE, lp.getLevel(LogType.CLIENT));269 assertEquals(Level.ALL, lp.getLevel(LogType.DRIVER));270 assertEquals(Level.OFF, lp.getLevel(LogType.SERVER));271 }272 @Test273 public void testShouldNotParseQuotedJsonObjectsAsActualJsonObjects() {274 JsonObject inner = new JsonObject();275 inner.addProperty("color", "green");276 inner.addProperty("number", 123);277 JsonObject outer = new JsonObject();278 outer.addProperty("inner", inner.toString());279 String jsonStr = outer.toString();280 Object convertedOuter = new JsonToBeanConverter().convert(Map.class, jsonStr);281 assertThat(convertedOuter, instanceOf(Map.class));282 Object convertedInner = ((Map<?,?>) convertedOuter).get("inner");283 assertNotNull(convertedInner);284 assertThat(convertedInner, instanceOf(String.class));285 assertThat(convertedInner.toString(), equalTo(inner.toString()));286 }287 @Test288 public void shouldBeAbleToConvertASelenium3CommandToASelenium2Command() {289 SessionId expectedId = new SessionId("thisisakey");290 JsonObject rawJson = new JsonObject();291 // In selenium 2, the sessionId is an object. In selenium 3, it's a straight string.292 rawJson.addProperty("sessionId", expectedId.toString());293 rawJson.addProperty("name", "some command");294 rawJson.add("parameters", new JsonObject());295 String stringified = rawJson.toString();296 Command converted = new JsonToBeanConverter().convert(Command.class, stringified);297 assertEquals(expectedId, converted.getSessionId());298 }299 @Test300 public void testShouldCallFromJsonMethodIfPresent() {301 JsonAware res = new JsonToBeanConverter().convert(JsonAware.class, "converted");302 assertEquals("converted", res.convertedValue);303 }304 // Test for issue 8187305 @Test306 public void testDecodingResponseWithNumbersInValueObject() {307 Response response = new JsonToBeanConverter()308 .convert(Response.class, "{\"status\":0,\"value\":{\"width\":96,\"height\":46.19140625}}");309 @SuppressWarnings("unchecked")310 Map<String, Number> value = (Map<String, Number>) response.getValue();311 assertEquals(96, value.get("width").intValue());312 assertEquals(46, value.get("height").intValue());313 assertEquals(46.19140625, value.get("height").doubleValue(), 0.00001);314 }315 @Test316 public void testShouldRecognizeNumericStatus() {317 Response response = new JsonToBeanConverter()318 .convert(Response.class, "{\"status\":0,\"value\":\"cheese\"}");319 assertEquals(0, response.getStatus().intValue());320 Assert.assertEquals(new ErrorCodes().toState(0), response.getState());321 String value = (String) response.getValue();322 assertEquals("cheese", value);323 }324 @Test325 public void testShouldRecognizeStringStatus() {326 Response response = new JsonToBeanConverter()327 .convert(Response.class, "{\"status\":\"success\",\"value\":\"cheese\"}");328 assertEquals(0, response.getStatus().intValue());329 assertEquals(new ErrorCodes().toState(0), response.getState());330 String value = (String) response.getValue();331 assertEquals("cheese", value);332 }333 @Test334 public void testShouldConvertInvalidSelectorError() {335 Response response = new JsonToBeanConverter()336 .convert(Response.class, "{\"state\":\"invalid selector\",\"message\":\"invalid xpath selector\"}");337 assertEquals(32, response.getStatus().intValue());338 assertEquals(new ErrorCodes().toState(32), response.getState());339 }340 @Test341 public void testShouldRecognizeStringState() {342 Response response = new JsonToBeanConverter()343 .convert(Response.class, "{\"state\":\"success\",\"value\":\"cheese\"}");344 assertEquals("success", response.getState());345 assertEquals(0, response.getStatus().intValue());346 String value = (String) response.getValue();347 assertEquals("cheese", value);348 }349 @Test350 public void testNoStatusShouldBeNullInResponseObject() {351 Response response = new JsonToBeanConverter()352 .convert(Response.class, "{\"value\":\"cheese\"}");353 assertNull(response.getStatus());354 }355 @Test356 public void canConvertAnEnumWithALowerCaseValue() {357 Proxy.ProxyType type = new JsonToBeanConverter().convert(Proxy.ProxyType.class, "pac");358 assertEquals(Proxy.ProxyType.PAC, type);359 }360 public static class SimpleBean {361 private String value;362 public String getValue() {363 return value;364 }365 public void setValue(String value) {366 this.value = value;367 }368 }369 public static class ContainingBean {370 private String name;371 private SimpleBean bean;372 public String getName() {373 return name;374 }375 public void setName(String name) {376 this.name = name;377 }378 public SimpleBean getBean() {379 return bean;380 }381 public void setBean(SimpleBean bean) {382 this.bean = bean;383 }384 }385 public static class JsonAware {386 private String convertedValue;387 public JsonAware(String convertedValue) {388 this.convertedValue = convertedValue;389 }390 public static JsonAware fromJson(String json) {391 return new JsonAware(json);392 }393 }394}...
Source:BasicFitRest.java
1package es.qopuir.basicfitbot.back;2import java.io.IOException;3import java.time.LocalDate;4import java.time.format.DateTimeFormatter;5import java.util.ArrayList;6import java.util.List;7import java.util.Locale;8import java.util.stream.IntStream;9import org.openqa.selenium.By;10import org.openqa.selenium.Dimension;11import org.openqa.selenium.JavascriptExecutor;12import org.openqa.selenium.OutputType;13import org.openqa.selenium.Proxy;14import org.openqa.selenium.Proxy.ProxyType;15import org.openqa.selenium.TakesScreenshot;16import org.openqa.selenium.WebDriver;17import org.openqa.selenium.WebElement;18import org.openqa.selenium.phantomjs.PhantomJSDriver;19import org.openqa.selenium.phantomjs.PhantomJSDriverService;20import org.openqa.selenium.remote.CapabilityType;21import org.openqa.selenium.remote.DesiredCapabilities;22import org.slf4j.Logger;23import org.slf4j.LoggerFactory;24import org.springframework.beans.factory.annotation.Autowired;25import org.springframework.stereotype.Component;26import org.springframework.util.LinkedMultiValueMap;27import org.springframework.util.MultiValueMap;28import org.springframework.web.util.UriComponents;29import org.springframework.web.util.UriComponentsBuilder;30import es.qopuir.basicfitbot.back.PhantomjsDownloader.Version;31@Component32public class BasicFitRest {33 private static final Logger LOG = LoggerFactory.getLogger(BasicFitRest.class);34 private static final String BASICFIT_TIMETABLE_BASEURL = "https://portal.virtuagym.com/classes/week/{day}";35 private static final MultiValueMap<String, String> BASICFIT_TIMETABLE_PARAMS = new LinkedMultiValueMap<String, String>();36 static {37 BASICFIT_TIMETABLE_PARAMS.add("event_type", "1");38 BASICFIT_TIMETABLE_PARAMS.add("coach", "0");39 BASICFIT_TIMETABLE_PARAMS.add("activity_id", "0");40 BASICFIT_TIMETABLE_PARAMS.add("member_id_filter", "0");41 BASICFIT_TIMETABLE_PARAMS.add("embedded", "1");42 BASICFIT_TIMETABLE_PARAMS.add("planner_type", "7");43 BASICFIT_TIMETABLE_PARAMS.add("show_personnel_schedule", "");44 BASICFIT_TIMETABLE_PARAMS.add("in_app", "0");45 BASICFIT_TIMETABLE_PARAMS.add("pref_club", "10560");46 BASICFIT_TIMETABLE_PARAMS.add("embedded", "1");47 }48 private final ProxyProperties proxyProperties;49 @Autowired50 public BasicFitRest(ProxyProperties proxyProperties) {51 this.proxyProperties = proxyProperties;52 }53 public enum Mode {54 TODAY, WEEK;55 }56 private String getUrl() {57 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");58 LocalDate today = LocalDate.now();59 UriComponents uri = UriComponentsBuilder.fromHttpUrl(BASICFIT_TIMETABLE_BASEURL)60 .queryParams(BASICFIT_TIMETABLE_PARAMS).buildAndExpand(today.format(formatter));61 return uri.toUriString();62 }63 64 /**65 * Returns today in short format (ex: Wed 27 Apr)66 * 67 * @return today in short format (ex: Wed 27 Apr)68 */69 private String getTodayShort() {70 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd MMM").withLocale(Locale.ENGLISH);71 72 LocalDate today = LocalDate.now();73 74 return today.format(formatter);75 }76 77 /**78 * Returns today in long format (ex: Wednesday 27 Apr)79 * 80 * @return today in long format (ex: Wednesday 27 Apr)81 */82 private String getTodayLong() {83 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE dd MMM").withLocale(Locale.ENGLISH);84 85 LocalDate today = LocalDate.now();86 87 return today.format(formatter);88 }89 public byte[] getBasicFitTimetable() throws IOException {90 return getBasicFitTimetable(Mode.TODAY);91 }92 public DesiredCapabilities getDriverCapabilities() {93 DesiredCapabilities capabilities = new DesiredCapabilities();94 if (proxyProperties.isEnabled()) {95 Proxy proxy = new Proxy();96 proxy.setProxyType(ProxyType.MANUAL).setHttpProxy(proxyProperties.getHostPort())97 .setSslProxy(proxyProperties.getHostPort()).setNoProxy("localhost, 127.0.0.1");98 capabilities.setCapability(CapabilityType.PROXY, proxy);99 }100 capabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true);101 102 capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,103 PhantomjsDownloader.download(Version.V_2_1_1, proxyProperties).getAbsolutePath());104 return capabilities;105 }106 // @Cacheable("idealistaBuildingHtmlRequest")107 public byte[] getBasicFitTimetable(Mode mode) throws IOException {108 WebDriver driver = new PhantomJSDriver(getDriverCapabilities());109 // driver.manage().window().setSize(new Dimension(1920, 1773));110 driver.manage().window().setSize(new Dimension(350, 1773));111 driver.get(getUrl());112 if (driver instanceof JavascriptExecutor) {113 final JavascriptExecutor js = (JavascriptExecutor) driver;114 driver.findElement(By.id("head")).findElements(By.tagName("a")).forEach((e) -> {115 js.executeScript("arguments[0].parentNode.removeChild(arguments[0])", e);116 });117 List<Integer> deletedColumnIndex = new ArrayList<Integer>();118 List<WebElement> titleColumns = driver.findElement(By.id("schedule_header"))119 .findElements(By.tagName("div"));120 IntStream.range(0, titleColumns.size()).forEach((i) -> {121 long todaySpans = titleColumns.get(i).findElements(By.tagName("span")).stream().filter((e) -> {122 return !e.getText().equalsIgnoreCase(getTodayShort())123 && !e.getText().equalsIgnoreCase(getTodayLong());124 }).count();125 if (todaySpans > 1) {126 js.executeScript("arguments[0].parentNode.removeChild(arguments[0])", titleColumns.get(i));127 deletedColumnIndex.add(i);128 }129 });130 List<WebElement> contentColumns = driver.findElement(By.id("schedule_content"))131 .findElements(By.className("cal_column"));132 IntStream.range(0, contentColumns.size()).forEach((i) -> {133 if (deletedColumnIndex.contains(i)) {134 js.executeScript("arguments[0].parentNode.removeChild(arguments[0])", contentColumns.get(i));135 }136 });137 }138 byte[] screenshot = takeScreenshot(driver);139 driver.close();140 return screenshot;141 }142 private byte[] takeScreenshot(WebDriver driver) throws IOException {143 return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);144 }145}...
Source:WebDriverFactory.java
1package cn.datarx.automation.helpers;2import org.apache.commons.lang3.StringUtils;3import org.apache.log4j.Logger;4import org.openqa.selenium.Proxy;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.ie.InternetExplorerDriver;9import org.openqa.selenium.phantomjs.PhantomJSDriver;10import org.openqa.selenium.remote.DesiredCapabilities;11import org.openqa.selenium.remote.RemoteWebDriver;12import java.io.IOException;13import java.net.MalformedURLException;14import java.net.URL;15import java.nio.file.Files;16import java.nio.file.Path;17import java.nio.file.Paths;18import java.util.*;19import java.util.stream.Collectors;20import static org.openqa.selenium.Proxy.ProxyType.MANUAL;21import static org.openqa.selenium.remote.CapabilityType.PROXY;22/**23 * Created by lining on 2017/7/2.24 */25final class WebDriverFactory {26 private static Logger logger = Logger.getLogger(WebDriverFactory.class);27 private static Map<String, String> binaries;28 private WebDriverFactory() {29 }30 static {31 binaries = new HashMap<>();32 for (BinaryType binaryType : BinaryType.values()) {33 for (String filename : binaryType.getBinaryFilenames()) {34 binaries.put(filename, binaryType.getDriverSystemProperty());35 }36 }37 }38 private static void initEnv() {39 String directory = Env.getProperty("binary.directory", "selenium_standalone");40 try {41 Path dir = Paths.get(directory);42 logger.debug("binary directory:" + dir.toAbsolutePath().toString());43 Files.walk(dir)44 .filter(path -> Files.isRegularFile(path))45 .forEach(path -> {46 String filename = path.getFileName().toString();47 if (binaries.containsKey(filename)) {48 String binaryPath = path.toAbsolutePath().toString();49 System.setProperty(binaries.get(filename), binaryPath);50 logger.debug("set system property:" + binaryPath);51 }52 });53 } catch (IOException e) {54 logger.error(e);55 }56 }57 static WebDriver create() {58 initEnv();59 String webDriverProperty = Env.getProperty("webdriver");60 if (webDriverProperty == null || webDriverProperty.isEmpty()) {61 throw new IllegalStateException("The webdriver system property must be set");62 }63 try {64 Proxy proxy = null;65 if (Boolean.valueOf(Env.getProperty("proxy.enable", "false"))) {66 String proxyDetails = String.format("%s:%d", Env.getProperty("proxy.host"), Integer.valueOf(Env.getProperty("proxy.port")));67 proxy = new Proxy();68 proxy.setProxyType(MANUAL);69 proxy.setHttpProxy(proxyDetails);70 proxy.setSslProxy(proxyDetails);71 }72 return Drivers.valueOf(webDriverProperty.toUpperCase()).newDriver(proxy, Env.getProperty("remote.hub"));73 } catch (Exception e) {74 String msg = String.format("The webdriver system property '%s' did not match any " +75 "existing browser or the browser was not supported on your operating system. " +76 "Valid values are %s",77 webDriverProperty, Arrays.stream(Drivers78 .values())79 .map(Enum::name)80 .map(String::toLowerCase)81 .collect(Collectors.toList()));82 throw new RuntimeException(msg, e);83 }84 }85 private enum Drivers {86 FIREFOX {87 @Override88 public WebDriver newDriver(Proxy proxy, String hub) throws MalformedURLException {89 DesiredCapabilities capabilities = DesiredCapabilities.firefox();90 if (proxy != null) {91 capabilities.setCapability(PROXY, proxy);92 }93 return StringUtils.isEmpty(hub) ? new FirefoxDriver(capabilities) : new RemoteWebDriver(new URL(hub), capabilities);94 }95 }, CHROME {96 @Override97 public WebDriver newDriver(Proxy proxy, String hub) throws MalformedURLException {98 DesiredCapabilities capabilities = DesiredCapabilities.chrome();99 if (proxy != null) {100 capabilities.setCapability(PROXY, proxy);101 }102 return StringUtils.isEmpty(hub) ? new ChromeDriver(capabilities) : new RemoteWebDriver(new URL(hub), capabilities);103 }104 }, PHANTOMJS {105 @Override106 public WebDriver newDriver(Proxy proxy, String hub) throws MalformedURLException {107 DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();108 if (proxy != null) {109 List<String> cliArguments = new ArrayList<>();110 cliArguments.add("--proxy-type=http");111 cliArguments.add("--proxy=" + proxy.getHttpProxy());112 capabilities.setCapability("phantomjs.cli.args", cliArguments);113 }114 return StringUtils.isEmpty(hub) ? new PhantomJSDriver(capabilities) : new RemoteWebDriver(new URL(hub), capabilities);115 }116 }, IE {117 @Override118 public WebDriver newDriver(Proxy proxy, String hub) throws MalformedURLException {119 DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();120 if (proxy != null) {121 capabilities.setCapability(PROXY, proxy);122 }123 return StringUtils.isEmpty(hub) ? new InternetExplorerDriver(capabilities) : new RemoteWebDriver(new URL(hub), capabilities);124 }125 };126 public abstract WebDriver newDriver(Proxy proxy, String hub) throws MalformedURLException;127 }128}...
Source:WebDriverProvider.java
1package com.ptb.uranus.spider.common.webDriver;2import com.ptb.uranus.spider.common.utils.HttpUtil;3import org.openqa.selenium.Dimension;4import org.openqa.selenium.Proxy;5import org.openqa.selenium.phantomjs.PhantomJSDriver;6import org.openqa.selenium.phantomjs.PhantomJSDriverService;7import org.openqa.selenium.remote.DesiredCapabilities;8import java.util.ArrayList;9import java.util.List;10import java.util.concurrent.TimeUnit;11import java.util.logging.Level;12/**13 * Created by eric on 15/11/17.14 */15public class WebDriverProvider {16 public enum WebDriverType {17 Http,18 Sock,19 None,20 }21 /**22 * Load jquery string.23 *24 * @return the string25 */26 public static String loadJquery() {27 return "var oHead = document.getElementsByTagName('HEAD').item(0);\n" +28 "var oScript= document.createElement(\"script\");\n" +29 "oScript.type = \"text/javascript\";\n" +30 "oScript.src=\"http://libs.baidu.com/jquery/1.9.1/jquery.min.js\";\n" +31 "oHead.appendChild(oScript);";32 }33 private static Proxy getProxy(WebDriverType webDriverType) {34 Proxy proxy = new Proxy();35 try {36 switch (webDriverType) {37 case Http:38 proxy.setHttpProxy(HttpUtil.getProxy("http").replace("http://", ""));39 break;40 case Sock:41 proxy.setSocksProxy(HttpUtil.getProxy("sock"));42 break;43 default:44 return null;45 }46 } catch (Exception e) {47 return null;48 }49 return proxy;50 }51 /**52 * Create web driver phantom js driver.53 *54 * @param isNeedImage the is need image55 * @param isNeedCache the is need cache56 * @param useragent the useragent57 * @param proxyType58 * @return the phantom js driver59 */60 public static PhantomJSDriver createWebDriver(boolean isNeedImage, boolean isNeedCache, String useragent, WebDriverType proxyType) {61 DesiredCapabilities des = DesiredCapabilities.phantomjs();62 des.setCapability("phantomjs.page.settings.userAgent",63 useragent);64 des.setBrowserName("chrome");65 des.setCapability("webStorageEnabled", true);66 des.setCapability("locationContextEnabled", true);67 if (proxyType != null && proxyType != WebDriverType.None) {68 Proxy proxy = getProxy(proxyType);69 if(proxy != null) {70 des.setCapability("proxy", getProxy(proxyType));71 }72 }73 List<String> cliarg = new ArrayList<String>();74 cliarg.add("--ignore-ssl-errors=true");75 cliarg.add("--webdriver-loglevel=ERROR");76 des.setCapability(77 PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliarg);78 if (isNeedCache) {79 cliarg.add("--disk-cache=true");80 cliarg.add("--max-disk-cache-size=1000000");81/* cliarg.add("--disk-cache-path=/tmp/");*/82 } else {83 cliarg.add("--disk-cache=false");84 }85 if (isNeedImage) {86 cliarg.add("--load-images=true");87 } else {88 cliarg.add("--load-images=false");89 }90 des.setCapability("phantomjs.cli.args", cliarg);91 PhantomJSDriver driver = new PhantomJSDriver(des);92 driver.setLogLevel(Level.INFO);93 driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);94 driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);95 driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);96 driver.manage().window().setSize(new Dimension(1024, 768));97 return driver;98 }99 /**100 * Create pc web driver phantom js driver.101 *102 * @param isNeedImage the is need image103 * @param isNeedCache the is need cache104 * @return the phantom js driver105 */106 public static PhantomJSDriver createPcWebDriver(boolean isNeedImage, boolean isNeedCache) {107 return createWebDriver(isNeedImage, isNeedCache, HttpUtil.UA_PC_CHROME, WebDriverType.Http);108 }109 /**110 * Create mobile web driver phantom js driver.111 *112 * @param isNeedImage the is need image113 * @param isNeedCache the is need cache114 * @return the phantom js driver115 */116 public static PhantomJSDriver createMobileWebDriver(boolean isNeedImage, boolean isNeedCache) {117 return createWebDriver(isNeedImage, isNeedCache, HttpUtil.UA_IPHONE6_SAFARI, WebDriverType.Http);118 }119}...
Source:DriverSelector.java
1package selenium.config;2import org.openqa.selenium.Platform;3import org.openqa.selenium.Proxy;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.remote.DesiredCapabilities;6import org.openqa.selenium.remote.RemoteWebDriver;7import java.net.MalformedURLException;8import java.net.URL;9import static org.openqa.selenium.Proxy.ProxyType.MANUAL;10import static selenium.config.DriverEnum.CHROME;11import static selenium.config.DriverEnum.valueOf;12public class DriverSelector {13 private WebDriver webdriver;14 private DriverEnum selectedDriverType;15 private final DriverEnum defaultDriverType = CHROME;16 private final String browser = System.getProperty("browser", defaultDriverType.toString()).toUpperCase();17 private final String operatingSystem = System.getProperty("os.name").toUpperCase();18 private final String systemArchitecture = System.getProperty("os.arch");19 private final boolean useRemoteWebDriver = Boolean.getBoolean("remoteDriver");20 private final boolean proxyEnabled = Boolean.getBoolean("proxyEnabled");21 private final String proxyHostname = System.getProperty("proxyHost");22 private final Integer proxyPort = Integer.getInteger("proxyPort");23 private final String proxyDetails = String.format("%s:%d", proxyHostname, proxyPort);24 public WebDriver getDriver() throws Exception {25 if (null == webdriver) {26 Proxy proxy = null;27 if (proxyEnabled) {28 proxy = new Proxy();29 proxy.setProxyType(MANUAL);30 proxy.setHttpProxy(proxyDetails);31 proxy.setSslProxy(proxyDetails);32 }33 determineEffectiveDriverType();34 DesiredCapabilities desiredCapabilities = selectedDriverType.getDesiredCapabilities(proxy);35 instantiateWebDriver(desiredCapabilities);36 }37 return webdriver;38 }39 public void quitDriver() {40 if (null != webdriver) {41 webdriver.quit();42 }43 }44 private void determineEffectiveDriverType() {45 DriverEnum driverType = defaultDriverType;46 try {47 driverType = valueOf(browser);48 } catch (IllegalArgumentException ignored) {49 System.err.println("Unknown driver specified, defaulting to '" + driverType + "'...");50 } catch (NullPointerException ignored) {51 System.err.println("No driver specified, defaulting to '" + driverType + "'...");52 }53 selectedDriverType = driverType;54 }55 private void instantiateWebDriver(DesiredCapabilities desiredCapabilities) throws MalformedURLException {56 System.out.println(" ");57 System.out.println("Current Operating System: " + operatingSystem);58 System.out.println("Current Architecture: " + systemArchitecture);59 System.out.println("Current Browser Selection: " + selectedDriverType);60 System.out.println(" ");61 if (useRemoteWebDriver) {62 URL seleniumGridURL = new URL(System.getProperty("gridURL"));63 String desiredBrowserVersion = System.getProperty("desiredBrowserVersion");64 String desiredPlatform = System.getProperty("desiredPlatform");65 if (null != desiredPlatform && !desiredPlatform.isEmpty()) {66 desiredCapabilities.setPlatform(Platform.valueOf(desiredPlatform.toUpperCase()));67 }68 if (null != desiredBrowserVersion && !desiredBrowserVersion.isEmpty()) {69 desiredCapabilities.setVersion(desiredBrowserVersion);70 }71 webdriver = new RemoteWebDriver(seleniumGridURL, desiredCapabilities);72 } else {73 webdriver = selectedDriverType.getWebDriverObject(desiredCapabilities);74 }75 }76}...
Source:LocalBrowserFactory.java
1package com.epam.traning.tds_test.runner;2import java.net.InetAddress;3import java.net.UnknownHostException;4import org.apache.log4j.Logger;5import org.openqa.selenium.Proxy;6import org.openqa.selenium.ie.InternetExplorerDriver;7import org.openqa.selenium.remote.CapabilityType;8import org.openqa.selenium.remote.DesiredCapabilities;9import com.selenium.driver.DriverTypes;10import com.selenium.driver.factory.WebDriverFactory;11import com.selenium.driver.factory.impl.FirefoxDriverFactory;12import com.selenium.driver.factory.impl.chrome.ChromeDriverFactory;13import com.selenium.driver.factory.impl.ie.IEDriverFactory;14import com.thoughtworks.selenium.SeleniumException;15public class LocalBrowserFactory {16 private static final String CHROME_DRIVER_LOCAL_PATH = "exec/chrome/chromedriver.exe";17 private static final String IE_DRIVER_LOCAL_PATH = "exec/ie/IEDriverServer.exe";18 private static final Logger LOGGER = Logger.getLogger(LocalBrowserFactory.class);19 private static ThreadLocal<WebDriverFactory> currWDFactory = new ThreadLocal<WebDriverFactory>();20 public static synchronized WebDriverFactory createLocalFactory(DriverTypes driverTypes, int port) {21 DesiredCapabilities caps = new DesiredCapabilities();22 if ((port != -1)) {23 try {24 caps.setCapability(CapabilityType.PROXY, seleniumProxy(port));25 LOGGER.info("Port for selenium proxy: " + port);26 } catch (UnknownHostException e) {27 throw new SeleniumException(e.getMessage(), e);28 }29 }30 WebDriverFactory wdf;31 switch (driverTypes.getDriverType()) {32 case "firefox":33 wdf = new FirefoxDriverFactory(caps, port);34 currWDFactory.set(wdf);35 return wdf;36 case "googlechrome":37 wdf = new ChromeDriverFactory(caps, CHROME_DRIVER_LOCAL_PATH, port);38 currWDFactory.set(wdf);39 return wdf;40 case "iexplore":41 caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);42 wdf = new IEDriverFactory(caps, IE_DRIVER_LOCAL_PATH, port);43 currWDFactory.set(wdf);44 return wdf;45 default:46 throw new EnumConstantNotPresentException(DriverTypes.class, "There is no rules for " + driverTypes.getDriverType());47 }48 }49 /**50 * Configure selenium proxy if needed51 * 52 * @param port53 * @return proxy54 * @throws UnknownHostException55 */56 private static synchronized Proxy seleniumProxy(int port) throws UnknownHostException {57 Proxy proxy = new Proxy();58 proxy.setProxyType(Proxy.ProxyType.MANUAL);59 String proxyStr = String.format("%s:%d", InetAddress.getLocalHost().getCanonicalHostName(), port);60 proxy.setHttpProxy(proxyStr);61 proxy.setSslProxy(proxyStr);62 return proxy;63 }64 public static WebDriverFactory getCurrentWebDriverFactory() {65 return currWDFactory.get();66 }67}...
Source:ProxyProvider.java
1package LocalizationTestingPackage;2import org.openqa.selenium.Proxy;3import org.openqa.selenium.Proxy.ProxyType;4import org.openqa.selenium.remote.CapabilityType;5import org.openqa.selenium.remote.DesiredCapabilities;6public abstract class ProxyProvider {7 public static enum ProxyLocation {NONE, US, BRAZIL, ARGENTINA, INDONESIA, CHINA, 8 RUSSIA, SOUTH_AFRICA, JAPAN, FRANCE, ITALY,MEXICO, SINGAPORE};//, BRAZIL_CELLULAR_OI, BRAZIL_CELLULAR_WIND};9 public static void setProxyCapabilities(DesiredCapabilities capabilities, ProxyLocation location){10 if (ProxyLocation.NONE == location || null == location) return;11 String httpProxy = getProxyString(location);12 Proxy proxy = new Proxy();13 proxy.setProxyType(ProxyType.MANUAL);14 proxy.setHttpProxy(httpProxy);15 proxy.setSslProxy(httpProxy);16 // proxy.setFtpProxy(ftpProxy);17 18 capabilities.setCapability(CapabilityType.PROXY, proxy);19 capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);20 }21 private static String getProxyString(ProxyLocation location){22 if (null == location) return "";23 switch (location){24 // from https://www.proxynova.com/proxy-server-list/country-us/25 case BRAZIL: return "";26 case US: return "71.199.12.18:8080";27 case ARGENTINA: return "181.47.53.129:3128";28 case INDONESIA: return "119.252.172.133:3128";29 case RUSSIA: return "46.16.226.10:8080";30 case CHINA: return "103.227.76.30:80";31 case SOUTH_AFRICA: return "";32 case JAPAN: return "218.46.23.23:8080";33 case FRANCE: return "37.187.119.226:3128";34 case ITALY: return "37.159.208.218:3128";35 case MEXICO: return "200.76.251.166:3128";36 case SINGAPORE: return "";37 default: 38 return "";39 }40 }41 public static ProxyLocation mapTestNGLocationToProxyLocation(String testNGLocation ){42 if (null == testNGLocation) return ProxyLocation.NONE;43 switch (testNGLocation.toLowerCase()){44 case "brazil": return ProxyLocation.BRAZIL;45 case "US": return ProxyLocation.US;46 case "argentina": return ProxyLocation.ARGENTINA;47 case "indonesia": return ProxyLocation.INDONESIA;48 case "russia": return ProxyLocation.RUSSIA;49 case "china": return ProxyLocation.CHINA;50 case "south africa": return ProxyLocation.SOUTH_AFRICA;51 case "japan": return ProxyLocation.JAPAN;52 case "france": return ProxyLocation.FRANCE;53 case "italy": return ProxyLocation.ITALY;54 case "mexico": return ProxyLocation.MEXICO;55 case "singapore": return ProxyLocation.SINGAPORE;56 default: 57 return ProxyLocation.NONE;58 }59 }60}...
Enum Proxy.ProxyType
Using AI Code Generation
1import org.openqa.selenium.Proxy.ProxyType2def proxy = new Proxy()3proxy.setProxyType(Proxy.ProxyType.MANUAL)4proxy.setHttpProxy("localhost:8080")5proxy.setSslProxy("localhost:8080")6proxy.setSocksProxy("localhost:8080")7proxy.setSocksUsername("username")8proxy.setSocksPassword("password")9proxy.setNoProxy("localhost,
Enum Proxy.ProxyType
Using AI Code Generation
1public enum ProxyType {2 DIRECT, MANUAL, PAC, AUTODETECT, SYSTEM;3}4public class Proxy {5 private String proxyType;6 private String httpProxy;7 private String ftpProxy;8 private String sslProxy;9 private String socksProxy;10 private String socksUsername;11 private String socksPassword;12 private boolean noProxy;13 private String proxyAutoconfigUrl;14 private Map<String, String> additionalCapabilities;15 private String socksVersion;16 private String socks5RemoteDns;17 private String autodetect;18 private String ftpProxyExcludeList;19 private String httpProxyExcludeList;20 private String proxyAutoconfigExcludeList;21 private String sslProxyExcludeList;22 private String socksProxyExcludeList;23 public Proxy() {24 this.proxyType = ProxyType.DIRECT.name();25 this.additionalCapabilities = new HashMap();26 }27 public Proxy(ProxyType proxyType) {28 this.proxyType = proxyType.name();29 this.additionalCapabilities = new HashMap();30 }31 public Proxy(String proxyType) {32 this.proxyType = proxyType;33 this.additionalCapabilities = new HashMap();34 }35 public static Proxy fromPac(String proxyAutoconfigUrl) {36 Proxy proxy = new Proxy(ProxyType.PAC);37 proxy.setProxyAutoconfigUrl(proxyAutoconfigUrl);38 return proxy;39 }40 public static Proxy fromAutoconfig(String proxyAutoconfigUrl) {41 Proxy proxy = new Proxy(ProxyType.AUTODETECT);42 proxy.setProxyAutoconfigUrl(proxyAutoconfigUrl);43 return proxy;44 }45 public static Proxy fromAutoconfig(String proxyAutoconfigUrl, String proxyAutoconfigExcludeList) {46 Proxy proxy = new Proxy(ProxyType.AUTODETECT);47 proxy.setProxyAutoconfigUrl(proxyAutoconfigUrl);48 proxy.setProxyAutoconfigExcludeList(proxyAutoconfigExcludeList);49 return proxy;50 }51 public static Proxy fromAutoconfig(String proxyAutoconfigUrl, String proxyAutoconfigExcludeList, String ftpProxy, String ftpProxyExcludeList, String httpProxy, String httpProxyExcludeList, String noProxy, String sslProxy, String sslProxyExcludeList, String socksProxy, String socksProxyExcludeList) {52 Proxy proxy = new Proxy(ProxyType.AUTODETECT);53 proxy.setProxyAutoconfigUrl(proxyAutoconfigUrl);
Enum Proxy.ProxyType
Using AI Code Generation
1Proxy.ProxyType proxyType = Proxy.ProxyType.valueOf("MANUAL");2Proxy proxy = new Proxy();3proxy.setProxyType(proxyType);4DesiredCapabilities capabilities = DesiredCapabilities.chrome();5capabilities.setCapability(CapabilityType.PROXY, proxy);6WebDriver driver = new ChromeDriver(capabilities);7driver.quit();8package com.automation.selenium.proxy; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class Example3 { public static void main(String[] args)
Enum Proxy.ProxyType
Using AI Code Generation
1public void proxyTest() throws Exception {2 Proxy proxy = new Proxy();3 proxy.setProxyType(Proxy.ProxyType.MANUAL);4 proxy.setHttpProxy("proxy-server:port");5 proxy.setSslProxy("proxy-server:port");6 DesiredCapabilities capabilities = new DesiredCapabilities();7 capabilities.setCapability(CapabilityType.PROXY, proxy);8 WebDriver driver = new FirefoxDriver(capabilities);9 Thread.sleep(5000);10 driver.quit();11}12public void proxyTest() throws Exception {13 Proxy proxy = new Proxy();14 proxy.setProxyType(Proxy.ProxyType.MANUAL);15 proxy.setHttpProxy("proxy-server:port");16 proxy.setSslProxy("proxy-server:port");17 DesiredCapabilities capabilities = new DesiredCapabilities();18 capabilities.setCapability(CapabilityType.PROXY, proxy);19 WebDriver driver = new FirefoxDriver(capabilities);20 Thread.sleep(5000);21 driver.quit();22}23public void proxyTest() throws Exception {24 Proxy proxy = new Proxy();25 proxy.setProxyType(Proxy.ProxyType.M
Enum Proxy.ProxyType
Using AI Code Generation
1package org.example;2import org.openqa.selenium.Proxy;3import org.openqa.selenium.chrome.ChromeDriver;4public class TestProxy {5 public static void main(String[] args) {6 System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\selenium\\chromedriver.exe");7 Proxy proxy = new Proxy();8 proxy.setProxyType(Proxy.ProxyType.SYSTEM);9 ChromeDriver driver = new ChromeDriver(proxy);10 System.out.println(driver.getTitle());11 driver.quit();12 }13}14package org.example;15import org.openqa.selenium.Proxy;16import org.openqa.selenium.chrome.ChromeDriver;17public class TestProxy {18 public static void main(String[] args) {19 System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\selenium\\chromedriver.exe");20 Proxy proxy = new Proxy();21 proxy.proxyType(Proxy.ProxyType.SYSTEM);22 ChromeDriver driver = new ChromeDriver(proxy);23 System.out.println(driver.getTitle());24 driver.quit();25 }26}27package org.example;28import org.openqa.selenium.Proxy;29import org.openqa.selenium.chrome.ChromeDriver;30public class TestProxy {31 public static void main(String[] args) {32 System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\selenium\\chromedriver.exe");
Enum Proxy.ProxyType
Using AI Code Generation
1import org.openqa.selenium.Proxy;2import org.openqa.selenium.Proxy.ProxyType;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.chrome.ChromeOptions;6import org.openqa.selenium.remote.CapabilityType;7public class ProxyTypeTest {8 public static void main(String[] args) {9 System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");10 WebDriver driver = new ChromeDriver();11 Proxy proxy = new Proxy();12 proxy.setProxyType(ProxyType.MANUAL);
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!!