How to use Interface Capabilities class of org.openqa.selenium package

Best Selenium code snippet using org.openqa.selenium.Interface Capabilities

Source:BaseAugmenterTest.java Github

copy

Full Screen

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.remote;18import static org.junit.Assert.assertEquals;19import static org.junit.Assert.assertFalse;20import static org.junit.Assert.assertNotSame;21import static org.junit.Assert.assertSame;22import static org.junit.Assert.assertTrue;23import static org.junit.Assert.fail;24import static org.mockito.Mockito.mock;25import com.google.common.collect.ImmutableMap;26import org.junit.Test;27import org.openqa.selenium.By;28import org.openqa.selenium.Capabilities;29import org.openqa.selenium.HasCapabilities;30import org.openqa.selenium.ImmutableCapabilities;31import org.openqa.selenium.NoSuchElementException;32import org.openqa.selenium.Rotatable;33import org.openqa.selenium.ScreenOrientation;34import org.openqa.selenium.TakesScreenshot;35import org.openqa.selenium.WebDriver;36import org.openqa.selenium.WebElement;37import java.util.ArrayList;38import java.util.HashMap;39import java.util.List;40import java.util.Map;41public abstract class BaseAugmenterTest {42 @Test43 public void shouldReturnANormalWebDriverUntouched() {44 WebDriver driver = mock(WebDriver.class);45 WebDriver returned = getAugmenter().augment(driver);46 assertSame(driver, returned);47 }48 @Test49 public void shouldAddInterfaceFromCapabilityIfNecessary() {50 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);51 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);52 BaseAugmenter augmenter = getAugmenter();53 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());54 WebDriver returned = augmenter.augment(driver);55 assertNotSame(driver, returned);56 assertTrue(returned instanceof TakesScreenshot);57 }58 @Test59 public void shouldNotAddInterfaceWhenBooleanValueForItIsFalse() {60 Capabilities caps = new ImmutableCapabilities("magic.numbers", false);61 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);62 BaseAugmenter augmenter = getAugmenter();63 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());64 WebDriver returned = augmenter.augment(driver);65 assertSame(driver, returned);66 assertFalse(returned instanceof MagicNumberHolder);67 }68 @Test69 public void shouldDelegateToHandlerIfAdded() {70 Capabilities caps = new ImmutableCapabilities("foo", true);71 BaseAugmenter augmenter = getAugmenter();72 augmenter.addDriverAugmentation("foo", new AugmenterProvider() {73 public Class<?> getDescribedInterface() {74 return MyInterface.class;75 }76 public InterfaceImplementation getImplementation(Object value) {77 return (executeMethod, self, method, args) -> "Hello World";78 }79 });80 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);81 WebDriver returned = augmenter.augment(driver);82 String text = ((MyInterface) returned).getHelloWorld();83 assertEquals("Hello World", text);84 }85 @Test86 public void shouldDelegateUnmatchedMethodCallsToDriverImplementation() {87 Capabilities caps = new ImmutableCapabilities("magic.numbers", true);88 StubExecutor stubExecutor = new StubExecutor(caps);89 stubExecutor.expect(DriverCommand.GET_TITLE, new HashMap<>(), "Title");90 WebDriver driver = new RemoteWebDriver(stubExecutor, caps);91 BaseAugmenter augmenter = getAugmenter();92 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());93 WebDriver returned = augmenter.augment(driver);94 assertEquals("Title", returned.getTitle());95 }96 @Test(expected = NoSuchElementException.class)97 public void proxyShouldNotAppearInStackTraces() {98 // This will force the class to be enhanced99 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);100 DetonatingDriver driver = new DetonatingDriver();101 driver.setCapabilities(caps);102 BaseAugmenter augmenter = getAugmenter();103 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());104 WebDriver returned = augmenter.augment(driver);105 returned.findElement(By.id("ignored"));106 }107 @Test108 public void shouldLeaveAnUnAugmentableElementAlone() {109 RemoteWebElement element = new RemoteWebElement();110 element.setId("1234");111 WebElement returned = getAugmenter().augment(element);112 assertSame(element, returned);113 }114 @Test115 public void shouldAllowAnElementToBeAugmented() throws Exception {116 RemoteWebElement element = new RemoteWebElement();117 element.setId("1234");118 BaseAugmenter augmenter = getAugmenter();119 augmenter.addElementAugmentation("foo", new AugmenterProvider() {120 public Class<?> getDescribedInterface() {121 return MyInterface.class;122 }123 public InterfaceImplementation getImplementation(Object value) {124 return (executeMethod, self, method, args) -> "Hello World";125 }126 });127 final Capabilities caps = new ImmutableCapabilities("foo", true);128 StubExecutor executor = new StubExecutor(caps);129 RemoteWebDriver parent = new RemoteWebDriver(executor, caps) {130 @Override131 public Capabilities getCapabilities() {132 return caps;133 }134 };135 element.setParent(parent);136 WebElement returned = augmenter.augment(element);137 assertTrue(returned instanceof MyInterface);138 executor.expect(DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", "1234"),139 null);140 returned.click();141 }142 @Test143 public void shouldCopyFieldsFromTemplateInstanceIntoChildInstance() {144 ChildRemoteDriver driver = new ChildRemoteDriver();145 driver.setMagicNumber(3);146 MagicNumberHolder holder = (MagicNumberHolder) getAugmenter().augment(driver);147 assertEquals(3, holder.getMagicNumber());148 }149 @Test150 public void shouldNotChokeOnFinalFields() {151 WithFinals withFinals = new WithFinals();152 try {153 getAugmenter().augment(withFinals);154 } catch (Exception e) {155 fail("This is not expected: " + e.getMessage());156 }157 }158 @Test159 public void shouldBeAbleToAugmentMultipleTimes() {160 Capabilities caps = new ImmutableCapabilities("canRotate", true, "magic.numbers", true);161 StubExecutor stubExecutor = new StubExecutor(caps);162 stubExecutor.expect(DriverCommand.GET_SCREEN_ORIENTATION,163 ImmutableMap.<String, Object>of(),164 ScreenOrientation.PORTRAIT.name());165 RemoteWebDriver driver = new RemoteWebDriver(stubExecutor, caps);166 BaseAugmenter augmenter = getAugmenter();167 augmenter.addDriverAugmentation("canRotate", new AddRotatable());168 WebDriver augmented = augmenter.augment(driver);169 assertNotSame(augmented, driver);170 assertTrue(augmented instanceof Rotatable);171 assertFalse(augmented instanceof MagicNumberHolder);172 augmenter = getAugmenter();173 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());174 WebDriver augmentedAgain = augmenter.augment(augmented);175 assertNotSame(augmentedAgain, augmented);176 assertTrue(augmentedAgain instanceof Rotatable);177 assertTrue(augmentedAgain instanceof MagicNumberHolder);178 ((Rotatable) augmentedAgain).getOrientation(); // Should not throw.179 assertSame(driver.getCapabilities(),180 ((HasCapabilities) augmentedAgain).getCapabilities());181 }182 protected static class StubExecutor implements CommandExecutor {183 private final Capabilities capabilities;184 private final List<Data> expected = new ArrayList<>();185 protected StubExecutor(Capabilities capabilities) {186 this.capabilities = capabilities;187 }188 public Response execute(Command command) {189 if (DriverCommand.NEW_SESSION.equals(command.getName())) {190 Response response = new Response(new SessionId("foo"));191 response.setValue(capabilities.asMap());192 return response;193 }194 for (Data possibleMatch : expected) {195 if (possibleMatch.commandName.equals(command.getName()) &&196 possibleMatch.args.equals(command.getParameters())) {197 Response response = new Response(new SessionId("foo"));198 response.setValue(possibleMatch.returnValue);199 return response;200 }201 }202 fail("Unexpected method invocation: " + command);203 return null; // never reached204 }205 public void expect(String commandName, Map<String, ?> args, Object returnValue) {206 expected.add(new Data(commandName, args, returnValue));207 }208 private static class Data {209 public String commandName;210 public Map<String, ?> args;211 public Object returnValue;212 public Data(String commandName, Map<String, ?> args, Object returnValue) {213 this.commandName = commandName;214 this.args = args;215 this.returnValue = returnValue;216 }217 }218 }219 public interface MyInterface {220 String getHelloWorld();221 }222 public static class DetonatingDriver extends RemoteWebDriver {223 private Capabilities caps;224 public void setCapabilities(Capabilities caps) {225 this.caps = caps;226 }227 @Override228 public Capabilities getCapabilities() {229 return caps;230 }231 @Override232 public WebElement findElementById(String id) {233 throw new NoSuchElementException("Boom");234 }235 }236 private interface MagicNumberHolder {237 public int getMagicNumber();238 public void setMagicNumber(int number);239 }240 public static class ChildRemoteDriver extends RemoteWebDriver implements MagicNumberHolder {241 private int magicNumber;242 @Override243 public Capabilities getCapabilities() {244 return DesiredCapabilities.firefox();245 }246 @Override247 public int getMagicNumber() {248 return magicNumber;249 }250 @Override251 public void setMagicNumber(int magicNumber) {252 this.magicNumber = magicNumber;253 }254 }255 public static class WithFinals extends RemoteWebDriver {256 public final String finalField = "FINAL";257 @Override258 public Capabilities getCapabilities() {259 return new ImmutableCapabilities();260 }261 }262 public abstract BaseAugmenter getAugmenter();263 private static class AddsMagicNumberHolder implements AugmenterProvider {264 @Override265 public Class<?> getDescribedInterface() {266 return MagicNumberHolder.class;267 }268 @Override269 public InterfaceImplementation getImplementation(Object value) {270 return (executeMethod, self, method, args) -> null;271 }272 }273}...

Full Screen

Full Screen

Source:Augmenter.java Github

copy

Full Screen

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.remote;18import net.bytebuddy.ByteBuddy;19import net.bytebuddy.description.annotation.AnnotationDescription;20import net.bytebuddy.dynamic.DynamicType;21import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;22import net.bytebuddy.implementation.FixedValue;23import net.bytebuddy.implementation.MethodDelegation;24import org.openqa.selenium.Beta;25import org.openqa.selenium.Capabilities;26import org.openqa.selenium.HasCapabilities;27import org.openqa.selenium.ImmutableCapabilities;28import org.openqa.selenium.WebDriver;29import org.openqa.selenium.WebDriverException;30import org.openqa.selenium.WrapsDriver;31import org.openqa.selenium.internal.Require;32import org.openqa.selenium.remote.html5.AddApplicationCache;33import org.openqa.selenium.remote.html5.AddLocationContext;34import org.openqa.selenium.remote.html5.AddWebStorage;35import org.openqa.selenium.remote.mobile.AddNetworkConnection;36import java.lang.reflect.Field;37import java.lang.reflect.Modifier;38import java.util.HashSet;39import java.util.List;40import java.util.ServiceLoader;41import java.util.Set;42import java.util.function.BiFunction;43import java.util.function.Predicate;44import java.util.stream.Collectors;45import java.util.stream.Stream;46import java.util.stream.StreamSupport;47import static java.util.Collections.unmodifiableSet;48import static net.bytebuddy.matcher.ElementMatchers.anyOf;49import static net.bytebuddy.matcher.ElementMatchers.named;50/**51 * Enhance the interfaces implemented by an instance of the52 * {@link org.openqa.selenium.WebDriver} based on the returned53 * {@link org.openqa.selenium.Capabilities} of the driver.54 *55 * Note: this class is still experimental. Use at your own risk.56 */57@Beta58public class Augmenter {59 private final Set<Augmentation<?>> augmentations;60 public Augmenter() {61 Set<Augmentation<?>> augmentations = new HashSet<>();62 Stream.of(63 new AddApplicationCache(),64 new AddLocationContext(),65 new AddNetworkConnection(),66 new AddRotatable(),67 new AddWebStorage()68 ).forEach(provider -> augmentations.add(createAugmentation(provider)));69 StreamSupport.stream(ServiceLoader.load(AugmenterProvider.class).spliterator(), false)70 .forEach(provider -> augmentations.add(createAugmentation(provider)));71 this.augmentations = unmodifiableSet(augmentations);72 }73 private static <X> Augmentation<X> createAugmentation(AugmenterProvider<X> provider) {74 Require.nonNull("Interface provider", provider);75 return new Augmentation<>(provider.isApplicable(),76 provider.getDescribedInterface(),77 provider::getImplementation);78 }79 private Augmenter(Set<Augmentation<?>> augmentations, Augmentation<?> toAdd) {80 Require.nonNull("Current list of augmentations", augmentations);81 Require.nonNull("Augmentation to add", toAdd);82 Set<Augmentation<?>> toUse = new HashSet<>(augmentations.size() + 1);83 toUse.addAll(augmentations);84 toUse.add(toAdd);85 this.augmentations = unmodifiableSet(toUse);86 }87 public <X> Augmenter addDriverAugmentation(AugmenterProvider<X> provider) {88 Require.nonNull("Interface provider", provider);89 return addDriverAugmentation(90 provider.isApplicable(),91 provider.getDescribedInterface(),92 provider::getImplementation);93 }94 public <X> Augmenter addDriverAugmentation(95 String capabilityName,96 Class<X> implementThis,97 BiFunction<Capabilities, ExecuteMethod, X> usingThis) {98 Require.nonNull("Capability name", capabilityName);99 Require.nonNull("Interface to implement", implementThis);100 Require.nonNull("Concrete implementation", usingThis, "of %s", implementThis);101 return addDriverAugmentation(check(capabilityName), implementThis, usingThis);102 }103 public <X> Augmenter addDriverAugmentation(104 Predicate<Capabilities> whenThisMatches,105 Class<X> implementThis,106 BiFunction<Capabilities, ExecuteMethod, X> usingThis) {107 Require.nonNull("Capability predicate", whenThisMatches);108 Require.nonNull("Interface to implement", implementThis);109 Require.nonNull("Concrete implementation", usingThis, "of %s", implementThis);110 Require.precondition(implementThis.isInterface(), "Expected %s to be an interface", implementThis);111 return new Augmenter(augmentations, new Augmentation<>(whenThisMatches, implementThis, usingThis));112 }113 private Predicate<Capabilities> check(String capabilityName) {114 return caps -> {115 Require.nonNull("Capability name", capabilityName);116 Object value = caps.getCapability(capabilityName);117 if (value instanceof Boolean && !((Boolean) value)) {118 return false;119 }120 return value != null;121 };122 }123 /**124 * Enhance the interfaces implemented by this instance of WebDriver iff that instance is a125 * {@link org.openqa.selenium.remote.RemoteWebDriver}.126 *127 * The WebDriver that is returned may well be a dynamic proxy. You cannot rely on the concrete128 * implementing class to remain constant.129 *130 * @param driver The driver to enhance131 * @return A class implementing the described interfaces.132 */133 public WebDriver augment(WebDriver driver) {134 Require.nonNull("WebDriver", driver);135 Require.precondition(driver instanceof HasCapabilities, "Driver must have capabilities", driver);136 Capabilities caps = ImmutableCapabilities.copyOf(((HasCapabilities) driver).getCapabilities());137 // Collect the interfaces to apply138 List<Augmentation<?>> matchingAugmenters = augmentations.stream()139 // Only consider the augmenters that match interfaces we don't already implement140 .filter(augmentation -> !augmentation.interfaceClass.isAssignableFrom(driver.getClass()))141 // And which match an augmentation we have142 .filter(augmentation -> augmentation.whenMatches.test(caps))143 .collect(Collectors.toList());144 if (matchingAugmenters.isEmpty()) {145 return driver;146 }147 // Grab a remote execution method, if possible148 RemoteWebDriver remote = extractRemoteWebDriver(driver);149 ExecuteMethod execute = remote == null ?150 (commandName, parameters) -> { throw new WebDriverException("Cannot execute remote command: " + commandName); } :151 new RemoteExecuteMethod(remote);152 DynamicType.Builder<? extends WebDriver> builder = new ByteBuddy()153 .subclass(driver.getClass())154 .annotateType(AnnotationDescription.Builder.ofType(Augmentable.class).build())155 .method(named("isAugmented")).intercept(FixedValue.value(true));156 for (Augmentation<?> augmentation : augmentations) {157 Class<?> iface = augmentation.interfaceClass;158 Object instance = augmentation.implementation.apply(caps, execute);159 builder = builder.implement(iface)160 .method(anyOf(iface.getDeclaredMethods()))161 .intercept(MethodDelegation.to(instance, iface));162 }163 Class<? extends WebDriver> definition = builder.make()164 .load(driver.getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)165 .getLoaded()166 .asSubclass(driver.getClass());167 try {168 WebDriver toReturn = definition.getDeclaredConstructor().newInstance();169 copyFields(driver.getClass(), driver, toReturn);170 return toReturn;171 } catch (ReflectiveOperationException e) {172 throw new IllegalStateException("Unable to create new proxy", e);173 }174 }175 private RemoteWebDriver extractRemoteWebDriver(WebDriver driver) {176 Require.nonNull("WebDriver", driver);177 if (driver instanceof RemoteWebDriver) {178 return (RemoteWebDriver) driver;179 }180 if (driver instanceof WrapsDriver) {181 return extractRemoteWebDriver(((WrapsDriver) driver).getWrappedDriver());182 }183 return null;184 }185 private void copyFields(Class<?> clazz, Object source, Object target) {186 if (Object.class.equals(clazz)) {187 // Stop!188 return;189 }190 for (Field field : clazz.getDeclaredFields()) {191 copyField(source, target, field);192 }193 copyFields(clazz.getSuperclass(), source, target);194 }195 private void copyField(Object source, Object target, Field field) {196 if (Modifier.isFinal(field.getModifiers())) {197 return;198 }199 try {200 field.setAccessible(true);201 Object value = field.get(source);202 field.set(target, value);203 } catch (IllegalAccessException e) {204 throw new RuntimeException(e);205 }206 }207 private static class Augmentation<X> {208 public final Predicate<Capabilities> whenMatches;209 public final Class<X> interfaceClass;210 public final BiFunction<Capabilities, ExecuteMethod, X> implementation;211 public Augmentation(212 Predicate<Capabilities> whenMatches,213 Class<X> interfaceClass,214 BiFunction<Capabilities, ExecuteMethod, X> implementation) {215 this.whenMatches = Require.nonNull("Capabilities predicate", whenMatches);216 this.interfaceClass = Require.nonNull("Interface to implement", interfaceClass);217 this.implementation = Require.nonNull("Interface implementation", implementation);218 Require.precondition(219 interfaceClass.isInterface(),220 "%s must be an interface, not a concrete class",221 interfaceClass);222 }223 }224}...

Full Screen

Full Screen

Source:UtilsTest.java Github

copy

Full Screen

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.remote.server.handler.html5;18import static org.junit.Assert.assertEquals;19import static org.junit.Assert.assertSame;20import static org.junit.Assert.fail;21import static org.mockito.Mockito.mock;22import static org.mockito.Mockito.reset;23import static org.mockito.Mockito.verify;24import static org.mockito.Mockito.when;25import com.google.common.collect.ImmutableMap;26import org.junit.Test;27import org.junit.runner.RunWith;28import org.junit.runners.JUnit4;29import org.openqa.selenium.HasCapabilities;30import org.openqa.selenium.UnsupportedCommandException;31import org.openqa.selenium.WebDriver;32import org.openqa.selenium.html5.AppCacheStatus;33import org.openqa.selenium.html5.ApplicationCache;34import org.openqa.selenium.html5.LocalStorage;35import org.openqa.selenium.html5.Location;36import org.openqa.selenium.html5.LocationContext;37import org.openqa.selenium.html5.SessionStorage;38import org.openqa.selenium.html5.WebStorage;39import org.openqa.selenium.remote.CapabilityType;40import org.openqa.selenium.remote.DesiredCapabilities;41import org.openqa.selenium.remote.DriverCommand;42import org.openqa.selenium.remote.ExecuteMethod;43/**44 * Tests for the {@link Utils} class.45 */46@RunWith(JUnit4.class)47public class UtilsTest {48 @Test49 public void returnsInputDriverIfRequestedFeatureIsImplementedDirectly() {50 WebDriver driver = mock(Html5Driver.class);51 assertSame(driver, Utils.getApplicationCache(driver));52 assertSame(driver, Utils.getLocationContext(driver));53 assertSame(driver, Utils.getWebStorage(driver));54 }55 @Test56 public void throwsIfRequestedFeatureIsNotSupported() {57 WebDriver driver = mock(WebDriver.class);58 try {59 Utils.getApplicationCache(driver);60 fail();61 } catch (UnsupportedCommandException expected) {62 // Do nothing.63 }64 try {65 Utils.getLocationContext(driver);66 fail();67 } catch (UnsupportedCommandException expected) {68 // Do nothing.69 }70 try {71 Utils.getWebStorage(driver);72 fail();73 } catch (UnsupportedCommandException expected) {74 // Do nothing.75 }76 }77 @Test78 public void providesRemoteAccessToAppCache() {79 DesiredCapabilities caps = new DesiredCapabilities();80 caps.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, true);81 CapableDriver driver = mock(CapableDriver.class);82 when(driver.getCapabilities()).thenReturn(caps);83 when(driver.execute(DriverCommand.GET_APP_CACHE_STATUS, null))84 .thenReturn(AppCacheStatus.CHECKING.name());85 ApplicationCache cache = Utils.getApplicationCache(driver);86 assertEquals(AppCacheStatus.CHECKING, cache.getStatus());87 }88 @Test89 public void providesRemoteAccessToLocationContext() {90 DesiredCapabilities caps = new DesiredCapabilities();91 caps.setCapability(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);92 CapableDriver driver = mock(CapableDriver.class);93 when(driver.getCapabilities()).thenReturn(caps);94 when(driver.execute(DriverCommand.GET_LOCATION, null)).thenReturn(95 ImmutableMap.of("latitude", 1.2, "longitude", 3.4, "altitude", 5.6));96 LocationContext context = Utils.getLocationContext(driver);97 Location location = context.location();98 assertEquals(1.2, location.getLatitude(), 0.001);99 assertEquals(3.4, location.getLongitude(), 0.001);100 assertEquals(5.6, location.getAltitude(), 0.001);101 reset(driver);102 location = new Location(7, 8, 9);103 context.setLocation(location);104 verify(driver).execute(DriverCommand.SET_LOCATION, ImmutableMap.of("location", location));105 }106 @Test107 public void providesRemoteAccessToWebStorage() {108 DesiredCapabilities caps = new DesiredCapabilities();109 caps.setCapability(CapabilityType.SUPPORTS_WEB_STORAGE, true);110 CapableDriver driver = mock(CapableDriver.class);111 when(driver.getCapabilities()).thenReturn(caps);112 WebStorage storage = Utils.getWebStorage(driver);113 LocalStorage localStorage = storage.getLocalStorage();114 SessionStorage sessionStorage = storage.getSessionStorage();115 localStorage.setItem("foo", "bar");116 sessionStorage.setItem("bim", "baz");117 verify(driver).execute(DriverCommand.SET_LOCAL_STORAGE_ITEM, ImmutableMap.of(118 "key", "foo", "value", "bar"));119 verify(driver).execute(DriverCommand.SET_SESSION_STORAGE_ITEM, ImmutableMap.of(120 "key", "bim", "value", "baz"));121 }122 interface CapableDriver extends WebDriver, ExecuteMethod, HasCapabilities {123 }124 interface Html5Driver extends WebDriver, ApplicationCache, LocationContext, WebStorage {125 }126}...

Full Screen

Full Screen

Source:LaunchBrowser.java Github

copy

Full Screen

1package com.shi.rtcp.business.keywords;2import java.io.IOException;3import java.util.concurrent.TimeUnit;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.chrome.ChromeOptions;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.firefox.FirefoxProfile;9import org.openqa.selenium.firefox.internal.ProfilesIni;10import org.openqa.selenium.ie.InternetExplorerDriver;11import org.openqa.selenium.remote.CapabilityType;12import org.openqa.selenium.remote.DesiredCapabilities;13import com.shi.rtcp.business.KeywordInterface;14import com.shi.rtcp.vos.TestStepExecutionResultVO;15public class LaunchBrowser implements KeywordInterface{16 public static String mainWindowHandle="";17 WebDriver webDriver;18 @Override19 public TestStepExecutionResultVO execute(WebDriver wd, String... params) {20 21 TestStepExecutionResultVO testStepExecutionResultVO = new TestStepExecutionResultVO();22 DesiredCapabilities capabilities = null;23 if(params[1].equalsIgnoreCase("chrome") || params[1].trim().isEmpty())24 {25 try {26 Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");27 } catch (IOException e) {28 // TODO Auto-generated catch block29 e.printStackTrace();30 }31 32 capabilities = DesiredCapabilities.chrome();33 34 ChromeOptions options = new ChromeOptions();35 options.addArguments("user-data-dir=C:/Users/"+System.getProperty("user.name")+"/AppData/Local/Google/Chrome/D");36 options.addArguments("--start-maximized");37 options.addArguments("test-type");38 capabilities.setCapability(ChromeOptions.CAPABILITY, options);39 System.setProperty("webdriver.chrome.driver", "chromedriver.exe");40 webDriver = new ChromeDriver(capabilities);41 }42 else if(params[1].equalsIgnoreCase("firefox"))43 {44 capabilities = DesiredCapabilities.firefox();45 46 ProfilesIni profile = new ProfilesIni();47 FirefoxProfile myprofile = profile.getProfile("C:\\Users\\vinusha\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\rwrqdehl.driverTest");48 49 webDriver = new FirefoxDriver(myprofile);50 }51 52 53 else if(params[1].equalsIgnoreCase("ie"))54 {55 try {56 Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe");57 Thread.sleep(2000);58 capabilities = null;59 capabilities = DesiredCapabilities.internetExplorer();60 capabilities.setCapability("nativeEvents", false);61 capabilities.setCapability("ignoreZoomSetting", true); 62 capabilities.setCapability("enablePersistentHover", true);63 capabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);64 capabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, false); 65 capabilities.setCapability(InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR, true);66 capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);67 capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);68 capabilities.setCapability("requireWindowFocus", true); 69 System.setProperty("webdriver.ie.driver", "C:\\Users\\vinusha\\Downloads\\IEDriverServer_x64_2.39.0\\IEDriverServer.exe");70 webDriver=new InternetExplorerDriver(capabilities);71 } catch (Exception e) {72 // TODO Auto-generated catch block73 e.printStackTrace();74 }75 76 }77 else78 {79 testStepExecutionResultVO.setDefectDesc("Unknown browser type");80 return testStepExecutionResultVO;81 }82 webDriver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);83 webDriver.manage().timeouts().pageLoadTimeout(240, TimeUnit.SECONDS);84 webDriver.manage().deleteAllCookies();85 webDriver.manage().window().maximize();86 System.out.println("hit url..");87 webDriver.get(params[0]);88 mainWindowHandle=webDriver.getWindowHandle();89 System.out.println("title.."+webDriver.getTitle());90 91 System.out.println("mainWindowHandle.."+mainWindowHandle);92 testStepExecutionResultVO.setStatus(1);93 return testStepExecutionResultVO;94 }95 public WebDriver getWebDriverInstance() {96 return this.webDriver;97 }98}...

Full Screen

Full Screen

Source:osciseriTest.java Github

copy

Full Screen

1package network.ite.run.com;23import static org.junit.Assert.assertTrue;4import static org.junit.Assert.fail;56import java.util.ArrayList;7import java.util.concurrent.TimeUnit;89import org.junit.After;10import org.junit.Before;11import org.junit.Test;12import org.openqa.selenium.By;13import org.openqa.selenium.WebDriver;14import org.openqa.selenium.ie.InternetExplorerDriver;15//import org.openqa.selenium.remote.CapabilityType;16import org.openqa.selenium.remote.DesiredCapabilities;17import org.openqa.selenium.support.ui.ExpectedConditions;18import org.openqa.selenium.support.ui.WebDriverWait;1920public class osciseriTest {21 private final String APP = "eri";22 private ErrSnapshot Snap;23 private WebDriver driver;24 private ReadXML userinfo;25 private ArrayList<String> names;26 private static final String KILL = "taskkill /F /IM ";2728 @Before29 public void setUp() throws Exception {30 System.out.println("<OSC IS ERI>");31 System.setProperty("webdriver.ie.driver", "C:\\eclipse-standard-luna-R-win32-x86_64\\IEDriverServer.exe");32 DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();33 capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, false);34 //capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, org.openqa.selenium.UnexpectedAlertBehaviour.DISMISS);35 driver = new InternetExplorerDriver(capabilities);36 Snap = new ErrSnapshot();37 userinfo = new ReadXML();38 names = userinfo.readXML(APP);39 driver.manage().window().maximize();40 }41 42 @After43 public void tearDown() throws Exception {44 driver.quit();45 killProcess();46 System.out.println("\n");47 }48 49 @Test50 public void test() {51 driver.manage().timeouts().pageLoadTimeout(280, TimeUnit.SECONDS); 52 try {53 driver.get(names.get(0));54 Popup pop = new Popup();55 WebDriverWait wait = new WebDriverWait(driver, 120); 56 if(pop.isAlertPresent(driver)) {57 pop.stupidpopup();58 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//td[@id='zz1_TopNavigationMenun0']/table/tbody/tr/td/a"))); 59 } 60 assertTrue(driver.getPageSource().contains("Equipment Request Interface"));61 } catch (Throwable e) {62 Snap.take(driver, APP);63 System.out.println("<OSC IS ERI Faiure>");64 fail("***Error: Equipment Request Interface is unavailable***");65 }66 67 try {68 driver.findElement(By.xpath("//td[@id='zz1_TopNavigationMenun0']/table/tbody/tr/td/a")).click();69 assertTrue(driver.getPageSource().contains("Equipment Request Interface"));70 } catch (Throwable e) {71 Snap.take(driver, APP);72 System.out.println("<OSC IS ERI Faiure>");73 fail("***Error: Equipment Request Interface is unavailable***");74 }75 System.out.println("PASS");76 }77 78 public static void killProcess() throws Exception {79 Runtime.getRuntime().exec(KILL + "iexplore.exe");80 }81} ...

Full Screen

Full Screen

Source:Utils.java Github

copy

Full Screen

1package org.openqa.selenium.remote.server.handler.html5;2import com.google.common.base.Throwables;3import java.lang.reflect.Constructor;4import java.lang.reflect.InvocationTargetException;5import org.openqa.selenium.Capabilities;6import org.openqa.selenium.HasCapabilities;7import org.openqa.selenium.UnsupportedCommandException;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.WebDriverException;10import org.openqa.selenium.html5.ApplicationCache;11import org.openqa.selenium.html5.LocationContext;12import org.openqa.selenium.html5.WebStorage;13import org.openqa.selenium.mobile.NetworkConnection;14import org.openqa.selenium.remote.ExecuteMethod;15import org.openqa.selenium.remote.html5.RemoteApplicationCache;16import org.openqa.selenium.remote.html5.RemoteLocationContext;17import org.openqa.selenium.remote.html5.RemoteWebStorage;18import org.openqa.selenium.remote.mobile.RemoteNetworkConnection;19public class Utils20{21 public Utils() {}22 23 static ApplicationCache getApplicationCache(WebDriver driver)24 {25 return (ApplicationCache)convert(driver, ApplicationCache.class, "applicationCacheEnabled", RemoteApplicationCache.class);26 }27 28 public static NetworkConnection getNetworkConnection(WebDriver driver)29 {30 return (NetworkConnection)convert(driver, NetworkConnection.class, "networkConnectionEnabled", RemoteNetworkConnection.class);31 }32 33 static LocationContext getLocationContext(WebDriver driver)34 {35 return (LocationContext)convert(driver, LocationContext.class, "locationContextEnabled", RemoteLocationContext.class);36 }37 38 static WebStorage getWebStorage(WebDriver driver)39 {40 return (WebStorage)convert(driver, WebStorage.class, "webStorageEnabled", RemoteWebStorage.class);41 }42 43 private static <T> T convert(WebDriver driver, Class<T> interfaceClazz, String capability, Class<? extends T> remoteImplementationClazz)44 {45 if (interfaceClazz.isInstance(driver)) {46 return interfaceClazz.cast(driver);47 }48 49 if (((driver instanceof ExecuteMethod)) && ((driver instanceof HasCapabilities)))50 {51 if (((HasCapabilities)driver).getCapabilities().is(capability)) {52 try {53 return 54 55 remoteImplementationClazz.getConstructor(new Class[] { ExecuteMethod.class }).newInstance(new Object[] { (ExecuteMethod)driver });56 } catch (InstantiationException e) {57 throw new WebDriverException(e);58 } catch (IllegalAccessException e) {59 throw new WebDriverException(e);60 } catch (InvocationTargetException e) {61 throw Throwables.propagate(e.getCause());62 } catch (NoSuchMethodException e) {63 throw new WebDriverException(e);64 }65 }66 }67 68 throw new UnsupportedCommandException("driver (" + driver.getClass().getName() + ") does not support " + interfaceClazz.getName());69 }70}...

Full Screen

Full Screen

Source:WebDrivers.java Github

copy

Full Screen

1package seleniumjavatpoint;2import org.openqa.selenium.By;3import org.openqa.selenium.Keys;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.ie.InternetExplorerDriver;9import org.openqa.selenium.remote.DesiredCapabilities;10import org.openqa.selenium.safari.SafariDriver;11import org.openqa.selenium.support.ui.ExpectedConditions;12import org.openqa.selenium.support.ui.Wait;13import org.openqa.selenium.support.ui.WebDriverWait;14public class WebDrivers {15 public static void main(String[] args) {16 firefoxDriver();17 chromeDriver();18 }19 public static void chromeDriver(){20 //Creating a driver object referencing WebDriver interface21 WebDriver driver;22//Setting the webdriver.chrome.driver property to its executable's location23 System.setProperty("webdriver.chrome.driver", "/Library/chromedriver");24//Instantiating driver object25 driver = new ChromeDriver();26//Using get() method to open a webpage27 driver.get("http://javatpoint.com");28//Closing the browser29 driver.quit();30 }31 public static void ieDriver(){32 //Creating a driver object referencing WebDriver interface33 WebDriver driver;34//Setting the webdriver.ie.driver property to its executable's location35 System.setProperty("webdriver.ie.driver", "/lib/IEDriverServer/IEDriverServer.exe");36//Instantiating driver object37 driver = new InternetExplorerDriver();38//Using get() method to open a webpage39 driver.get("http://javatpoint.com");40//Closing the browser41 driver.quit();42 }43 public static void firefoxDriver() {44 // System Property for Gecko Driver45 System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"/resources/webdrivers/mac/geckodriver");46 // Initialize Gecko Driver using Desired Capabilities Class47 DesiredCapabilities capabilities = DesiredCapabilities.firefox();48 capabilities.setCapability("marionette",true);49 WebDriver driver= new FirefoxDriver(capabilities);50 // Launch Website51 driver.navigate().to("http://www.javatpoint.com/");52 //Closing the browser53 driver.quit();54 }55}...

Full Screen

Full Screen

Source:BrowserFactory.java Github

copy

Full Screen

1package com.onfido.qa.webdriver.backend;2import org.openqa.selenium.Capabilities;3import org.openqa.selenium.MutableCapabilities;4import org.openqa.selenium.remote.DesiredCapabilities;5import org.openqa.selenium.remote.RemoteWebDriver;6import org.openqa.selenium.remote.service.DriverService;7import java.util.Properties;8public interface BrowserFactory {9 RemoteWebDriver createDriver(DriverService service, Capabilities capabilities);10 MutableCapabilities getOptions(DesiredCapabilities capabilities, Config config, Properties properties);11}...

Full Screen

Full Screen

Interface Capabilities

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.DesiredCapabilities;2import org.openqa.selenium.remote.RemoteWebDriver;3import java.net.MalformedURLException;4import java.net.URL;5import org.openqa.selenium.By;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.chrome.ChromeDriver;8import org.openqa.selenium.chrome.ChromeOptions;9import org.openqa.selenium.firefox.FirefoxDriver;10import org.openqa.selenium.firefox.FirefoxProfile;11import org.openqa.selenium.ie.InternetExplorerDriver;12import org.openqa.selenium.remote.DesiredCapabilities;13import org.openqa.selenium.remote.RemoteWebDriver;14import org.openqa.selenium.support.ui.Select;15import org.openqa.selenium.support.ui.WebDriverWait;16import org.testng.annotations.AfterClass;17import org.testng.annotations.BeforeClass;18import org.testng.annotations.Test;19public class TestGrid {20WebDriver driver;21public void setUp() throws MalformedURLException {22DesiredCapabilities capability = DesiredCapabilities.firefox();23capability.setBrowserName("firefox");24capability.setPlatform(Platform.WINDOWS);25}26public void testGrid() {27}28public void tearDown() {29driver.quit();30}31}

Full Screen

Full Screen

Interface Capabilities

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.DesiredCapabilities;2import org.openqa.selenium.remote.RemoteWebDriver;3import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.interactions.Actions;7import org.openqa.selenium.JavascriptExecutor;8import org.openqa.selenium.support.ui.ExpectedConditions;9import org.openqa.selenium.support.ui.WebDriverWait;10import org.openqa.selenium.support.ui.Select;11import org.openqa.selenium.NoSuchElementException;12import org.openqa.selenium.TakesScreenshot;13import org.apache.commons.io.FileUtils;14import org.openqa.selenium.OutputType;15import org.openqa.selenium.Dimension;16import org.openqa.selenium.Point;17import org.openqa.selenium.Alert;18import java.io.File;19import java.io.IOException;20import java.io.InputStream;21import java.io.FileInputStream;22import java.io.BufferedReader;23import java.io.InputStreamReader;24import java.util.List;25import java.util.Properties;26import java.util.Set;27import java.util.Iterator;28import java.util.concurrent.TimeUnit;29import java.util.Date;30import java.text.DateFormat;31import java.text.SimpleDateFormat;32import java.util.Calendar;33import java.util.logging.Level;34import java.util.logging.Logger;35import java.lang.reflect.Method;36import java.lang.reflect.InvocationTargetException;37import java.lang.reflect.Constructor;38import java.lang.reflect.Field;39import java.lang.reflect.Modifier;40import java.lang.reflect.Type;41import java.lang.reflect.TypeVariable;42import java.lang.reflect.ParameterizedType;43import java.lang.reflect.Method;44import java.lang.reflect.InvocationTargetException;45import java.lang.reflect.Constructor;46import java.lang.reflect.Field;47import java.lang.reflect.Modifier;48import java.lang.reflect.Type;49import java.lang.reflect.TypeVariable;50import java.lang.reflect.ParameterizedType;51import java.lang.reflect.Method;52import java.lang.reflect.InvocationTargetException;53import java.lang.reflect.Constructor;54import java.lang.reflect.Field;55import java.lang.reflect.Modifier;56import java.lang.reflect.Type;57import java.lang.reflect.TypeVariable;58import java.lang.reflect.ParameterizedType;59import java.lang.reflect.Method;60import java.lang.reflect.InvocationTargetException;61import java.lang.reflect.Constructor;62import java.lang.reflect.Field;63import java.lang.reflect.Modifier;64import java.lang.reflect.Type;65import java.lang.reflect.TypeVariable;66import java.lang.reflect.ParameterizedType;67import java.lang.reflect.Method;68import java.lang.reflect.InvocationTargetException;69import java.lang.reflect.Constructor;70import java.lang.reflect.Field;71import java.lang.reflect.Modifier;72import java.lang.reflect.Type;73import java.lang.reflect.TypeVariable;74import java.lang.reflect.ParameterizedType;75import java.lang.reflect.Method;76import java.lang

Full Screen

Full Screen

Interface Capabilities

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3import org.openqa.selenium.chrome.ChromeOptions;4import org.openqa.selenium.remote.DesiredCapabilities;5public class ChromeHeadless {6 public static void main(String[] args) {7 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Administrator\\Downloads\\chromedriver_win32\\chromedriver.exe");8 ChromeOptions options = new ChromeOptions();9 options.addArguments("headless");10 options.addArguments("window-size=1200x600");11 DesiredCapabilities capabilities = DesiredCapabilities.chrome();12 capabilities.setCapability(ChromeOptions.CAPABILITY, options);13 WebDriver driver = new ChromeDriver(capabilities);14 System.out.println("Google title is: " + driver.getTitle());15 driver.quit();16 }17}18package com.java2novice.selenium;19import org.openqa.selenium.WebDriver;20import org.openqa.selenium

Full Screen

Full Screen

Interface Capabilities

Using AI Code Generation

copy

Full Screen

1import io.appium.java_client.remote.MobileCapabilityType;2import io.appium.java_client.remote.MobilePlatform;3import io.appium.java_client.remote.AutomationName;4import io.appium.java_client.remote.AndroidMobileCapabilityType;5import io.appium.java_client.remote.IOSMobileCapabilityType;6import io.appium.java_client.remote.IOSMobileCapabilityType;7import io.appium.java_client.remote.IOSMobileCapabilityType;8import org.openqa.selenium.remote.DesiredCapabilities;9import org.openqa.selenium.remote.RemoteWebDriver;10import java.net.URL;11import java.net.MalformedURLException;12public class AppiumCapabilities {13 public static void main(String[] args) throws MalformedURLException {14 DesiredCapabilities capabilities = new DesiredCapabilities();15 capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);16 capabilities.setCapability(MobileCapabilityType.APP, "/Users/sumitkumar/Documents/workspace/AppiumDemo/src/test/resources/apps/ApiDemos-debug.apk");17 capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");18 capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "25");19 capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis");20 capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.WebView1");21 capabilities.setCapability(AndroidMobileCapabilityType.APP_WAIT_ACTIVITY, ".view.WebView1");22 capabilities.setCapability(AndroidMobileCapabilityType.AUTO_GRANT_PERMISSIONS, true);23 capabilities.setCapability(AndroidMobileCapabilityType

Full Screen

Full Screen

Interface Capabilities

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.*;2public class HTML5Test {3 public static void main(String[] args) {4 WebDriver driver = new FirefoxDriver();5 if (driver instanceof Html5Driver) {6 System.out.println("HTML5 is supported");7 } else {8 System.out.println("HTML5 is not supported");9 }10 driver.quit();11 }12}

Full Screen

Full Screen
copy
1public class WCFs2{3 // https://192.168.30.8/myservice.svc?wsdl4private static final String NAMESPACE = "http://tempuri.org/";5private static final String URL = "192.168.30.8";6private static final String SERVICE = "/myservice.svc?wsdl";7private static String SOAP_ACTION = "http://tempuri.org/iWCFserviceMe/";8910public static Thread myMethod(Runnable rp)11{12 String METHOD_NAME = "myMethod";1314 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);1516 request.addProperty("Message", "Https WCF Running...");17 return _call(rp,METHOD_NAME, request);18}1920protected static HandlerThread _call(final RunProcess rp,final String METHOD_NAME, SoapObject soapReq)21{22 final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);23 int TimeOut = 5*1000;2425 envelope.dotNet = true;26 envelope.bodyOut = soapReq;27 envelope.setOutputSoapObject(soapReq);2829 final HttpsTransportSE httpTransport_net = new HttpsTransportSE(URL, 443, SERVICE, TimeOut);3031 try32 {33 HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() // use this section if crt file is handmake34 {35 @Override36 public boolean verify(String hostname, SSLSession session)37 {38 return true;39 }40 });4142 KeyStore k = getFromRaw(R.raw.key, "PKCS12", "password");43 ((HttpsServiceConnectionSE) httpTransport_net.getServiceConnection()).setSSLSocketFactory(getSSLSocketFactory(k, "SSL"));444546 }47 catch(Exception e){}4849 HandlerThread thread = new HandlerThread("wcfTd"+ Generator.getRandomNumber())50 {51 @Override52 public void run()53 {54 Handler h = new Handler(Looper.getMainLooper());55 Object response = null;5657 for(int i=0; i<4; i++)58 {59 response = send(envelope, httpTransport_net , METHOD_NAME, null);6061 try62 {if(Thread.currentThread().isInterrupted()) return;}catch(Exception e){}6364 if(response != null)65 break;6667 ThreadHelper.threadSleep(250);68 }6970 if(response != null)71 {72 if(rp != null)73 {74 rp.setArguments(response.toString());75 h.post(rp);76 }77 }78 else79 {80 if(Thread.currentThread().isInterrupted())81 return;8283 if(rp != null)84 {85 rp.setExceptionState(true);86 h.post(rp);87 }88 }8990 ThreadHelper.stopThread(this);91 }92 };9394 thread.start();9596 return thread;97}9899100private static Object send(SoapSerializationEnvelope envelope, HttpTransportSE androidHttpTransport, String METHOD_NAME, List<HeaderProperty> headerList)101{102 try103 {104 if(headerList != null)105 androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope, headerList);106 else107 androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);108109 Object res = envelope.getResponse();110111 if(res instanceof SoapPrimitive)112 return (SoapPrimitive) envelope.getResponse();113 else if(res instanceof SoapObject)114 return ((SoapObject) envelope.getResponse());115 }116 catch(Exception e)117 {}118119 return null;120}121122public static KeyStore getFromRaw(@RawRes int id, String algorithm, String filePassword)123{124 try125 {126 InputStream inputStream = ResourceMaster.openRaw(id);127 KeyStore keystore = KeyStore.getInstance(algorithm);128 keystore.load(inputStream, filePassword.toCharArray());129 inputStream.close();130131 return keystore;132 }133 catch(Exception e)134 {}135136 return null;137}138139public static SSLSocketFactory getSSLSocketFactory(KeyStore trustKey, String SSLAlgorithm)140{141 try142 {143 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());144 tmf.init(trustKey);145146 SSLContext context = SSLContext.getInstance(SSLAlgorithm);//"SSL" "TLS"147 context.init(null, tmf.getTrustManagers(), null);148149 return context.getSocketFactory();150 }151 catch(Exception e){}152153 return null;154}155
Full Screen
copy
1const SslProtocols _Tls12 = (SslProtocols)0x00000C00;2const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;3ServicePointManager.SecurityProtocol = Tls12;4
Full Screen
copy
1httpClient = new DefaultHttpClient();23SSLContext ctx = SSLContext.getInstance("TLS");4X509TrustManager tm = new X509TrustManager() {5 public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }67 public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }89 public X509Certificate[] getAcceptedIssuers() {10 return null;11 }12};1314ctx.init(null, new TrustManager[]{tm}, null);15SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);1617httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, ssf));18
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.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful