How to use create method of org.openqa.selenium.remote.NewSessionPayload class

Best Selenium code snippet using org.openqa.selenium.remote.NewSessionPayload.create

Source:DistributorTest.java Github

copy

Full Screen

...77 @Before78 public void setUp() throws MalformedURLException {79 tracer = DistributedTracer.builder().build();80 bus = new GuavaEventBus();81 clientFactory = HttpClient.Factory.createDefault();82 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);83 local = new LocalDistributor(tracer, bus, HttpClient.Factory.createDefault(), sessions);84 distributor = new RemoteDistributor(85 tracer,86 new PassthroughHttpClient.Factory<>(local),87 new URL("http://does.not.exist/"));88 caps = new ImmutableCapabilities("browserName", "cheese");89 }90 @Test91 public void creatingANewSessionWithoutANodeEndsInFailure() {92 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {93 assertThatExceptionOfType(SessionNotCreatedException.class)94 .isThrownBy(() -> distributor.newSession(createRequest(payload)));95 }96 }97 @Test98 public void shouldBeAbleToAddANodeAndCreateASession() throws URISyntaxException {99 URI nodeUri = new URI("http://example:5678");100 URI routableUri = new URI("http://localhost:1234");101 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);102 LocalNode node = LocalNode.builder(tracer, bus, clientFactory, routableUri)103 .add(caps, new TestSessionFactory((id, c) -> new Session(id, nodeUri, c)))104 .build();105 Distributor distributor = new LocalDistributor(106 tracer,107 bus,108 new PassthroughHttpClient.Factory<>(node),109 sessions);110 distributor.add(node);111 MutableCapabilities sessionCaps = new MutableCapabilities(caps);112 sessionCaps.setCapability("sausages", "gravy");113 try (NewSessionPayload payload = NewSessionPayload.create(sessionCaps)) {114 Session session = distributor.newSession(createRequest(payload)).getSession();115 assertThat(session.getCapabilities()).isEqualTo(sessionCaps);116 assertThat(session.getUri()).isEqualTo(routableUri);117 }118 }119 @Test120 public void creatingASessionAddsItToTheSessionMap() throws URISyntaxException {121 URI nodeUri = new URI("http://example:5678");122 URI routableUri = new URI("http://localhost:1234");123 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);124 LocalNode node = LocalNode.builder(tracer, bus, clientFactory, routableUri)125 .add(caps, new TestSessionFactory((id, c) -> new Session(id, nodeUri, c)))126 .build();127 Distributor distributor = new LocalDistributor(128 tracer,129 bus,130 new PassthroughHttpClient.Factory<>(node),131 sessions);132 distributor.add(node);133 MutableCapabilities sessionCaps = new MutableCapabilities(caps);134 sessionCaps.setCapability("sausages", "gravy");135 try (NewSessionPayload payload = NewSessionPayload.create(sessionCaps)) {136 Session returned = distributor.newSession(createRequest(payload)).getSession();137 Session session = sessions.get(returned.getId());138 assertThat(session.getCapabilities()).isEqualTo(sessionCaps);139 assertThat(session.getUri()).isEqualTo(routableUri);140 }141 }142 @Test143 public void shouldBeAbleToRemoveANode() throws URISyntaxException, MalformedURLException {144 URI nodeUri = new URI("http://example:5678");145 URI routableUri = new URI("http://localhost:1234");146 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);147 LocalNode node = LocalNode.builder(tracer, bus, clientFactory, routableUri)148 .add(caps, new TestSessionFactory((id, c) -> new Session(id, nodeUri, c)))149 .build();150 Distributor local = new LocalDistributor(151 tracer,152 bus,153 new PassthroughHttpClient.Factory<>(node),154 sessions);155 distributor = new RemoteDistributor(156 tracer,157 new PassthroughHttpClient.Factory<>(local),158 new URL("http://does.not.exist"));159 distributor.add(node);160 distributor.remove(node.getId());161 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {162 assertThatExceptionOfType(SessionNotCreatedException.class)163 .isThrownBy(() -> distributor.newSession(createRequest(payload)));164 }165 }166 @Test167 public void registeringTheSameNodeMultipleTimesOnlyCountsTheFirstTime()168 throws URISyntaxException {169 URI nodeUri = new URI("http://example:5678");170 URI routableUri = new URI("http://localhost:1234");171 LocalNode node = LocalNode.builder(tracer, bus, clientFactory, routableUri)172 .add(caps, new TestSessionFactory((id, c) -> new Session(id, nodeUri, c)))173 .build();174 local.add(node);175 local.add(node);176 DistributorStatus status = local.getStatus();177 assertThat(status.getNodes().size()).isEqualTo(1);178 }179 @Test180 public void theMostLightlyLoadedNodeIsSelectedFirst() {181 // Create enough hosts so that we avoid the scheduler returning hosts in:182 // * insertion order183 // * reverse insertion order184 // * sorted with most heavily used first185 SessionMap sessions = new LocalSessionMap(tracer, bus);186 Node lightest = createNode(caps, 10, 0);187 Node medium = createNode(caps, 10, 4);188 Node heavy = createNode(caps, 10, 6);189 Node massive = createNode(caps, 10, 8);190 CombinedHandler handler = new CombinedHandler();191 handler.addHandler(lightest);192 handler.addHandler(medium);193 handler.addHandler(heavy);194 handler.addHandler(massive);195 Distributor distributor = new LocalDistributor(196 tracer,197 bus,198 new PassthroughHttpClient.Factory<>(handler),199 sessions)200 .add(heavy)201 .add(medium)202 .add(lightest)203 .add(massive);204 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {205 Session session = distributor.newSession(createRequest(payload)).getSession();206 assertThat(session.getUri()).isEqualTo(lightest.getStatus().getUri());207 }208 }209 @Test210 public void shouldUseLastSessionCreatedTimeAsTieBreaker() {211 SessionMap sessions = new LocalSessionMap(tracer, bus);212 Node leastRecent = createNode(caps, 5, 0);213 CombinedHandler handler = new CombinedHandler();214 handler.addHandler(sessions);215 handler.addHandler(leastRecent);216 Distributor distributor = new LocalDistributor(217 tracer,218 bus,219 new PassthroughHttpClient.Factory<>(handler),220 sessions)221 .add(leastRecent);222 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {223 distributor.newSession(createRequest(payload));224 // Will be "leastRecent" by default225 }226 Node middle = createNode(caps, 5, 0);227 handler.addHandler(middle);228 distributor.add(middle);229 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {230 Session session = distributor.newSession(createRequest(payload)).getSession();231 // Least lightly loaded is middle232 assertThat(session.getUri()).isEqualTo(middle.getStatus().getUri());233 }234 Node mostRecent = createNode(caps, 5, 0);235 handler.addHandler(mostRecent);236 distributor.add(mostRecent);237 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {238 Session session = distributor.newSession(createRequest(payload)).getSession();239 // Least lightly loaded is most recent240 assertThat(session.getUri()).isEqualTo(mostRecent.getStatus().getUri());241 }242 // All the nodes should be equally loaded.243 Map<Capabilities, Integer> expected = mostRecent.getStatus().getStereotypes();244 assertThat(leastRecent.getStatus().getStereotypes()).isEqualTo(expected);245 assertThat(middle.getStatus().getStereotypes()).isEqualTo(expected);246 // All nodes are now equally loaded. We should be going in time order now247 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {248 Session session = distributor.newSession(createRequest(payload)).getSession();249 assertThat(session.getUri()).isEqualTo(leastRecent.getStatus().getUri());250 }251 }252 @Test253 public void shouldIncludeHostsThatAreUpInHostList() {254 CombinedHandler handler = new CombinedHandler();255 SessionMap sessions = new LocalSessionMap(tracer, bus);256 handler.addHandler(sessions);257 URI uri = createUri();258 Node alwaysDown = LocalNode.builder(tracer, bus, clientFactory, uri)259 .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, c)))260 .advanced()261 .healthCheck(() -> new HealthCheck.Result(false, "Boo!"))262 .build();263 handler.addHandler(alwaysDown);264 Node alwaysUp = LocalNode.builder(tracer, bus, clientFactory, uri)265 .add(caps, new TestSessionFactory((id, c) -> new Session(id, uri, c)))266 .advanced()267 .healthCheck(() -> new HealthCheck.Result(true, "Yay!"))268 .build();269 handler.addHandler(alwaysUp);270 LocalDistributor distributor = new LocalDistributor(271 tracer,272 bus,273 new PassthroughHttpClient.Factory<>(handler),274 sessions);275 handler.addHandler(distributor);276 distributor.add(alwaysDown);277 // Should be unable to create a session because the node is down.278 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {279 assertThatExceptionOfType(SessionNotCreatedException.class)280 .isThrownBy(() -> distributor.newSession(createRequest(payload)));281 }282 distributor.add(alwaysUp);283 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {284 distributor.newSession(createRequest(payload));285 }286 }287 @Test288 public void shouldNotScheduleAJobIfAllSlotsAreBeingUsed() {289 SessionMap sessions = new LocalSessionMap(tracer, bus);290 CombinedHandler handler = new CombinedHandler();291 Distributor distributor = new LocalDistributor(292 tracer,293 bus,294 new PassthroughHttpClient.Factory<>(handler),295 sessions);296 handler.addHandler(distributor);297 Node node = createNode(caps, 1, 0);298 handler.addHandler(node);299 distributor.add(node);300 // Use up the one slot available301 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {302 distributor.newSession(createRequest(payload));303 }304 // Now try and create a session.305 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {306 assertThatExceptionOfType(SessionNotCreatedException.class)307 .isThrownBy(() -> distributor.newSession(createRequest(payload)));308 }309 }310 @Test311 public void shouldReleaseSlotOnceSessionEnds() {312 SessionMap sessions = new LocalSessionMap(tracer, bus);313 CombinedHandler handler = new CombinedHandler();314 Distributor distributor = new LocalDistributor(315 tracer,316 bus,317 new PassthroughHttpClient.Factory<>(handler),318 sessions);319 handler.addHandler(distributor);320 Node node = createNode(caps, 1, 0);321 handler.addHandler(node);322 distributor.add(node);323 // Use up the one slot available324 Session session;325 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {326 session = distributor.newSession(createRequest(payload)).getSession();327 }328 // Make sure the session map has the session329 sessions.get(session.getId());330 node.stop(session.getId());331 // Now wait for the session map to say the session is gone.332 Wait<Object> wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(2));333 wait.until(obj -> {334 try {335 sessions.get(session.getId());336 return false;337 } catch (NoSuchSessionException e) {338 return true;339 }340 });341 wait.until(obj -> distributor.getStatus().hasCapacity());342 // And we should now be able to create another session.343 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {344 distributor.newSession(createRequest(payload));345 }346 }347 @Test348 public void shouldNotStartASessionIfTheCapabilitiesAreNotSupported() {349 CombinedHandler handler = new CombinedHandler();350 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);351 handler.addHandler(handler);352 Distributor distributor = new LocalDistributor(353 tracer,354 bus,355 new PassthroughHttpClient.Factory<>(handler),356 sessions);357 handler.addHandler(distributor);358 Node node = createNode(caps, 1, 0);359 handler.addHandler(node);360 distributor.add(node);361 ImmutableCapabilities unmatched = new ImmutableCapabilities("browserName", "transit of venus");362 try (NewSessionPayload payload = NewSessionPayload.create(unmatched)) {363 assertThatExceptionOfType(SessionNotCreatedException.class)364 .isThrownBy(() -> distributor.newSession(createRequest(payload)));365 }366 }367 @Test368 public void attemptingToStartASessionWhichFailsMarksAsTheSlotAsAvailable() {369 CombinedHandler handler = new CombinedHandler();370 SessionMap sessions = new LocalSessionMap(tracer, bus);371 handler.addHandler(sessions);372 URI uri = createUri();373 Node node = LocalNode.builder(tracer, bus, clientFactory, uri)374 .add(caps, new TestSessionFactory((id, caps) -> {375 throw new SessionNotCreatedException("OMG");376 }))377 .build();378 handler.addHandler(node);379 Distributor distributor = new LocalDistributor(380 tracer,381 bus,382 new PassthroughHttpClient.Factory<>(handler),383 sessions);384 handler.addHandler(distributor);385 distributor.add(node);386 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {387 assertThatExceptionOfType(SessionNotCreatedException.class)388 .isThrownBy(() -> distributor.newSession(createRequest(payload)));389 }390 assertThat(distributor.getStatus().hasCapacity()).isTrue();391 }392 @Test393 public void shouldReturnNodesThatWereDownToPoolOfNodesOnceTheyMarkTheirHealthCheckPasses() {394 CombinedHandler handler = new CombinedHandler();395 SessionMap sessions = new LocalSessionMap(tracer, bus);396 handler.addHandler(sessions);397 AtomicBoolean isUp = new AtomicBoolean(false);398 URI uri = createUri();399 Node node = LocalNode.builder(tracer, bus, clientFactory, uri)400 .add(caps, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))401 .advanced()402 .healthCheck(() -> new HealthCheck.Result(isUp.get(), "TL;DR"))403 .build();404 handler.addHandler(node);405 LocalDistributor distributor = new LocalDistributor(406 tracer,407 bus,408 new PassthroughHttpClient.Factory<>(handler),409 sessions);410 handler.addHandler(distributor);411 distributor.add(node);412 // Should be unable to create a session because the node is down.413 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {414 assertThatExceptionOfType(SessionNotCreatedException.class)415 .isThrownBy(() -> distributor.newSession(createRequest(payload)));416 }417 // Mark the node as being up418 isUp.set(true);419 // Kick the machinery to ensure that everything is fine.420 distributor.refresh();421 // Because the node is now up and running, we should now be able to create a session422 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {423 distributor.newSession(createRequest(payload));424 }425 }426 @Test427 @Ignore428 public void shouldPriotizeHostsWithTheMostSlotsAvailableForASessionType() {429 // Consider the case where you have 1 Windows machine and 5 linux machines. All of these hosts430 // can run Chrome and Firefox sessions, but only one can run Edge sessions. Ideally, the machine431 // able to run Edge would be sorted last.432 fail("Write me");433 }434 private Node createNode(Capabilities stereotype, int count, int currentLoad) {435 URI uri = createUri();436 LocalNode.Builder builder = LocalNode.builder(tracer, bus, clientFactory, uri);437 for (int i = 0; i < count; i++) {438 builder.add(stereotype, new TestSessionFactory((id, caps) -> new HandledSession(uri, caps)));439 }440 LocalNode node = builder.build();441 for (int i = 0; i < currentLoad; i++) {442 // Ignore the session. We're just creating load.443 node.newSession(new CreateSessionRequest(444 ImmutableSet.copyOf(Dialect.values()),445 stereotype,446 ImmutableMap.of()));447 }448 return node;449 }450 @Test451 @Ignore452 public void shouldCorrectlySetSessionCountsWhenStartedAfterNodeWithSession() {453 fail("write me");454 }455 @Test456 public void statusShouldIndicateThatDistributorIsNotAvailableIfNodesAreDown()457 throws URISyntaxException {458 Capabilities capabilities = new ImmutableCapabilities("cheese", "peas");459 URI uri = new URI("http://exmaple.com");460 Node node = LocalNode.builder(tracer, bus, clientFactory, uri)461 .add(capabilities, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))462 .advanced()463 .healthCheck(() -> new HealthCheck.Result(false, "TL;DR"))464 .build();465 local.add(node);466 DistributorStatus status = local.getStatus();467 assertFalse(status.hasCapacity());468 }469 private HttpRequest createRequest(NewSessionPayload payload) {470 StringBuilder builder = new StringBuilder();471 try {472 payload.writeTo(builder);473 } catch (IOException e) {474 throw new UncheckedIOException(e);475 }476 HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/session");477 request.setContent(utf8String(builder.toString()));478 return request;479 }480 private URI createUri() {481 try {482 return new URI("http://localhost:" + PortProber.findFreePort());483 } catch (URISyntaxException e) {484 throw new RuntimeException(e);485 }486 }487 class HandledSession extends Session implements CommandHandler {488 HandledSession(URI uri, Capabilities caps) {489 super(new SessionId(UUID.randomUUID()), uri, caps);490 }491 @Override492 public void execute(HttpRequest req, HttpResponse resp) {493 // no-op494 }...

Full Screen

Full Screen

Source:NewSessionPayload.java Github

copy

Full Screen

...76 private final static Predicate<String> ACCEPTED_W3C_PATTERNS = new AcceptedW3CCapabilityKeys();77 private final Json json = new Json();78 private final FileBackedOutputStream backingStore;79 private final ImmutableSet<Dialect> dialects;80 public static NewSessionPayload create(Capabilities caps) {81 // We need to convert the capabilities into a new session payload. At this point we're dealing82 // with references, so I'm Just Sure This Will Be Fine.83 return create(ImmutableMap.of("desiredCapabilities", caps.asMap()));84 }85 public static NewSessionPayload create(Map<String, ?> source) {86 Objects.requireNonNull(source, "Payload must be set");87 String json = new Json().toJson(source);88 return new NewSessionPayload(new StringReader(json));89 }90 public static NewSessionPayload create(Reader source) {91 return new NewSessionPayload(source);92 }93 private NewSessionPayload(Reader source) {94 // Dedicate up to 10% of all RAM or 20% of available RAM (whichever is smaller) to storing this95 // payload.96 int threshold = (int) Math.min(97 Integer.MAX_VALUE,98 Math.min(99 Runtime.getRuntime().freeMemory() / 5,100 Runtime.getRuntime().maxMemory() / 10));101 backingStore = new FileBackedOutputStream(threshold);102 try (Writer writer = new OutputStreamWriter(backingStore, UTF_8)) {103 CharStreams.copy(source, writer);104 } catch (IOException e) {105 throw new UncheckedIOException(e);106 }107 ImmutableSet.Builder<CapabilitiesFilter> adapters = ImmutableSet.builder();108 ServiceLoader.load(CapabilitiesFilter.class).forEach(adapters::add);109 adapters110 .add(new ChromeFilter())111 .add(new EdgeFilter())112 .add(new FirefoxFilter())113 .add(new InternetExplorerFilter())114 .add(new OperaFilter())115 .add(new SafariFilter());116 this.adapters = adapters.build();117 ImmutableSet.Builder<CapabilityTransform> transforms = ImmutableSet.builder();118 ServiceLoader.load(CapabilityTransform.class).forEach(transforms::add);119 transforms120 .add(new ProxyTransform())121 .add(new StripAnyPlatform())122 .add(new W3CPlatformNameNormaliser());123 this.transforms = transforms.build();124 ImmutableSet.Builder<Dialect> dialects = ImmutableSet.builder();125 try {126 if (getOss() != null) {127 dialects.add(Dialect.OSS);128 }129 if (getAlwaysMatch() != null || getFirstMatches() != null) {130 dialects.add(Dialect.W3C);131 }132 this.dialects = dialects.build();133 validate();134 } catch (IOException e) {135 throw new UncheckedIOException(e);136 }137 }138 private void validate() throws IOException {139 Map<String, Object> alwaysMatch = getAlwaysMatch();140 if (alwaysMatch == null) {141 alwaysMatch = ImmutableMap.of();142 }143 Map<String, Object> always = alwaysMatch;144 Collection<Map<String, Object>> firsts = getFirstMatches();145 if (firsts == null) {146 firsts = ImmutableList.of(ImmutableMap.of());147 }148 if (firsts.isEmpty()) {149 throw new IllegalArgumentException("First match w3c capabilities is zero length");150 }151 firsts.stream()152 .peek(map -> {153 Set<String> overlap = Sets.intersection(always.keySet(), map.keySet());154 if (!overlap.isEmpty()) {155 throw new IllegalArgumentException(156 "Overlapping keys between w3c always and first match capabilities: " + overlap);157 }158 })159 .map(first -> {160 Map<String, Object> toReturn = new HashMap<>();161 toReturn.putAll(always);162 toReturn.putAll(first);163 return toReturn;164 })165 .peek(map -> {166 ImmutableSortedSet<String> nullKeys = map.entrySet().stream()167 .filter(entry -> entry.getValue() == null)168 .map(Map.Entry::getKey)169 .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));170 if (!nullKeys.isEmpty()) {171 throw new IllegalArgumentException(172 "Null values found in w3c capabilities. Keys are: " + nullKeys);173 }174 })175 .peek(map -> {176 ImmutableSortedSet<String> illegalKeys = map.entrySet().stream()177 .filter(entry -> !ACCEPTED_W3C_PATTERNS.test(entry.getKey()))178 .map(Map.Entry::getKey)179 .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));180 if (!illegalKeys.isEmpty()) {181 throw new IllegalArgumentException(182 "Illegal key values seen in w3c capabilities: " + illegalKeys);183 }184 })185 .forEach(map -> {});186 }187 public void writeTo(Appendable appendable) throws IOException {188 try (JsonOutput json = new Json().newOutput(appendable)) {189 json.beginObject();190 Map<String, Object> first = getOss();191 if (first == null) {192 //noinspection unchecked193 first = stream().findFirst()194 .orElse(new ImmutableCapabilities())195 .asMap();196 }197 Map<String, Object> ossFirst = new HashMap<>(first);198 if (first.containsKey(CapabilityType.PROXY)) {199 Map<String, Object> proxyMap;200 Object rawProxy = first.get(CapabilityType.PROXY);201 if (rawProxy instanceof Proxy) {202 proxyMap = ((Proxy) rawProxy).toJson();203 } else if (rawProxy instanceof Map) {204 proxyMap = (Map<String, Object>) rawProxy;205 } else {206 proxyMap = new HashMap<>();207 }208 if (proxyMap.containsKey("noProxy")) {209 Map<String, Object> ossProxyMap = new HashMap<>(proxyMap);210 Object rawData = proxyMap.get("noProxy");211 if (rawData instanceof List) {212 ossProxyMap.put("noProxy", ((List<String>) rawData).stream().collect(Collectors.joining(",")));213 }214 ossFirst.put(CapabilityType.PROXY, ossProxyMap);215 }216 }217 // Write the first capability we get as the desired capability.218 json.name("desiredCapabilities");219 json.write(ossFirst);220 // Now for the w3c capabilities221 json.name("capabilities");222 json.beginObject();223 // Then write everything into the w3c payload. Because of the way we do this, it's easiest224 // to just populate the "firstMatch" section. The spec says it's fine to omit the225 // "alwaysMatch" field, so we do this.226 json.name("firstMatch");227 json.beginArray();228 //noinspection unchecked229 getW3C().forEach(json::write);230 json.endArray();231 json.endObject(); // Close "capabilities" object232 writeMetaData(json);233 json.endObject();234 }235 }236 private void writeMetaData(JsonOutput out) throws IOException {237 CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);238 try (Reader reader = charSource.openBufferedStream();239 JsonInput input = json.newInput(reader)) {240 input.beginObject();241 while (input.hasNext()) {242 String name = input.nextName();243 switch (name) {244 case "capabilities":245 case "desiredCapabilities":246 case "requiredCapabilities":247 input.skipValue();248 break;249 default:250 out.name(name);251 out.write(input.<Object>read(Object.class));252 break;253 }254 }255 }256 }257 /**258 * Stream the {@link Capabilities} encoded in the payload used to create this instance. The259 * {@link Stream} will start with a {@link Capabilities} object matching the OSS capabilities, and260 * will then expand each of the "{@code firstMatch}" and "{@code alwaysMatch}" contents as defined261 * in the W3C WebDriver spec.262 * <p>263 * The OSS {@link Capabilities} are listed first because converting the OSS capabilities to the264 * equivalent W3C capabilities isn't particularly easy, so it's hoped that this approach gives us265 * the most compatible implementation.266 */267 public Stream<Capabilities> stream() {268 try {269 // OSS first270 Stream<Map<String, Object>> oss = Stream.of(getOss());271 // And now W3C272 Stream<Map<String, Object>> w3c = getW3C();...

Full Screen

Full Screen

Source:LocalNewSessionQueueTest.java Github

copy

Full Screen

...49 private HttpRequest expectedSessionRequest;50 private RequestId requestId;51 @Before52 public void setUp() {53 Tracer tracer = DefaultTestTracer.createTracer();54 caps = new ImmutableCapabilities("browserName", "chrome");55 bus = new GuavaEventBus();56 requestId = new RequestId(UUID.randomUUID());57 sessionQueue = new LocalNewSessionQueue(tracer, bus, Duration.ofSeconds(1));58 NewSessionPayload payload = NewSessionPayload.create(caps);59 expectedSessionRequest = createRequest(payload, POST, "/session");60 }61 @Test62 public void shouldBeAbleToAddToEndOfQueue() throws InterruptedException {63 AtomicBoolean result = new AtomicBoolean(false);64 CountDownLatch latch = new CountDownLatch(1);65 bus.addListener(NewSessionRequestEvent.listener(reqId -> {66 result.set(reqId.equals(requestId));67 latch.countDown();68 }));69 boolean added = sessionQueue.offerLast(expectedSessionRequest, requestId);70 assertTrue(added);71 72 latch.await(5, TimeUnit.SECONDS);73 assertThat(latch.getCount()).isEqualTo(0);74 assertTrue(result.get());75 }76 @Test77 public void shouldBeAbleToRemoveFromFrontOfQueue() {78 boolean added = sessionQueue.offerLast(expectedSessionRequest, requestId);79 assertTrue(added);80 Optional<HttpRequest> receivedRequest = sessionQueue.poll();81 assertTrue(receivedRequest.isPresent());82 assertEquals(expectedSessionRequest, receivedRequest.get());83 }84 @Test85 public void shouldAddTimestampHeader() {86 boolean added = sessionQueue.offerLast(expectedSessionRequest, requestId);87 assertTrue(added);88 Optional<HttpRequest> receivedRequest = sessionQueue.poll();89 assertTrue(receivedRequest.isPresent());90 HttpRequest request = receivedRequest.get();91 assertEquals(expectedSessionRequest, request);92 assertTrue(request.getHeader(NewSessionQueue.SESSIONREQUEST_TIMESTAMP_HEADER) != null);93 }94 @Test95 public void shouldAddRequestIdHeader() {96 boolean added = sessionQueue.offerLast(expectedSessionRequest, requestId);97 assertTrue(added);98 Optional<HttpRequest> receivedRequest = sessionQueue.poll();99 assertTrue(receivedRequest.isPresent());100 HttpRequest request = receivedRequest.get();101 assertEquals(expectedSessionRequest, request);102 String polledRequestId = request.getHeader(NewSessionQueue.SESSIONREQUEST_ID_HEADER);103 assertTrue(polledRequestId != null);104 assertEquals(requestId, new RequestId(UUID.fromString(polledRequestId)));105 }106 @Test107 public void shouldBeAbleToAddToFrontOfQueue() {108 ImmutableCapabilities chromeCaps = new ImmutableCapabilities("browserName", "chrome");109 NewSessionPayload chromePayload = NewSessionPayload.create(chromeCaps);110 HttpRequest chromeRequest = createRequest(chromePayload, POST, "/session");111 RequestId chromeRequestId = new RequestId(UUID.randomUUID());112 ImmutableCapabilities firefoxCaps = new ImmutableCapabilities("browserName", "firefox");113 NewSessionPayload firefoxpayload = NewSessionPayload.create(firefoxCaps);114 HttpRequest firefoxRequest = createRequest(firefoxpayload, POST, "/session");115 RequestId firefoxRequestId = new RequestId(UUID.randomUUID());116 boolean addedChromeRequest = sessionQueue.offerFirst(chromeRequest, chromeRequestId);117 assertTrue(addedChromeRequest);118 boolean addFirefoxRequest = sessionQueue.offerFirst(firefoxRequest, firefoxRequestId);119 assertTrue(addFirefoxRequest);120 Optional<HttpRequest> polledFirefoxRequest = sessionQueue.poll();121 assertTrue(polledFirefoxRequest.isPresent());122 assertEquals(firefoxRequest, polledFirefoxRequest.get());123 Optional<HttpRequest> polledChromeRequest = sessionQueue.poll();124 assertTrue(polledChromeRequest.isPresent());125 assertEquals(chromeRequest, polledChromeRequest.get());126 }127 @Test128 public void shouldBeClearAPopulatedQueue() {129 sessionQueue.offerLast(expectedSessionRequest, requestId);130 sessionQueue.offerLast(expectedSessionRequest, requestId);131 int count = sessionQueue.clear();132 assertEquals(count, 2);133 }134 @Test135 public void shouldBeClearAEmptyQueue() {136 int count = sessionQueue.clear();137 assertEquals(count, 0);138 }139 private HttpRequest createRequest(NewSessionPayload payload, HttpMethod httpMethod, String uri) {140 StringBuilder builder = new StringBuilder();141 try {142 payload.writeTo(builder);143 } catch (IOException e) {144 throw new UncheckedIOException(e);145 }146 HttpRequest request = new HttpRequest(httpMethod, uri);147 request.setContent(utf8String(builder.toString()));148 return request;149 }150}...

Full Screen

Full Screen

Source:ProtocolHandshake.java Github

copy

Full Screen

...37import static java.nio.charset.StandardCharsets.UTF_8;38import static org.openqa.selenium.remote.CapabilityType.PROXY;39public class ProtocolHandshake {40 private final static Logger LOG = Logger.getLogger(ProtocolHandshake.class.getName());41 public Result createSession(HttpClient client, Command command)42 throws IOException {43 Capabilities desired = (Capabilities) command.getParameters().get("desiredCapabilities");44 desired = desired == null ? new ImmutableCapabilities() : desired;45 int threshold = (int) Math.min(Runtime.getRuntime().freeMemory() / 10, Integer.MAX_VALUE);46 FileBackedOutputStream os = new FileBackedOutputStream(threshold);47 try (48 CountingOutputStream counter = new CountingOutputStream(os);49 Writer writer = new OutputStreamWriter(counter, UTF_8);50 NewSessionPayload payload = NewSessionPayload.create(desired)) {51 payload.writeTo(writer);52 try (InputStream rawIn = os.asByteSource().openBufferedStream();53 BufferedInputStream contentStream = new BufferedInputStream(rawIn)) {54 Optional<Result> result = createSession(client, contentStream, counter.getCount());55 if (result.isPresent()) {56 Result toReturn = result.get();57 LOG.info(String.format("Detected dialect: %s", toReturn.dialect));58 return toReturn;59 }60 }61 } finally {62 os.reset();63 }64 throw new SessionNotCreatedException(65 String.format(66 "Unable to create new remote session. " +67 "desired capabilities = %s",68 desired));69 }70 private Optional<Result> createSession(HttpClient client, InputStream newSessionBlob, long size)71 throws IOException {72 // Create the http request and send it73 HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");74 request.setHeader(CONTENT_LENGTH, String.valueOf(size));75 request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());76 request.setContent(newSessionBlob);77 long start = System.currentTimeMillis();78 HttpResponse response = client.execute(request);79 long time = System.currentTimeMillis() - start;80 // Ignore the content type. It may not have been set. Strictly speaking we're not following the81 // W3C spec properly. Oh well.82 Map<?, ?> blob;83 try {84 blob = new Json().toType(response.getContentString(), Map.class);85 } catch (JsonException e) {86 throw new WebDriverException(87 "Unable to parse remote response: " + response.getContentString());88 }89 InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(90 time,91 response.getStatus(),92 blob);93 return Stream.of(94 new JsonWireProtocolResponse().getResponseFunction(),95 new Gecko013ProtocolResponse().getResponseFunction(),96 new W3CHandshakeResponse().getResponseFunction())97 .map(func -> func.apply(initialResponse))98 .filter(Optional::isPresent)99 .map(Optional::get)100 .findFirst();101 }102 public static class Result {103 private static Function<Object, Proxy> massageProxy = obj -> {104 if (obj instanceof Proxy) {105 return (Proxy) obj;106 }107 if (!(obj instanceof Map)) {108 return null;109 }110 Map<?, ?> rawMap = (Map<?, ?>) obj;111 for (Object key : rawMap.keySet()) {112 if (!(key instanceof String)) {113 return null;114 }115 }116 // This cast is now safe.117 //noinspection unchecked118 return new Proxy((Map<String, ?>) obj);119 };120 private final Dialect dialect;121 private final Map<String, ?> capabilities;122 private final SessionId sessionId;123 Result(Dialect dialect, String sessionId, Map<String, ?> capabilities) {124 this.dialect = dialect;125 this.sessionId = new SessionId(Preconditions.checkNotNull(sessionId));126 this.capabilities = capabilities;127 if (capabilities.containsKey(PROXY)) {128 //noinspection unchecked129 ((Map<String, Object>)capabilities).put(PROXY, massageProxy.apply(capabilities.get(PROXY)));130 }131 }132 public Dialect getDialect() {133 return dialect;134 }135 public Response createResponse() {136 Response response = new Response(sessionId);137 response.setValue(capabilities);138 response.setStatus(ErrorCodes.SUCCESS);139 response.setState(ErrorCodes.SUCCESS_STRING);140 return response;141 }142 @Override143 public String toString() {144 return String.format("%s: %s", dialect, capabilities);145 }146 }147}...

Full Screen

Full Screen

Source:AppiumProtocolHandshake.java Github

copy

Full Screen

...78 json.endObject();79 }80 }81 @Override82 public Result createSession(HttpHandler client, Command command) throws IOException {83 //noinspection unchecked84 Capabilities desired = ((Set<Map<String, Object>>) command.getParameters().get("capabilities"))85 .stream()86 .findAny()87 .map(ImmutableCapabilities::new)88 .orElseGet(ImmutableCapabilities::new);89 try (NewSessionPayload payload = NewSessionPayload.create(desired)) {90 Either<SessionNotCreatedException, Result> result = createSession(client, payload);91 if (result.isRight()) {92 return result.right();93 }94 throw result.left();95 }96 }97 @Override98 public Either<SessionNotCreatedException, Result> createSession(99 HttpHandler client, NewSessionPayload payload) throws IOException {100 int threshold = (int) Math.min(Runtime.getRuntime().freeMemory() / 10, Integer.MAX_VALUE);101 FileBackedOutputStream os = new FileBackedOutputStream(threshold);102 try (CountingOutputStream counter = new CountingOutputStream(os);103 Writer writer = new OutputStreamWriter(counter, UTF_8)) {104 writeJsonPayload(payload, writer);105 try (InputStream rawIn = os.asByteSource().openBufferedStream();106 BufferedInputStream contentStream = new BufferedInputStream(rawIn)) {107 Method createSessionMethod = ProtocolHandshake.class.getDeclaredMethod("createSession",108 HttpHandler.class, InputStream.class, long.class);109 createSessionMethod.setAccessible(true);110 //noinspection unchecked111 return (Either<SessionNotCreatedException, Result>) createSessionMethod.invoke(112 this, client, contentStream, counter.getCount()113 );114 } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {115 throw new WebDriverException(e);116 }117 } finally {118 os.reset();119 }120 }121}...

Full Screen

Full Screen

Source:NewSessionQueuer.java Github

copy

Full Screen

...64 delete("/se/grid/newsessionqueuer/queue")65 .to(() -> new ClearSessionQueue(tracer, this)));66 }67 public void validateSessionRequest(HttpRequest request) {68 try (Span span = tracer.getCurrentContext().createSpan("newsession_queuer.validate")) {69 Map<String, EventAttributeValue> attributeMap = new HashMap<>();70 try (71 Reader reader = reader(request);72 NewSessionPayload payload = NewSessionPayload.create(reader)) {73 Objects.requireNonNull(payload, "Requests to process must be set.");74 attributeMap.put("request.payload", EventAttribute.setValue(payload.toString()));75 Iterator<Capabilities> iterator = payload.stream().iterator();76 if (!iterator.hasNext()) {77 SessionNotCreatedException78 exception =79 new SessionNotCreatedException("No capabilities found");80 EXCEPTION.accept(attributeMap, exception);81 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),82 EventAttribute.setValue(exception.getMessage()));83 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);84 throw exception;85 }86 } catch (IOException e) {...

Full Screen

Full Screen

Source:ActiveSessionFactory.java Github

copy

Full Screen

...25import java.util.ServiceLoader;26import java.util.logging.Logger;27import java.util.stream.StreamSupport;28/**29 * Used to create new {@link ActiveSession} instances as required.30 */31public class ActiveSessionFactory {32 private final static Logger LOG = Logger.getLogger(ActiveSessionFactory.class.getName());33 private final Map<String, SessionFactory> factories;34 public ActiveSessionFactory() {35 Map<String, SessionFactory> builder = new LinkedHashMap<>();36 ImmutableMap.<String, String>builder()37 .put(chrome().getBrowserName(), "org.openqa.selenium.chrome.ChromeDriverService")38 .put(edge().getBrowserName(), "org.openqa.selenium.edge.EdgeDriverService")39 .put(firefox().getBrowserName(), "org.openqa.selenium.firefox.GeckoDriverService")40 .put(internetExplorer().getBrowserName(), "org.openqa.selenium.ie.InternetExplorerDriverService")41 .put(opera().getBrowserName(), "org.openqa.selenium.opera.OperaDriverService")42 .put(operaBlink().getBrowserName(), "org.openqa.selenium.ie.OperaDriverService")43 .put(phantomjs().getBrowserName(), "org.openqa.selenium.phantomjs.PhantomJSDriverService")44 .put(safari().getBrowserName(), "org.openqa.selenium.safari.SafariDriverService")45 .build()46 .entrySet().stream()47 .filter(e -> {48 try {49 Class.forName(e.getValue());50 return true;51 } catch (ClassNotFoundException cnfe) {52 return false;53 }54 })55 .forEach(e -> builder.put(e.getKey(), new ServicedSession.Factory(e.getValue())));56 // Attempt to bind the htmlunitdriver if it's present.57 try {58 Class<? extends WebDriver> clazz = Class.forName("org.openqa.selenium.htmlunit.HtmlUnitDriver")59 .asSubclass(WebDriver.class);60 builder.put(61 htmlUnit().getBrowserName(),62 new InMemorySession.Factory(new DefaultDriverProvider(htmlUnit(), clazz)));63 } catch (ReflectiveOperationException ignored) {64 // Just carry on. Everything is fine.65 }66 // Allow user-defined factories to override default ones67 StreamSupport.stream(ServiceLoader.load(DriverProvider.class).spliterator(), false)68 .forEach(p -> builder.put(p.getProvidedCapabilities().getBrowserName(), new InMemorySession.Factory(p)));69 this.factories = ImmutableMap.copyOf(builder);70 }71 public ActiveSession createSession(NewSessionPayload newSessionPayload) throws IOException {72 return newSessionPayload.stream()73 .map(this::determineBrowser)74 .filter(Objects::nonNull)75 .map(factory -> factory.apply(newSessionPayload))76 .filter(Objects::nonNull)77 .findFirst()78 .orElseThrow(() -> new SessionNotCreatedException(79 "Unable to create a new session because of no configuration."));80 }81 private SessionFactory determineBrowser(Capabilities caps) {82 return caps.asMap().entrySet().stream()83 .map(entry -> guessBrowserName(entry.getKey(), entry.getValue()))84 .filter(factories.keySet()::contains)85 .map(factories::get)86 .findFirst()87 .orElse(null);88 }89 private String guessBrowserName(String capabilityKey, Object value) {90 if (BROWSER_NAME.equals(capabilityKey)) {91 return (String) value;92 }93 if ("chromeOptions".equals(capabilityKey)) {...

Full Screen

Full Screen

Source:BeginSession.java Github

copy

Full Screen

...51 ActiveSession session;52 try (Reader reader = new InputStreamReader(53 req.consumeContentStream(),54 req.getContentEncoding());55 NewSessionPayload payload = NewSessionPayload.create(reader)) {56 session = pipeline.createNewSession(payload);57 allSessions.put(session);58 }59 // Force capture of server-side logs since we don't have easy access to the request from the60 // local end.61 LoggingPreferences loggingPrefs = new LoggingPreferences();62 loggingPrefs.enable(LogType.SERVER, Level.INFO);63 Object raw = session.getCapabilities().get(CapabilityType.LOGGING_PREFS);64 if (raw instanceof LoggingPreferences) {65 loggingPrefs.addPreferences((LoggingPreferences) raw);66 }67 LoggingManager.perSessionLogHandler().configureLogging(loggingPrefs);68 LoggingManager.perSessionLogHandler().attachToCurrentThread(session.getId());69 // Only servers implementing the server-side webdriver-backed selenium need to return this70 // particular value....

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1NewSessionPayload payload = new NewSessionPayload();2payload.addDesiredCapability(CapabilityType.BROWSER_NAME, "chrome");3payload.addDesiredCapability(CapabilityType.PLATFORM_NAME, "windows");4payload.addDesiredCapability(CapabilityType.VERSION, "10");5NewSessionPayload payload = new NewSessionPayload();6payload.addDesiredCapability(CapabilityType.BROWSER_NAME, "chrome");7payload.addDesiredCapability(CapabilityType.PLATFORM_NAME, "windows");8payload.addDesiredCapability(CapabilityType.VERSION, "10");9NewSessionPayload payload = new NewSessionPayload();10payload.addDesiredCapability(CapabilityType.BROWSER_NAME, "chrome");11payload.addDesiredCapability(CapabilityType.PLATFORM_NAME, "windows");12payload.addDesiredCapability(CapabilityType.VERSION, "10");13NewSessionPayload payload = new NewSessionPayload();14payload.addDesiredCapability(CapabilityType.BROWSER_NAME, "chrome");15payload.addDesiredCapability(CapabilityType.PLATFORM_NAME, "windows");16payload.addDesiredCapability(CapabilityType.VERSION, "10");17NewSessionPayload payload = new NewSessionPayload();18payload.addDesiredCapability(CapabilityType.BROWSER_NAME, "chrome");19payload.addDesiredCapability(CapabilityType.PLATFORM_NAME, "windows");20payload.addDesiredCapability(CapabilityType.VERSION, "10");21NewSessionPayload payload = new NewSessionPayload();22payload.addDesiredCapability(CapabilityType.BROWSER_NAME, "chrome");23payload.addDesiredCapability(CapabilityType.PLATFORM_NAME, "windows");24payload.addDesiredCapability(CapabilityType.VERSION, "10");25NewSessionPayload payload = new NewSessionPayload();26payload.addDesiredCapability(CapabilityType.BROWSER_NAME, "chrome");27payload.addDesiredCapability(CapabilityType.PLATFORM_NAME, "windows");28payload.addDesiredCapability(CapabilityType.VERSION, "10");

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1package org.openqa.selenium.remote;2import org.openqa.selenium.Capabilities;3import org.openqa.selenium.ImmutableCapabilities;4import org.openqa.selenium.json.Json;5import org.openqa.selenium.json.JsonInput;6import org.openqa.selenium.json.JsonOutput;7import java.io.IOException;8import java.io.UncheckedIOException;9import java.util.ArrayList;10import java.util.List;11import java.util.Map;12import java.util.Objects;13public class NewSessionPayload {14 private static final Json JSON = new Json();15 private final Capabilities capabilities;16 private final Map<String, Object> extensions;17 public NewSessionPayload(Capabilities capabilities) {18 this(capabilities, ImmutableCapabilities.EMPTY);19 }20 public NewSessionPayload(Capabilities capabilities, Map<String, Object> extensions) {21 this.capabilities = Objects.requireNonNull(capabilities);22 this.extensions = Objects.requireNonNull(extensions);23 }24 public Capabilities getCapabilities() {25 return capabilities;26 }27 public Map<String, Object> getExtensions() {28 return extensions;29 }30 public static NewSessionPayload create(Capabilities capabilities) {31 return new NewSessionPayload(capabilities);32 }33 public static NewSessionPayload create(Capabilities capabilities, Map<String, Object> extensions) {34 return new NewSessionPayload(capabilities, extensions);35 }36 public static NewSessionPayload deserialize(String json) {37 JsonInput input = JSON.newInput(json);38 input.beginObject();39 Capabilities capabilities = null;40 Map<String, Object> extensions = null;41 while (input.hasNext()) {42 switch (input.nextName()) {43 input.beginObject();44 while (input.hasNext()) {45 switch (input.nextName()) {46 capabilities = input.read(Capabilities.class);47 break;48 List<Capabilities> firstMatch = new ArrayList<>();49 input.beginArray();50 while (input.hasNext()) {51 firstMatch.add(input.read(Capabilities.class));52 }53 input.endArray();54 break;55 input.skipValue();56 break;57 }58 }59 input.endObject();60 break;61 capabilities = input.read(Capabilities.class);62 break;63 capabilities = input.read(Capabilities.class);64 break;65 capabilities = input.read(Capabilities.class);66 break;

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1package com.test;2import java.io.IOException;3import java.util.HashMap;4import java.util.Map;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.remote.Command;7import org.openqa.selenium.remote.CommandExecutor;8import org.openqa.selenium.remote.HttpCommandExecutor;9import org.openqa.selenium.remote.Response;10import org.openqa.selenium.remote.http.HttpClient;11import org.openqa.selenium.remote.http.HttpMethod;12import org.openqa.selenium.remote.http.HttpRequest;13import org.openqa.selenium.remote.http.HttpResponse;14import org.openqa.selenium.remote.internal.ApacheHttpClient;15import org.openqa.selenium.remote.internal.HttpClientFactory;16import org.openqa.selenium.remote.internal.JsonToBeanConverter;17import org.openqa.selenium.remote.internal.OkHttpClient;18import org.openqa.selenium.remote.internal.ResponseCodec;19import org.openqa.selenium.remote.internal.WebElementToJsonConverter;20import com.google.common.collect.ImmutableMap;21public class Test {22 public static void main(String[] args) throws IOException {23 HttpClientFactory httpClientFactory = new HttpClientFactory();24 HttpClient httpClient = httpClientFactory.createClient(new HashMap<>());25 CommandExecutor commandExecutor = new HttpCommandExecutor(ImmutableMap.of(), httpClient);26 Command command = new Command(null, "POST", "/session", ImmutableMap.of("capabilities", ImmutableMap.of("alwaysMatch", ImmutableMap.of("browserName", "chrome"))));27 Response response = commandExecutor.execute(command);28 System.out.println(response.getValue());29 }30}31{acceptInsecureCerts=false, browserVersion=88.0.4324.182, platformName=linux, webStorageEnabled=false, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, platformVersion=5.4.0-65-generic, setWindowRect=true, takesElementScreenshot=true, pageLoadStrategy=normal, unhandledPromptBehavior=dismiss and notify, strictFileInteractability=false, timeouts={implicit=0, page load=300000, script=30000}, platform=linux, acceptSslCerts=false, proxy={}, pageLoadTimeout=300000, networkConnectionEnabled=false, chrome={chromedriverVersion=88.0.4324.96 (2e7e6d8b6c1f6e1b6e0f6c8f6f7e6c9b6e7d6c8e-refs/branch-heads/4324@{#1311}), userDataDir=/tmp/.com.google.Chrome.0e7i7E}, elementScrollBehavior=0, unhandledPromptBehavior

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.NewSessionPayload;2import org.openqa.selenium.remote.SessionId;3NewSessionPayload payload = NewSessionPayload.create(4 ImmutableMap.of("browserName", "firefox", "platform", "ANY"));5SessionId sessionId = new SessionId("1234-1234-1234-1234");6import org.openqa.selenium.remote.Response;7import org.openqa.selenium.remote.SessionId;8Response response = Response.createSuccess();9response.setSessionId(new SessionId("1234-1234-1234-1234"));10response.setValue(ImmutableMap.of("browserName", "firefox", "platform", "ANY"));11import org.openqa.selenium.remote.Command;12import org.openqa.selenium.remote.SessionId;13Command command = Command.createSession(14 ImmutableMap.of("browserName", "firefox", "platform", "ANY"));15command.setSessionId(new SessionId("1234-1234-1234-1234"));16import org.openqa.selenium.remote.ErrorCodes;17ErrorCodes errorCodes = ErrorCodes.builder().build();18errorCodes.toStatus(7);19import org.openqa.selenium.remote.ErrorCodes;20ErrorCodes errorCodes = ErrorCodes.builder().build();21errorCodes.toStatus(7);22import org.openqa.selenium.remote.ErrorCodes;23ErrorCodes errorCodes = ErrorCodes.builder().build();24errorCodes.toStatus(7);25import org.openqa.selenium.remote.ErrorCodes;26ErrorCodes errorCodes = ErrorCodes.builder().build();27errorCodes.toStatus(7);28import org.openqa.selenium.remote.ErrorCodes;29ErrorCodes errorCodes = ErrorCodes.builder().build();30errorCodes.toStatus(7);

Full Screen

Full Screen

create

Using AI Code Generation

copy

Full Screen

1NewSessionPayload newSessionPayload = NewSessionPayload.create(caps);2newSessionPayload.setAcceptInsecureCerts(true);3newSessionPayload.setAcceptInsecureCerts(false);4Map<String, Object> newSessionPayloadMap = newSessionPayload.asMap();5NewSessionPayload newSessionPayload = NewSessionPayload.create(caps);6newSessionPayload.setAcceptInsecureCerts(true);7newSessionPayload.setAcceptInsecureCerts(false);8Map<String, Object> newSessionPayloadMap = newSessionPayload.asMap();9NewSessionPayload newSessionPayload = NewSessionPayload.create(caps);10newSessionPayload.setAcceptInsecureCerts(true);11newSessionPayload.setAcceptInsecureCerts(false);12Map<String, Object> newSessionPayloadMap = newSessionPayload.asMap();

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

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

Most used method in NewSessionPayload

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful