How to use ProtocolHandshake class of org.openqa.selenium.remote package

Best Selenium code snippet using org.openqa.selenium.remote.ProtocolHandshake

Source:AppiumCommandExecutor.java Github

copy

Full Screen

...35import org.openqa.selenium.remote.CommandInfo;36import org.openqa.selenium.remote.Dialect;37import org.openqa.selenium.remote.DriverCommand;38import org.openqa.selenium.remote.HttpCommandExecutor;39import org.openqa.selenium.remote.ProtocolHandshake;40import org.openqa.selenium.remote.Response;41import org.openqa.selenium.remote.ResponseCodec;42import org.openqa.selenium.remote.http.HttpClient;43import org.openqa.selenium.remote.http.HttpRequest;44import org.openqa.selenium.remote.http.HttpResponse;45import org.openqa.selenium.remote.http.W3CHttpCommandCodec;46import org.openqa.selenium.remote.service.DriverService;47import java.io.BufferedInputStream;48import java.io.IOException;49import java.io.InputStream;50import java.io.OutputStreamWriter;51import java.io.Writer;52import java.lang.reflect.Field;53import java.lang.reflect.InvocationTargetException;54import java.lang.reflect.Method;55import java.net.ConnectException;56import java.net.URL;57import java.util.Map;58import java.util.Optional;59import java.util.UUID;60public class AppiumCommandExecutor extends HttpCommandExecutor {61 // https://github.com/appium/appium-base-driver/pull/40062 private static final String IDEMPOTENCY_KEY_HEADER = "X-Idempotency-Key";63 private final Optional<DriverService> serviceOptional;64 private AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,65 URL addressOfRemoteServer,66 HttpClient.Factory httpClientFactory) {67 super(additionalCommands,68 ofNullable(service)69 .map(DriverService::getUrl)70 .orElse(addressOfRemoteServer), httpClientFactory);71 serviceOptional = ofNullable(service);72 }73 public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,74 HttpClient.Factory httpClientFactory) {75 this(additionalCommands, checkNotNull(service), null, httpClientFactory);76 }77 public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,78 URL addressOfRemoteServer, HttpClient.Factory httpClientFactory) {79 this(additionalCommands, null, checkNotNull(addressOfRemoteServer), httpClientFactory);80 }81 public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,82 URL addressOfRemoteServer) {83 this(additionalCommands, addressOfRemoteServer, HttpClient.Factory.createDefault());84 }85 public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,86 DriverService service) {87 this(additionalCommands, service, HttpClient.Factory.createDefault());88 }89 protected <B> B getPrivateFieldValue(String fieldName, Class<B> fieldType) {90 Class<?> superclass = getClass().getSuperclass();91 Throwable recentException = null;92 while (superclass != Object.class) {93 try {94 final Field f = superclass.getDeclaredField(fieldName);95 f.setAccessible(true);96 return fieldType.cast(f.get(this));97 } catch (NoSuchFieldException | IllegalAccessException e) {98 recentException = e;99 }100 superclass = superclass.getSuperclass();101 }102 throw new WebDriverException(recentException);103 }104 protected void setPrivateFieldValue(String fieldName, Object newValue) {105 Class<?> superclass = getClass().getSuperclass();106 Throwable recentException = null;107 while (superclass != Object.class) {108 try {109 final Field f = superclass.getDeclaredField(fieldName);110 f.setAccessible(true);111 f.set(this, newValue);112 return;113 } catch (NoSuchFieldException | IllegalAccessException e) {114 recentException = e;115 }116 superclass = superclass.getSuperclass();117 }118 throw new WebDriverException(recentException);119 }120 protected Map<String, CommandInfo> getAdditionalCommands() {121 //noinspection unchecked122 return getPrivateFieldValue("additionalCommands", Map.class);123 }124 protected CommandCodec<HttpRequest> getCommandCodec() {125 //noinspection unchecked126 return getPrivateFieldValue("commandCodec", CommandCodec.class);127 }128 protected void setCommandCodec(CommandCodec<HttpRequest> newCodec) {129 setPrivateFieldValue("commandCodec", newCodec);130 }131 protected void setResponseCodec(ResponseCodec<HttpResponse> codec) {132 setPrivateFieldValue("responseCodec", codec);133 }134 protected HttpClient getClient() {135 return getPrivateFieldValue("client", HttpClient.class);136 }137 protected HttpClient withRequestsPatchedByIdempotencyKey(HttpClient httpClient) {138 return (request) -> {139 request.setHeader(IDEMPOTENCY_KEY_HEADER, UUID.randomUUID().toString().toLowerCase());140 return httpClient.execute(request);141 };142 }143 private Response createSession(Command command) throws IOException {144 if (getCommandCodec() != null) {145 throw new SessionNotCreatedException("Session already exists");146 }147 ProtocolHandshake handshake = new ProtocolHandshake() {148 @SuppressWarnings("unchecked")149 public Result createSession(HttpClient client, Command command) throws IOException {150 Capabilities desiredCapabilities = (Capabilities) command.getParameters().get("desiredCapabilities");151 Capabilities desired = desiredCapabilities == null ? new ImmutableCapabilities() : desiredCapabilities;152 //the number of bytes before the stream should switch to buffering to a file153 int threshold = (int) Math.min(Runtime.getRuntime().freeMemory() / 10, Integer.MAX_VALUE);154 FileBackedOutputStream os = new FileBackedOutputStream(threshold);155 try {156 CountingOutputStream counter = new CountingOutputStream(os);157 Writer writer = new OutputStreamWriter(counter, UTF_8);158 NewAppiumSessionPayload payload = NewAppiumSessionPayload.create(desired);159 payload.writeTo(writer);160 try (InputStream rawIn = os.asByteSource().openBufferedStream();161 BufferedInputStream contentStream = new BufferedInputStream(rawIn)) {162 Method createSessionMethod = this.getClass().getSuperclass()163 .getDeclaredMethod("createSession", HttpClient.class, InputStream.class, long.class);164 createSessionMethod.setAccessible(true);165 Optional<Result> result = (Optional<Result>) createSessionMethod.invoke(this,166 withRequestsPatchedByIdempotencyKey(client), contentStream, counter.getCount());167 return result.map(result1 -> {168 Result toReturn = result.get();169 getLogger(ProtocolHandshake.class.getName())170 .info(format("Detected dialect: %s", toReturn.getDialect()));171 return toReturn;172 }).orElseThrow(() -> new SessionNotCreatedException(173 format("Unable to create a new remote session. Desired capabilities = %s", desired)));174 } catch (NoSuchMethodException | IllegalAccessException e) {175 throw new SessionNotCreatedException(format("Unable to create a new remote session. "176 + "Make sure your project dependencies config does not override "177 + "Selenium API version %s used by java-client library.",178 Config.main().getValue("selenium.version", String.class)), e);179 } catch (InvocationTargetException e) {180 String message = "Unable to create a new remote session.";181 if (e.getCause() != null) {182 if (e.getCause() instanceof WebDriverException) {183 message += " Please check the server log for more details.";184 }185 message += format(" Original error: %s", e.getCause().getMessage());186 }187 throw new SessionNotCreatedException(message, e);188 }189 } finally {190 os.reset();191 }192 }193 };194 ProtocolHandshake.Result result = handshake195 .createSession(getClient(), command);196 Dialect dialect = result.getDialect();197 setCommandCodec(dialect.getCommandCodec());198 getAdditionalCommands().forEach(this::defineCommand);199 setResponseCodec(dialect.getResponseCodec());200 return result.createResponse();201 }202 @Override203 public Response execute(Command command) throws WebDriverException {204 if (DriverCommand.NEW_SESSION.equals(command.getName())) {205 serviceOptional.ifPresent(driverService -> {206 try {207 driverService.start();208 } catch (IOException e) {...

Full Screen

Full Screen

Source:ProtocolHandshakeTest.java Github

copy

Full Screen

...41import java.util.Optional;42import java.util.Set;43import java.util.stream.Collectors;44@SuppressWarnings("unchecked")45public class ProtocolHandshakeTest {46 @Test47 public void requestShouldIncludeJsonWireProtocolCapabilities() throws IOException {48 Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());49 Command command = new Command(null, DriverCommand.NEW_SESSION, params);50 HttpResponse response = new HttpResponse();51 response.setStatus(HTTP_OK);52 response.setContent(utf8String(53 "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));54 RecordingHttpClient client = new RecordingHttpClient(response);55 new ProtocolHandshake().createSession(client, command);56 Map<String, Object> json = getRequestPayloadAsMap(client);57 assertThat(json.get("desiredCapabilities")).isEqualTo(EMPTY_MAP);58 }59 @Test60 public void requestShouldIncludeSpecCompliantW3CCapabilities() throws IOException {61 Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());62 Command command = new Command(null, DriverCommand.NEW_SESSION, params);63 HttpResponse response = new HttpResponse();64 response.setStatus(HTTP_OK);65 response.setContent(utf8String(66 "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));67 RecordingHttpClient client = new RecordingHttpClient(response);68 new ProtocolHandshake().createSession(client, command);69 Map<String, Object> json = getRequestPayloadAsMap(client);70 List<Map<String, Object>> caps = mergeW3C(json);71 assertThat(caps).isNotEmpty();72 }73 @Test74 public void shouldParseW3CNewSessionResponse() throws IOException {75 Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());76 Command command = new Command(null, DriverCommand.NEW_SESSION, params);77 HttpResponse response = new HttpResponse();78 response.setStatus(HTTP_OK);79 response.setContent(utf8String(80 "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));81 RecordingHttpClient client = new RecordingHttpClient(response);82 ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);83 assertThat(result.getDialect()).isEqualTo(Dialect.W3C);84 }85 @Test86 public void shouldParseWireProtocolNewSessionResponse() throws IOException {87 Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());88 Command command = new Command(null, DriverCommand.NEW_SESSION, params);89 HttpResponse response = new HttpResponse();90 response.setStatus(HTTP_OK);91 response.setContent(utf8String(92 "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));93 RecordingHttpClient client = new RecordingHttpClient(response);94 ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);95 assertThat(result.getDialect()).isEqualTo(Dialect.OSS);96 }97 @Test98 public void shouldNotIncludeNonProtocolExtensionKeys() throws IOException {99 Capabilities caps = new ImmutableCapabilities(100 "se:option", "cheese",101 "option", "I like sausages",102 "browserName", "amazing cake browser");103 Map<String, Object> params = singletonMap("desiredCapabilities", caps);104 Command command = new Command(null, DriverCommand.NEW_SESSION, params);105 HttpResponse response = new HttpResponse();106 response.setStatus(HTTP_OK);107 response.setContent(utf8String(108 "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));109 RecordingHttpClient client = new RecordingHttpClient(response);110 new ProtocolHandshake().createSession(client, command);111 Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);112 Object rawCaps = handshakeRequest.get("capabilities");113 assertThat(rawCaps).isInstanceOf(Map.class);114 Map<?, ?> capabilities = (Map<?, ?>) rawCaps;115 assertThat(capabilities.get("alwaysMatch")).isNull();116 List<Map<?, ?>> first = (List<Map<?, ?>>) capabilities.get("firstMatch");117 // We don't care where they are, but we want to see "se:option" and not "option"118 Set<String> keys = first.stream()119 .map(Map::keySet)120 .flatMap(Collection::stream)121 .map(String::valueOf).collect(Collectors.toSet());122 assertThat(keys)123 .contains("browserName", "se:option")124 .doesNotContain("options");125 }126 @Test127 public void firstMatchSeparatesCapsForDifferentBrowsers() throws IOException {128 Capabilities caps = new ImmutableCapabilities(129 "moz:firefoxOptions", EMPTY_MAP,130 "browserName", "chrome");131 Map<String, Object> params = singletonMap("desiredCapabilities", caps);132 Command command = new Command(null, DriverCommand.NEW_SESSION, params);133 HttpResponse response = new HttpResponse();134 response.setStatus(HTTP_OK);135 response.setContent(utf8String(136 "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));137 RecordingHttpClient client = new RecordingHttpClient(response);138 new ProtocolHandshake().createSession(client, command);139 Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);140 List<Map<String, Object>> capabilities = mergeW3C(handshakeRequest);141 assertThat(capabilities).contains(142 singletonMap("moz:firefoxOptions", EMPTY_MAP),143 singletonMap("browserName", "chrome"));144 }145 @Test146 public void doesNotCreateFirstMatchForNonW3CCaps() throws IOException {147 Capabilities caps = new ImmutableCapabilities(148 "cheese", EMPTY_MAP,149 "moz:firefoxOptions", EMPTY_MAP,150 "browserName", "firefox");151 Map<String, Object> params = singletonMap("desiredCapabilities", caps);152 Command command = new Command(null, DriverCommand.NEW_SESSION, params);153 HttpResponse response = new HttpResponse();154 response.setStatus(HTTP_OK);155 response.setContent(utf8String(156 "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));157 RecordingHttpClient client = new RecordingHttpClient(response);158 new ProtocolHandshake().createSession(client, command);159 Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);160 List<Map<String, Object>> w3c = mergeW3C(handshakeRequest);161 assertThat(w3c).hasSize(1);162 // firstMatch should not contain an object for Chrome-specific capabilities. Because163 // "chromeOptions" is not a W3C capability name, it is stripped from any firstMatch objects.164 // The resulting empty object should be omitted from firstMatch; if it is present, then the165 // Firefox-specific capabilities might be ignored.166 assertThat(w3c.get(0))167 .containsKey("moz:firefoxOptions")168 .containsEntry("browserName", "firefox");169 }170 @Test171 public void shouldLowerCaseProxyTypeForW3CRequest() throws IOException {172 Proxy proxy = new Proxy();173 proxy.setProxyType(AUTODETECT);174 Capabilities caps = new ImmutableCapabilities(CapabilityType.PROXY, proxy);175 Map<String, Object> params = singletonMap("desiredCapabilities", caps);176 Command command = new Command(null, DriverCommand.NEW_SESSION, params);177 HttpResponse response = new HttpResponse();178 response.setStatus(HTTP_OK);179 response.setContent(utf8String(180 "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));181 RecordingHttpClient client = new RecordingHttpClient(response);182 new ProtocolHandshake().createSession(client, command);183 Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);184 mergeW3C(handshakeRequest).forEach(always -> {185 Map<String, ?> seenProxy = (Map<String, ?>) always.get("proxy");186 assertThat(seenProxy.get("proxyType")).isEqualTo("autodetect");187 });188 Map<String, ?> jsonCaps = (Map<String, ?>) handshakeRequest.get("desiredCapabilities");189 Map<String, ?> seenProxy = (Map<String, ?>) jsonCaps.get("proxy");190 assertThat(seenProxy.get("proxyType")).isEqualTo("AUTODETECT");191 }192 @Test193 public void shouldNotIncludeMappingOfANYPlatform() throws IOException {194 Capabilities caps = new ImmutableCapabilities(195 "platform", "ANY",196 "platformName", "ANY",197 "browserName", "cake");198 Map<String, Object> params = singletonMap("desiredCapabilities", caps);199 Command command = new Command(null, DriverCommand.NEW_SESSION, params);200 HttpResponse response = new HttpResponse();201 response.setStatus(HTTP_OK);202 response.setContent(utf8String(203 "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));204 RecordingHttpClient client = new RecordingHttpClient(response);205 new ProtocolHandshake().createSession(client, command);206 Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);207 mergeW3C(handshakeRequest)208 .forEach(capabilities -> {209 assertThat(capabilities.get("browserName")).isEqualTo("cake");210 assertThat(capabilities.get("platformName")).isNull();211 assertThat(capabilities.get("platform")).isNull();212 });213 }214 private List<Map<String, Object>> mergeW3C(Map<String, Object> caps) {215 Map<String, Object> capabilities = (Map<String, Object>) caps.get("capabilities");216 if (capabilities == null) {217 return null;218 }219 Map<String, Object> always = Optional.ofNullable(...

Full Screen

Full Screen

Source:ServicedSession.java Github

copy

Full Screen

...26import org.openqa.selenium.remote.Augmenter;27import org.openqa.selenium.remote.CommandCodec;28import org.openqa.selenium.remote.CommandExecutor;29import org.openqa.selenium.remote.Dialect;30import org.openqa.selenium.remote.ProtocolHandshake;31import org.openqa.selenium.remote.RemoteWebDriver;32import org.openqa.selenium.remote.Response;33import org.openqa.selenium.remote.ResponseCodec;34import org.openqa.selenium.remote.SessionId;35import org.openqa.selenium.remote.http.HttpClient;36import org.openqa.selenium.remote.http.HttpMethod;37import org.openqa.selenium.remote.http.HttpRequest;38import org.openqa.selenium.remote.http.HttpResponse;39import org.openqa.selenium.remote.http.JsonHttpCommandCodec;40import org.openqa.selenium.remote.http.JsonHttpResponseCodec;41import org.openqa.selenium.remote.http.W3CHttpCommandCodec;42import org.openqa.selenium.remote.http.W3CHttpResponseCodec;43import org.openqa.selenium.remote.internal.ApacheHttpClient;44import org.openqa.selenium.remote.service.DriverService;45import java.io.File;46import java.io.IOException;47import java.io.InputStream;48import java.lang.reflect.Method;49import java.net.URL;50import java.util.Map;51import java.util.function.Supplier;52class ServicedSession implements ActiveSession {53 private final DriverService service;54 private final SessionId id;55 private final Dialect downstream;56 private final Dialect upstream;57 private final SessionCodec codec;58 private final Map<String, Object> capabilities;59 private final TemporaryFilesystem filesystem;60 private final WebDriver driver;61 public ServicedSession(62 DriverService service,63 Dialect downstream,64 Dialect upstream,65 SessionCodec codec,66 SessionId id,67 Map<String, Object> capabilities) throws IOException {68 this.service = service;69 this.downstream = downstream;70 this.upstream = upstream;71 this.codec = codec;72 this.id = id;73 this.capabilities = capabilities;74 File tempRoot = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), id.toString());75 Preconditions.checkState(tempRoot.mkdirs());76 this.filesystem = TemporaryFilesystem.getTmpFsBasedOn(tempRoot);77 CommandExecutor executor = new ActiveSessionCommandExecutor(this);78 this.driver = new Augmenter().augment(new RemoteWebDriver(79 executor,80 new ImmutableCapabilities(getCapabilities())));81 }82 @Override83 public void execute(HttpRequest req, HttpResponse resp) throws IOException {84 codec.handle(req, resp);85 }86 @Override87 public SessionId getId() {88 return id;89 }90 @Override91 public Dialect getUpstreamDialect() {92 return upstream;93 }94 @Override95 public Dialect getDownstreamDialect() {96 return downstream;97 }98 @Override99 public Map<String, Object> getCapabilities() {100 return capabilities;101 }102 @Override103 public WebDriver getWrappedDriver() {104 return driver;105 }106 @Override107 public TemporaryFilesystem getFileSystem() {108 return filesystem;109 }110 @Override111 public void stop() {112 // Try and kill the running session. Both W3C and OSS use the same quit endpoint113 try {114 HttpRequest request = new HttpRequest(HttpMethod.DELETE, "/session/" + getId());115 HttpResponse ignored = new HttpResponse();116 execute(request, ignored);117 } catch (IOException e) {118 // This is fine.119 }120 service.stop();121 }122 public static class Factory implements SessionFactory {123 private final Supplier<? extends DriverService> createService;124 private final String serviceClassName;125 Factory(String serviceClassName) {126 this.serviceClassName = serviceClassName;127 try {128 Class<? extends DriverService> driverClazz =129 Class.forName(serviceClassName).asSubclass(DriverService.class);130 Method serviceMethod = driverClazz.getMethod("createDefaultService");131 serviceMethod.setAccessible(true);132 this.createService = () -> {133 try {134 return (DriverService) serviceMethod.invoke(null);135 } catch (ReflectiveOperationException e) {136 throw new SessionNotCreatedException(137 "Unable to create new service: " + driverClazz.getSimpleName(), e);138 }139 };140 } catch (ReflectiveOperationException e) {141 throw new SessionNotCreatedException("Cannot find service factory method", e);142 }143 }144 @Override145 public ActiveSession apply(NewSessionPayload payload) {146 DriverService service = createService.get();147 try (InputStream in = payload.getPayload().get()) {148 service.start();149 PortProber.waitForPortUp(service.getUrl().getPort(), 30, SECONDS);150 URL url = service.getUrl();151 HttpClient client = new ApacheHttpClient.Factory().createClient(url);152 ProtocolHandshake.Result result = new ProtocolHandshake()153 .createSession(client, in, payload.getPayloadSize())154 .orElseThrow(() -> new SessionNotCreatedException("Unable to create session"));155 SessionCodec codec;156 Dialect upstream = result.getDialect();157 Dialect downstream;158 if (payload.getDownstreamDialects().contains(result.getDialect())) {159 codec = new Passthrough(url);160 downstream = upstream;161 } else {162 downstream = payload.getDownstreamDialects().iterator().next();163 codec = new ProtocolConverter(164 url,165 getCommandCodec(downstream),166 getResponseCodec(downstream),...

Full Screen

Full Screen

Source:RemoteSession.java Github

copy

Full Screen

...28import org.openqa.selenium.remote.CommandCodec;29import org.openqa.selenium.remote.CommandExecutor;30import org.openqa.selenium.remote.Dialect;31import org.openqa.selenium.remote.DriverCommand;32import org.openqa.selenium.remote.ProtocolHandshake;33import org.openqa.selenium.remote.RemoteWebDriver;34import org.openqa.selenium.remote.Response;35import org.openqa.selenium.remote.ResponseCodec;36import org.openqa.selenium.remote.SessionId;37import org.openqa.selenium.remote.http.HttpClient;38import org.openqa.selenium.remote.http.HttpRequest;39import org.openqa.selenium.remote.http.HttpResponse;40import org.openqa.selenium.remote.http.JsonHttpCommandCodec;41import org.openqa.selenium.remote.http.JsonHttpResponseCodec;42import org.openqa.selenium.remote.http.W3CHttpCommandCodec;43import org.openqa.selenium.remote.http.W3CHttpResponseCodec;44import java.io.File;45import java.io.IOException;46import java.net.URL;47import java.util.Map;48import java.util.Optional;49import java.util.Set;50import java.util.logging.Level;51import java.util.logging.Logger;52/**53 * Abstract class designed to do things like protocol conversion.54 */55public abstract class RemoteSession implements ActiveSession {56 protected static Logger log = Logger.getLogger(ActiveSession.class.getName());57 private final SessionId id;58 private final Dialect downstream;59 private final Dialect upstream;60 private final SessionCodec codec;61 private final Map<String, Object> capabilities;62 private final TemporaryFilesystem filesystem;63 private final WebDriver driver;64 protected RemoteSession(65 Dialect downstream,66 Dialect upstream,67 SessionCodec codec,68 SessionId id,69 Map<String, Object> capabilities) {70 this.downstream = downstream;71 this.upstream = upstream;72 this.codec = codec;73 this.id = id;74 this.capabilities = capabilities;75 File tempRoot = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), id.toString());76 Preconditions.checkState(tempRoot.mkdirs());77 this.filesystem = TemporaryFilesystem.getTmpFsBasedOn(tempRoot);78 CommandExecutor executor = new ActiveSessionCommandExecutor(this);79 this.driver = new Augmenter().augment(new RemoteWebDriver(80 executor,81 new ImmutableCapabilities(getCapabilities())));82 }83 @Override84 public SessionId getId() {85 return id;86 }87 @Override88 public Dialect getUpstreamDialect() {89 return upstream;90 }91 @Override92 public Dialect getDownstreamDialect() {93 return downstream;94 }95 @Override96 public Map<String, Object> getCapabilities() {97 return capabilities;98 }99 @Override100 public TemporaryFilesystem getFileSystem() {101 return filesystem;102 }103 @Override104 public WebDriver getWrappedDriver() {105 return driver;106 }107 @Override108 public void execute(HttpRequest req, HttpResponse resp) throws IOException {109 codec.handle(req, resp);110 }111 public abstract static class Factory<X> implements SessionFactory {112 protected Optional<ActiveSession> performHandshake(113 X additionalData,114 URL url,115 Set<Dialect> downstreamDialects,116 Capabilities capabilities) {117 try {118 HttpClient client = HttpClient.Factory.createDefault().createClient(url);119 Command command = new Command(120 null,121 DriverCommand.NEW_SESSION,122 ImmutableMap.of("desiredCapabilities", capabilities));123 ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);124 SessionCodec codec;125 Dialect upstream = result.getDialect();126 Dialect downstream;127 if (downstreamDialects.contains(result.getDialect())) {128 codec = new Passthrough(url);129 downstream = upstream;130 } else {131 downstream = downstreamDialects.isEmpty() ? OSS : downstreamDialects.iterator().next();132 codec = new ProtocolConverter(133 url,134 getCommandCodec(downstream),135 getResponseCodec(downstream),136 getCommandCodec(upstream),137 getResponseCodec(upstream));...

Full Screen

Full Screen

Source:DockerSessionFactory.java Github

copy

Full Screen

...33import org.openqa.selenium.net.PortProber;34import org.openqa.selenium.remote.Command;35import org.openqa.selenium.remote.Dialect;36import org.openqa.selenium.remote.DriverCommand;37import org.openqa.selenium.remote.ProtocolHandshake;38import org.openqa.selenium.remote.Response;39import org.openqa.selenium.remote.SessionId;40import org.openqa.selenium.remote.http.HttpClient;41import org.openqa.selenium.remote.http.HttpRequest;42import org.openqa.selenium.remote.http.HttpResponse;43import org.openqa.selenium.support.ui.FluentWait;44import org.openqa.selenium.support.ui.Wait;45import java.io.IOException;46import java.io.UncheckedIOException;47import java.net.MalformedURLException;48import java.net.URL;49import java.time.Duration;50import java.util.Map;51import java.util.Objects;52import java.util.Optional;53import java.util.logging.Level;54import java.util.logging.Logger;55public class DockerSessionFactory implements SessionFactory {56 public static final Logger LOG = Logger.getLogger(DockerSessionFactory.class.getName());57 private final HttpClient.Factory clientFactory;58 private final Docker docker;59 private final Image image;60 private final Capabilities stereotype;61 public DockerSessionFactory(62 HttpClient.Factory clientFactory,63 Docker docker,64 Image image,65 Capabilities stereotype) {66 this.clientFactory = Objects.requireNonNull(clientFactory, "HTTP client must be set.");67 this.docker = Objects.requireNonNull(docker, "Docker command must be set.");68 this.image = Objects.requireNonNull(image, "Docker image to use must be set.");69 this.stereotype = ImmutableCapabilities.copyOf(70 Objects.requireNonNull(stereotype, "Stereotype must be set."));71 }72 @Override73 public boolean test(Capabilities capabilities) {74 return stereotype.getCapabilityNames().stream()75 .map(name -> Objects.equals(stereotype.getCapability(name), capabilities.getCapability(name)))76 .reduce(Boolean::logicalAnd)77 .orElse(false);78 }79 @Override80 public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {81 LOG.info("Starting session for " + sessionRequest.getCapabilities());82 int port = PortProber.findFreePort();83 URL remoteAddress = getUrl(port);84 HttpClient client = clientFactory.createClient(remoteAddress);85 LOG.info("Creating container, mapping container port 4444 to " + port);86 Container container = docker.create(image(image).map(Port.tcp(4444), Port.tcp(port)));87 container.start();88 LOG.info(String.format("Waiting for server to start (container id: %s)", container.getId()));89 try {90 waitForServerToStart(client, Duration.ofMinutes(1));91 } catch (TimeoutException e) {92 container.stop(Duration.ofMinutes(1));93 container.delete();94 LOG.warning(String.format(95 "Unable to connect to docker server (container id: %s)", container.getId()));96 return Optional.empty();97 }98 LOG.info(String.format("Server is ready (container id: %s)", container.getId()));99 Command command = new Command(100 null,101 DriverCommand.NEW_SESSION(sessionRequest.getCapabilities()));102 ProtocolHandshake.Result result;103 Response response;104 try {105 result = new ProtocolHandshake().createSession(client, command);106 response = result.createResponse();107 } catch (IOException | RuntimeException e) {108 container.stop(Duration.ofMinutes(1));109 container.delete();110 LOG.log(Level.WARNING, "Unable to create session: " + e.getMessage(), e);111 return Optional.empty();112 }113 SessionId id = new SessionId(response.getSessionId());114 Capabilities capabilities = new ImmutableCapabilities((Map<?, ?>) response.getValue());115 Dialect downstream = sessionRequest.getDownstreamDialects().contains(result.getDialect()) ?116 result.getDialect() :117 W3C;118 LOG.info(String.format(119 "Created session: %s - %s (container id: %s)",...

Full Screen

Full Screen

Source:myHttpCommandExecutor.java Github

copy

Full Screen

...12import org.openqa.selenium.remote.CommandCodec;13import org.openqa.selenium.remote.Dialect;14import org.openqa.selenium.remote.HttpCommandExecutor;15import org.openqa.selenium.remote.HttpSessionId;16import org.openqa.selenium.remote.ProtocolHandshake;17import org.openqa.selenium.remote.Response;18import org.openqa.selenium.remote.ResponseCodec;19import org.openqa.selenium.remote.http.HttpClient;20import org.openqa.selenium.remote.http.HttpRequest;21import org.openqa.selenium.remote.http.HttpResponse;22import org.openqa.selenium.remote.http.W3CHttpCommandCodec;23import org.openqa.selenium.remote.http.W3CHttpResponseCodec;24public class myHttpCommandExecutor extends HttpCommandExecutor {25 private CommandCodec<HttpRequest> mycommandCodec;26 private ResponseCodec<HttpResponse> myresponseCodec;27 private final HttpClient myclient;28 public myHttpCommandExecutor(URL addressOfRemoteServer) {29 super(addressOfRemoteServer);30 initCodec();31 this.myclient = HttpClient.Factory.createDefault().createClient(addressOfRemoteServer);32 }33 private void initCodec() {34 mycommandCodec = new W3CHttpCommandCodec();35 myresponseCodec = new W3CHttpResponseCodec();36 }37 public Response execute(Command command) throws IOException {38 if (command.getSessionId() == null) {39 if (QUIT.equals(command.getName())) {40 return new Response();41 }42 if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) {43 throw new NoSuchSessionException("Session ID is null. Using WebDriver after calling quit()?");44 }45 }46 if (NEW_SESSION.equals(command.getName())) {47 if (mycommandCodec != null) {48 throw new SessionNotCreatedException("Session already exists");49 }50 ProtocolHandshake handshake = new ProtocolHandshake();51 ProtocolHandshake.Result result = handshake.createSession(myclient, command);52 Dialect dialect = result.getDialect();53 mycommandCodec = dialect.getCommandCodec();54 myresponseCodec = dialect.getResponseCodec();55 return result.createResponse();56 }57 if (mycommandCodec == null || myresponseCodec == null) {58 throw new WebDriverException("No command or response codec has been defined. Unable to proceed");59 }60 HttpRequest httpRequest = mycommandCodec.encode(command);61 try {62 HttpResponse httpResponse = myclient.execute(httpRequest);63 Response response = myresponseCodec.decode(httpResponse);64 if (response.getSessionId() == null) {65 if (httpResponse.getTargetHost() != null) {...

Full Screen

Full Screen

Source:DriverServiceSessionFactory.java Github

copy

Full Screen

...23import org.openqa.selenium.grid.node.SessionFactory;24import org.openqa.selenium.remote.Command;25import org.openqa.selenium.remote.Dialect;26import org.openqa.selenium.remote.DriverCommand;27import org.openqa.selenium.remote.ProtocolHandshake;28import org.openqa.selenium.remote.Response;29import org.openqa.selenium.remote.SessionId;30import org.openqa.selenium.remote.http.HttpClient;31import org.openqa.selenium.remote.service.DriverService;32import java.util.Map;33import java.util.Objects;34import java.util.Optional;35import java.util.Set;36import java.util.function.Predicate;37public class DriverServiceSessionFactory implements SessionFactory {38 private final HttpClient.Factory clientFactory;39 private final Predicate<Capabilities> predicate;40 private final DriverService.Builder builder;41 public DriverServiceSessionFactory(42 HttpClient.Factory clientFactory,43 Predicate<Capabilities> predicate,44 DriverService.Builder builder) {45 this.clientFactory = Objects.requireNonNull(clientFactory);46 this.predicate = Objects.requireNonNull(predicate);47 this.builder = Objects.requireNonNull(builder);48 }49 @Override50 public boolean test(Capabilities capabilities) {51 return predicate.test(capabilities);52 }53 @Override54 public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {55 if (sessionRequest.getDownstreamDialects().isEmpty()) {56 return Optional.empty();57 }58 DriverService service = builder.build();59 try {60 service.start();61 HttpClient client = clientFactory.createClient(service.getUrl());62 Command command = new Command(63 null,64 DriverCommand.NEW_SESSION(sessionRequest.getCapabilities()));65 ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);66 Set<Dialect> downstreamDialects = sessionRequest.getDownstreamDialects();67 Dialect upstream = result.getDialect();68 Dialect downstream = downstreamDialects.contains(result.getDialect()) ?69 result.getDialect() :70 downstreamDialects.iterator().next();71 Response response = result.createResponse();72 return Optional.of(73 new ProtocolConvertingSession(74 client,75 new SessionId(response.getSessionId()),76 service.getUrl(),77 downstream,78 upstream,79 new ImmutableCapabilities((Map<?, ?>)response.getValue())) {...

Full Screen

Full Screen

ProtocolHandshake

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.ProtocolHandshake;2import org.openqa.selenium.remote.internal.HttpClientFactory;3import org.openqa.selenium.remote.DesiredCapabilities;4import org.openqa.selenium.remote.RemoteWebDriver;5import java.net.URL;6public class RemoteWebDriverExample {7 public static void main(String[] args) {8 DesiredCapabilities capabilities = DesiredCapabilities.chrome();9 ProtocolHandshake protocolHandshake = new ProtocolHandshake();10 HttpClientFactory httpClientFactory = new HttpClientFactory();11 RemoteWebDriver driver = new RemoteWebDriver(httpClientFactory, protocolHandshake.createSession(capabilities, url));12 System.out.println("Page title is: " + driver.getTitle());13 driver.quit();14 }15}16Selenium WebDriver – WebDriverException – Unable to create new remote session. desired capabilities = Capabilities {browserName=chrome, version=, platform=ANY}17Selenium WebDriver – WebDriverException – Unable to create new remote session. desired capabilities = Capabilities {browserName=chrome, version=, platform=ANY}18Selenium WebDriver – WebDriverException – Unable to create new remote session. desired capabilities = Capabilities {browserName=chrome, version=, platform=ANY}19Selenium WebDriver – WebDriverException – Unable to create new remote session. desired capabilities = Capabilities {browserName=chrome, version=, platform=ANY}20Selenium WebDriver – WebDriverException – Unable to create new remote session. desired capabilities = Capabilities {browserName=chrome, version=, platform=ANY}

Full Screen

Full Screen

ProtocolHandshake

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.internal.ProtocolHandshake;2import org.openqa.selenium.remote.DesiredCapabilities;3DesiredCapabilities capabilities = DesiredCapabilities.chrome();4ProtocolHandshake handshake = new ProtocolHandshake();5handshake.createSession(capabilities);6String sessionId = response.getSessionId();7Capabilities capabilities = response.getCapabilities();8String proxyId = response.getProxyId();9int statusCode = response.getStatusCode();10String statusMessage = response.getStatusMessage();11String message = response.getValue("message");12String value = response.getValue("value");13String sessionId = response.getValue("sessionId");14String proxyId = response.getValue("proxyId");15int status = response.getValue("status");16String state = response.getValue("state");17String className = response.getValue("class");18String build = response.getValue("build");19String os = response.getValue("os");20String version = response.getValue("version");21String browserName = response.getValue("browserName");

Full Screen

Full Screen

ProtocolHandshake

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.ProtocolHandshake;2ProtocolHandshake.Result result = ProtocolHandshake.createSession(hubConnection, desiredCapabilities);3import org.openqa.selenium.remote.ProtocolHandshake.Result;4public class Result {5 private final Capabilities capabilities;6 private final SessionId sessionId;7 public Result(Capabilities capabilities, SessionId sessionId) {8 this.capabilities = capabilities;9 this.sessionId = sessionId;10 }11 public Capabilities getCapabilities() {12 return capabilities;13 }14 public SessionId getSessionId() {15 return sessionId;16 }17}18import org.openqa.selenium.remote.ProtocolHandshake.Result;19public class Result {20 private final Capabilities capabilities;21 private final SessionId sessionId;22 public Result(Capabilities capabilities, SessionId sessionId) {23 this.capabilities = capabilities;24 this.sessionId = sessionId;25 }26 public Capabilities getCapabilities() {27 return capabilities;28 }29 public SessionId getSessionId() {30 return sessionId;31 }32}33import org.openqa.selenium.remote.ProtocolHandshake.Result;34public class Result {35 private final Capabilities capabilities;36 private final SessionId sessionId;37 public Result(Capabilities capabilities, SessionId sessionId) {38 this.capabilities = capabilities;39 this.sessionId = sessionId;40 }41 public Capabilities getCapabilities() {42 return capabilities;43 }44 public SessionId getSessionId() {45 return sessionId;46 }47}48import org.openqa.selenium.remote.ProtocolHandshake.Result;49public class Result {50 private final Capabilities capabilities;51 private final SessionId sessionId;52 public Result(Capabilities capabilities, SessionId sessionId) {53 this.capabilities = capabilities;54 this.sessionId = sessionId;55 }56 public Capabilities getCapabilities() {57 return capabilities;58 }59 public SessionId getSessionId() {60 return sessionId;61 }62}63import org.openqa.selenium.remote.ProtocolHandshake.Result;64public class Result {65 private final Capabilities capabilities;66 private final SessionId sessionId;67 public Result(Capabilities capabilities, SessionId sessionId) {68 this.sessionId = sessionId;69 }70 public Capabilities getCapabilities() {71 return capabilities;72 }73 public SessionId getSessionId() {74 return sessionId;75 }76}77import org.openqa.selenium.remote.ProtocolHandshake.Result;78public class Result {79 private final Capabilities capabilities;80 private final SessionId sessionId;81 public Result(Capabilities capabilities, SessionId sessionId) {82 this.capabilities = capabilities;83 this.sessionId = sessionId;84 }85 public Capabilities getCapabilities() {86 return capabilities;87 }88 public SessionId getSessionId() {89 return sessionId;90 }91}92import org.openqa.selenium.remote.ProtocolHandshake.Result;93public class Result {94 private final Capabilities capabilities;95 private final SessionId sessionId;96 public Result(Capabilities capabilities, SessionId sessionId) {97 this.capabilities = capabilities;98 this.sessionId = sessionId;99 }100 public Capabilities getCapabilities() {101 return capabilities;102 }103 public SessionId getSessionId() {104 return sessionId;105 }106}107import org.openqa.selenium.remote.ProtocolHandshake.Result;108public class Result {109 private final Capabilities capabilities;110 private final SessionId sessionId;111 public Result(Capabilities capabilities, SessionId sessionId) {112String sessionId = response.getSessionId();113Capabilities capabilities = response.getCapabilities();114String proxyId = response.getProxyId();115int statusCode = response.getStatusCode();116String statusMessage = response.getStatusMessage();117String message = response.getValue("message");118String value = response.getValue("value");119String sessionId = response.getValue("sessionId");120String proxyId = response.getValue("proxyId");121int status = response.getValue("status");122String state = response.getValue("state");123String className = response.getValue("class");124String build = response.getValue("build");125String os = response.getValue("os");126String version = response.getValue("version");127String browserName = response.getValue("browserName");

Full Screen

Full Screen

ProtocolHandshake

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.ProtocolHandshake;2ProtocolHandshake.Result result = ProtocolHandshake.createSession(hubConnection, desiredCapabilities);3import org.openqa.selenium.remote.ProtocolHandshake.Result;4public class Result {5 private final Capabilities capabilities;6 private final SessionId sessionId;7 public Result(Capabilities capabilities, SessionId sessionId) {8 this.capabilities = capabilities;9 this.sessionId = sessionId;10 }11 public Capabilities getCapabilities() {12 return capabilities;13 }14 public SessionId getSessionId() {15 return sessionId;16 }17}18import org.openqa.selenium.remote.ProtocolHandshake.Result;19public class Result {20 private final Capabilities capabilities;21 private final SessionId sessionId;22 public Result(Capabilities capabilities, SessionId sessionId) {23 this.capabilities = capabilities;24 this.sessionId = sessionId;25 }26 public Capabilities getCapabilities() {27 return capabilities;28 }29 public SessionId getSessionId() {30 return sessionId;31 }32}33import org.openqa.selenium.remote.ProtocolHandshake.Result;34public class Result {35 private final Capabilities capabilities;36 private final SessionId sessionId;37 public Result(Capabilities capabilities, SessionId sessionId) {38 this.capabilities = capabilities;39 this.sessionId = sessionId;40 }41 public Capabilities getCapabilities() {42 return capabilities;43 }44 public SessionId getSessionId() {45 return sessionId;46 }47}48import org.openqa.selenium.remote.ProtocolHandshake.Result;49public class Result {50 private final Capabilities capabilities;51 private final SessionId sessionId;52 public Result(Capabilities capabilities, SessionId sessionId) {53 this.capabilities = capabilities;54 this.sessionId = sessionId;55 }56 public Capabilities getCapabilities() {57 return capabilities;58 }59 public SessionId getSessionId() {60 return sessionId;61 }62}63import org.openqa.selenium.remote.ProtocolHandshake.Result;64public class Result {65 private final Capabilities capabilities;66 private final SessionId sessionId;67 public Result(Capabilities capabilities, SessionId sessionId) {

Full Screen

Full Screen
copy
1String fooString1 = new String("foo");2String fooString2 = new String("foo");34// Evaluates to false5fooString1 == fooString2;67// Evaluates to true8fooString1.equals(fooString2);910// Evaluates to true, because Java uses the same object11"bar" == "bar";12
Full Screen
copy
1String a="Test";2String b="Test";3if(a==b) ===> true4
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.

Most used methods in ProtocolHandshake

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