Best Selenium code snippet using org.openqa.selenium.grid.distributor.local.LocalDistributor.add
Source:LocalDistributor.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.distributor.local;18import static com.google.common.collect.ImmutableList.toImmutableList;19import static org.openqa.selenium.grid.distributor.local.Host.Status.DOWN;20import static org.openqa.selenium.grid.distributor.local.Host.Status.DRAINING;21import static org.openqa.selenium.grid.distributor.local.Host.Status.UP;22import com.google.common.annotations.VisibleForTesting;23import com.google.common.collect.ImmutableList;24import org.openqa.selenium.Beta;25import org.openqa.selenium.Capabilities;26import org.openqa.selenium.SessionNotCreatedException;27import org.openqa.selenium.concurrent.Regularly;28import org.openqa.selenium.grid.component.HealthCheck;29import org.openqa.selenium.grid.data.Session;30import org.openqa.selenium.grid.distributor.Distributor;31import org.openqa.selenium.grid.distributor.DistributorStatus;32import org.openqa.selenium.grid.node.Node;33import org.openqa.selenium.grid.node.NodeStatus;34import org.openqa.selenium.json.Json;35import org.openqa.selenium.json.JsonOutput;36import org.openqa.selenium.remote.NewSessionPayload;37import org.openqa.selenium.remote.http.HttpClient;38import org.openqa.selenium.remote.tracing.DistributedTracer;39import org.openqa.selenium.remote.tracing.Span;40import java.time.Duration;41import java.util.ArrayList;42import java.util.Collection;43import java.util.Comparator;44import java.util.HashSet;45import java.util.Iterator;46import java.util.Map;47import java.util.Objects;48import java.util.Optional;49import java.util.Set;50import java.util.UUID;51import java.util.concurrent.ConcurrentHashMap;52import java.util.concurrent.locks.Lock;53import java.util.concurrent.locks.ReadWriteLock;54import java.util.concurrent.locks.ReentrantReadWriteLock;55import java.util.function.Supplier;56import java.util.logging.Logger;57public class LocalDistributor extends Distributor {58 private static final Json JSON = new Json();59 private static final Logger LOG = Logger.getLogger("Selenium Distributor");60 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);61 private final Set<Host> hosts = new HashSet<>();62 private final DistributedTracer tracer;63 private final Regularly hostChecker = new Regularly("distributor host checker");64 private final Map<UUID, Collection<Runnable>> allChecks = new ConcurrentHashMap<>();65 public LocalDistributor(DistributedTracer tracer, HttpClient.Factory httpClientFactory) {66 super(tracer, httpClientFactory);67 this.tracer = Objects.requireNonNull(tracer);68 }69 @Override70 public Session newSession(NewSessionPayload payload) throws SessionNotCreatedException {71 Iterator<Capabilities> allCaps = payload.stream().iterator();72 if (!allCaps.hasNext()) {73 throw new SessionNotCreatedException("No capabilities found");74 }75 Capabilities caps = allCaps.next();76 Optional<Supplier<Session>> selected;77 Lock writeLock = this.lock.writeLock();78 writeLock.lock();79 try {80 selected = this.hosts.stream()81 .filter(host -> host.getHostStatus() == UP)82 // Find a host that supports this kind of thing83 .filter(host -> host.hasCapacity(caps))84 .min(85 // Now sort by node which has the lowest load (natural ordering)86 Comparator.comparingDouble(Host::getLoad)87 // Then last session created (oldest first), so natural ordering again88 .thenComparingLong(Host::getLastSessionCreated)89 // And use the host id as a tie-breaker.90 .thenComparing(Host::getId))91 // And reserve some space92 .map(host -> host.reserve(caps));93 } finally {94 writeLock.unlock();95 }96 return selected97 .orElseThrow(98 () -> new SessionNotCreatedException("Unable to find provider for session: " + allCaps))99 .get();100 }101 @Override102 public LocalDistributor add(Node node) {103 StringBuilder sb = new StringBuilder();104 Lock writeLock = this.lock.writeLock();105 writeLock.lock();106 try (Span span = tracer.createSpan("distributor.add", tracer.getActiveSpan());107 JsonOutput out = JSON.newOutput(sb)) {108 out.setPrettyPrint(false).write(node);109 span.addTag("node", sb.toString());110 // TODO: We should check to see what happens for duplicate nodes.111 Host host = new Host(node);112 hosts.add(host);113 LOG.info(String.format("Added node %s.", node.getId()));114 host.refresh();115 Runnable runnable = host::refresh;116 Collection<Runnable> nodeRunnables = allChecks.getOrDefault(node.getId(), new ArrayList<>());117 nodeRunnables.add(runnable);118 allChecks.put(node.getId(), nodeRunnables);119 hostChecker.submit(runnable, Duration.ofMinutes(5), Duration.ofSeconds(30));120 } finally {121 writeLock.unlock();122 }123 return this;124 }125 @Override126 public void remove(UUID nodeId) {127 Lock writeLock = lock.writeLock();128 writeLock.lock();129 try (Span span = tracer.createSpan("distributor.remove", tracer.getActiveSpan())) {130 span.addTag("node.id", nodeId);131 hosts.removeIf(host -> nodeId.equals(host.getId()));132 allChecks.getOrDefault(nodeId, new ArrayList<>()).forEach(hostChecker::remove);133 } finally {134 writeLock.unlock();135 }136 }137 @Override138 public DistributorStatus getStatus() {139 Lock readLock = this.lock.readLock();140 readLock.lock();141 try {142 ImmutableList<NodeStatus> nodesStatuses = this.hosts.stream()143 .map(Host::getStatus)144 .collect(toImmutableList());...
Source:EndToEndTest.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.router;18import com.google.common.collect.ImmutableMap;19import org.junit.Test;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.grid.config.MapConfig;24import org.openqa.selenium.grid.data.Session;25import org.openqa.selenium.grid.distributor.Distributor;26import org.openqa.selenium.grid.distributor.local.LocalDistributor;27import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;28import org.openqa.selenium.grid.node.local.LocalNode;29import org.openqa.selenium.grid.server.BaseServer;30import org.openqa.selenium.grid.server.BaseServerOptions;31import org.openqa.selenium.grid.server.Server;32import org.openqa.selenium.grid.sessionmap.SessionMap;33import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;34import org.openqa.selenium.grid.sessionmap.remote.RemoteSessionMap;35import org.openqa.selenium.grid.web.CommandHandler;36import org.openqa.selenium.grid.web.Routes;37import org.openqa.selenium.net.PortProber;38import org.openqa.selenium.remote.RemoteWebDriver;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.remote.tracing.DistributedTracer;44import java.net.URI;45import java.net.URISyntaxException;46import java.util.UUID;47import java.util.function.Function;48public class EndToEndTest {49 private final Capabilities driverCaps = new ImmutableCapabilities("browserName", "cheese");50 private final DistributedTracer tracer = DistributedTracer.builder().build();51 @Test52 public void inMemory() throws URISyntaxException {53 SessionMap sessions = new LocalSessionMap();54 Distributor distributor = new LocalDistributor(tracer);55 URI nodeUri = new URI("http://localhost:4444");56 LocalNode node = LocalNode.builder(tracer, nodeUri, sessions)57 .add(driverCaps, createFactory(nodeUri))58 .build();59 distributor.add(node);60 Router router = new Router(sessions, distributor);61 Server<?> server = createServer();62 server.addRoute(Routes.matching(router).using(router));63 server.start();64 exerciseDriver(server);65 }66 private void exerciseDriver(Server<?> server) {67 WebDriver driver = new RemoteWebDriver(68 server.getUrl(),69 new ImmutableCapabilities("browserName", "cheese", "type", "cheddar"));70 driver.get("http://www.google.com");71 driver.quit();72 }73 @Test74 public void withServers() throws URISyntaxException {75 LocalSessionMap localSessions = new LocalSessionMap();76 Server<?> sessionServer = createServer();77 sessionServer.addRoute(Routes.matching(localSessions).using(localSessions));78 sessionServer.start();79 SessionMap sessions = new RemoteSessionMap(getClient(sessionServer));80 LocalDistributor localDistributor = new LocalDistributor(tracer);81 Server<?> distributorServer = createServer();82 distributorServer.addRoute(Routes.matching(localDistributor).using(localDistributor));83 distributorServer.start();84 Distributor distributor = new RemoteDistributor(tracer, getClient(distributorServer));85 int port = PortProber.findFreePort();86 URI nodeUri = new URI("http://localhost:" + port);87 LocalNode localNode = LocalNode.builder(tracer, nodeUri, sessions)88 .add(driverCaps, createFactory(nodeUri))89 .build();90 Server<?> nodeServer = new BaseServer<>(91 DistributedTracer.builder().build(),92 new BaseServerOptions(93 new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", port)))));94 nodeServer.addRoute(Routes.matching(localNode).using(localNode));95 nodeServer.start();96 distributor.add(localNode);97 Router router = new Router(sessions, distributor);98 Server<?> routerServer = createServer();99 routerServer.addRoute(Routes.matching(router).using(router));100 routerServer.start();101 exerciseDriver(routerServer);102 }103 private HttpClient getClient(Server<?> server) {104 return HttpClient.Factory.createDefault().createClient(server.getUrl());105 }106 private Server<?> createServer() {107 int port = PortProber.findFreePort();108 return new BaseServer<>(DistributedTracer.builder().build(), new BaseServerOptions(109 new MapConfig(ImmutableMap.of("server", ImmutableMap.of("port", port)))));110 }111 private Function<Capabilities, Session> createFactory(URI serverUri) {112 class SpoofSession extends Session implements CommandHandler {113 private SpoofSession(Capabilities capabilities) {...
Source:DistributorTest.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.distributor;18import static org.assertj.core.api.Assertions.assertThat;19import static org.assertj.core.api.Assertions.assertThatExceptionOfType;20import org.junit.Before;21import org.junit.Test;22import org.openqa.selenium.ImmutableCapabilities;23import org.openqa.selenium.MutableCapabilities;24import org.openqa.selenium.SessionNotCreatedException;25import org.openqa.selenium.grid.data.Session;26import org.openqa.selenium.grid.distributor.local.LocalDistributor;27import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;28import org.openqa.selenium.grid.node.local.LocalNode;29import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;30import org.openqa.selenium.grid.web.PassthroughHttpClient;31import org.openqa.selenium.remote.NewSessionPayload;32import org.openqa.selenium.remote.SessionId;33import org.openqa.selenium.remote.tracing.DistributedTracer;34import java.net.URI;35import java.net.URISyntaxException;36import java.util.UUID;37public class DistributorTest {38 private DistributedTracer tracer;39 private Distributor local;40 private Distributor distributor;41 private ImmutableCapabilities caps;42 @Before43 public void setUp() {44 tracer = DistributedTracer.builder().build();45 local = new LocalDistributor(tracer);46 distributor = new RemoteDistributor(tracer, new PassthroughHttpClient<>(local));47 caps = new ImmutableCapabilities("browserName", "cheese");48 }49 @Test50 public void creatingANewSessionWithoutANodeEndsInFailure() {51 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {52 assertThatExceptionOfType(SessionNotCreatedException.class)53 .isThrownBy(() -> distributor.newSession(payload));54 }55 }56 @Test57 public void shouldBeAbleToAddANodeAndCreateASession() throws URISyntaxException {58 URI nodeUri = new URI("http://example:5678");59 URI routableUri = new URI("http://localhost:1234");60 LocalSessionMap sessions = new LocalSessionMap();61 LocalNode node = LocalNode.builder(tracer, routableUri, sessions)62 .add(caps, c -> new Session(new SessionId(UUID.randomUUID()), nodeUri, c))63 .build();64 Distributor distributor = new LocalDistributor(tracer);65 distributor.add(node);66 MutableCapabilities sessionCaps = new MutableCapabilities(caps);67 sessionCaps.setCapability("sausages", "gravy");68 try (NewSessionPayload payload = NewSessionPayload.create(sessionCaps)) {69 Session session = distributor.newSession(payload);70 assertThat(session.getCapabilities()).isEqualTo(sessionCaps);71 assertThat(session.getUri()).isEqualTo(routableUri);72 }73 }74 @Test75 public void shouldBeAbleToRemoveANode() throws URISyntaxException {76 URI nodeUri = new URI("http://example:5678");77 URI routableUri = new URI("http://localhost:1234");78 LocalSessionMap sessions = new LocalSessionMap();79 LocalNode node = LocalNode.builder(tracer, routableUri, sessions)80 .add(caps, c -> new Session(new SessionId(UUID.randomUUID()), nodeUri, c))81 .build();82 Distributor local = new LocalDistributor(tracer);83 distributor = new RemoteDistributor(tracer, new PassthroughHttpClient<>(local));84 distributor.add(node);85 distributor.remove(node.getId());86 try (NewSessionPayload payload = NewSessionPayload.create(caps)) {87 assertThatExceptionOfType(SessionNotCreatedException.class)88 .isThrownBy(() -> distributor.newSession(payload));89 }90 }91 @Test92 public void registeringTheSameNodeMultipleTimesOnlyCountsTheFirstTime()93 throws URISyntaxException {94 URI nodeUri = new URI("http://example:5678");95 URI routableUri = new URI("http://localhost:1234");96 LocalSessionMap sessions = new LocalSessionMap();97 LocalNode node = LocalNode.builder(tracer, routableUri, sessions)98 .add(caps, c -> new Session(new SessionId(UUID.randomUUID()), nodeUri, c))99 .build();100 local.add(node);101 local.add(node);102 DistributorStatus status = local.getStatus();103 assertThat(status.getNodes().size()).isEqualTo(1);104 }105 @Test106 public void theMostLightlyLoadedNodeIsSelectedFirst() {107 }108}...
Source:Standalone.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.commands;18import com.google.auto.service.AutoService;19import com.beust.jcommander.JCommander;20import com.beust.jcommander.ParameterException;21import org.openqa.selenium.WebDriverException;22import org.openqa.selenium.cli.CliCommand;23import org.openqa.selenium.grid.config.AnnotatedConfig;24import org.openqa.selenium.grid.config.CompoundConfig;25import org.openqa.selenium.grid.config.ConcatenatingConfig;26import org.openqa.selenium.grid.config.Config;27import org.openqa.selenium.grid.config.EnvConfig;28import org.openqa.selenium.grid.distributor.Distributor;29import org.openqa.selenium.grid.distributor.local.LocalDistributor;30import org.openqa.selenium.grid.node.local.LocalNode;31import org.openqa.selenium.grid.node.local.NodeFlags;32import org.openqa.selenium.grid.router.Router;33import org.openqa.selenium.grid.server.BaseServer;34import org.openqa.selenium.grid.server.BaseServerFlags;35import org.openqa.selenium.grid.server.BaseServerOptions;36import org.openqa.selenium.grid.server.HelpFlags;37import org.openqa.selenium.grid.server.Server;38import org.openqa.selenium.grid.server.W3CCommandHandler;39import org.openqa.selenium.grid.sessionmap.SessionMap;40import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;41import org.openqa.selenium.grid.web.Routes;42import org.openqa.selenium.net.NetworkUtils;43import org.openqa.selenium.remote.tracing.DistributedTracer;44import java.net.URI;45import java.net.URISyntaxException;46@AutoService(CliCommand.class)47public class Standalone implements CliCommand {48 @Override49 public String getName() {50 return "standalone";51 }52 @Override53 public String getDescription() {54 return "The selenium server, running everything in-process.";55 }56 @Override57 public Executable configure(String... args) {58 HelpFlags help = new HelpFlags();59 BaseServerFlags baseFlags = new BaseServerFlags(4444);60 NodeFlags nodeFlags = new NodeFlags();61 JCommander commander = JCommander.newBuilder()62 .programName("standalone")63 .addObject(baseFlags)64 .addObject(help)65 .addObject(nodeFlags)66 .build();67 return () -> {68 try {69 commander.parse(args);70 } catch (ParameterException e) {71 System.err.println(e.getMessage());72 commander.usage();73 return;74 }75 if (help.displayHelp(commander, System.out)) {76 return;77 }78 Config config = new CompoundConfig(79 new AnnotatedConfig(help),80 new AnnotatedConfig(baseFlags),81 new EnvConfig(),82 new ConcatenatingConfig("selenium", '.', System.getProperties()));83 DistributedTracer tracer = DistributedTracer.getInstance();84 SessionMap sessions = new LocalSessionMap();85 Distributor distributor = new LocalDistributor(tracer);86 Router router = new Router(sessions, distributor);87 String hostName;88 try {89 hostName = new NetworkUtils().getNonLoopbackAddressOfThisMachine();90 } catch (WebDriverException e) {91 hostName = "localhost";92 }93 int port = config.getInt("server", "port")94 .orElseThrow(() -> new IllegalArgumentException("No port to use configured"));95 URI localhost = null;96 try {97 localhost = new URI("http", null, hostName, port, null, null, null);98 } catch (URISyntaxException e) {99 throw new RuntimeException(e);100 }101 LocalNode.Builder node = LocalNode.builder(tracer, localhost, sessions)102 .maximumConcurrentSessions(Runtime.getRuntime().availableProcessors() * 3);103 nodeFlags.configure(node);104 distributor.add(node.build());105 Server<?> server = new BaseServer<>(tracer, new BaseServerOptions(config));106 server.addRoute(Routes.matching(router).using(router).decorateWith(W3CCommandHandler.class));107 server.start();108 };109 }110}...
Source:Hub.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.commands;18import com.google.auto.service.AutoService;19import com.beust.jcommander.JCommander;20import com.beust.jcommander.ParameterException;21import org.openqa.selenium.cli.CliCommand;22import org.openqa.selenium.grid.config.AnnotatedConfig;23import org.openqa.selenium.grid.config.CompoundConfig;24import org.openqa.selenium.grid.config.ConcatenatingConfig;25import org.openqa.selenium.grid.config.Config;26import org.openqa.selenium.grid.config.EnvConfig;27import org.openqa.selenium.grid.distributor.Distributor;28import org.openqa.selenium.grid.distributor.local.LocalDistributor;29import org.openqa.selenium.grid.node.local.NodeFlags;30import org.openqa.selenium.grid.router.Router;31import org.openqa.selenium.grid.server.BaseServer;32import org.openqa.selenium.grid.server.BaseServerFlags;33import org.openqa.selenium.grid.server.BaseServerOptions;34import org.openqa.selenium.grid.server.HelpFlags;35import org.openqa.selenium.grid.server.Server;36import org.openqa.selenium.grid.server.W3CCommandHandler;37import org.openqa.selenium.grid.sessionmap.SessionMap;38import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;39import org.openqa.selenium.grid.web.Routes;40import org.openqa.selenium.remote.tracing.DistributedTracer;41@AutoService(CliCommand.class)42public class Hub implements CliCommand {43 @Override44 public String getName() {45 return "hub";46 }47 @Override48 public String getDescription() {49 return "A grid hub, composed of sessions, distributor, and router.";50 }51 @Override52 public Executable configure(String... args) {53 HelpFlags help = new HelpFlags();54 BaseServerFlags baseFlags = new BaseServerFlags(4444);55 NodeFlags nodeFlags = new NodeFlags();56 JCommander commander = JCommander.newBuilder()57 .programName("standalone")58 .addObject(baseFlags)59 .addObject(help)60 .addObject(nodeFlags)61 .build();62 return () -> {63 try {64 commander.parse(args);65 } catch (ParameterException e) {66 System.err.println(e.getMessage());67 commander.usage();68 return;69 }70 if (help.displayHelp(commander, System.out)) {71 return;72 }73 Config config = new CompoundConfig(74 new AnnotatedConfig(help),75 new AnnotatedConfig(baseFlags),76 new EnvConfig(),77 new ConcatenatingConfig("selenium", '.', System.getProperties()));78 DistributedTracer tracer = DistributedTracer.getInstance();79 SessionMap sessions = new LocalSessionMap();80 Distributor distributor = new LocalDistributor(tracer);81 Router router = new Router(sessions, distributor);82 Server<?> server = new BaseServer<>(83 tracer,84 new BaseServerOptions(config));85 server.addRoute(Routes.matching(router).using(router).decorateWith(W3CCommandHandler.class));86 server.start();87 };88 }89}...
Source:DistributorServer.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.distributor.httpd;18import com.google.auto.service.AutoService;19import com.beust.jcommander.JCommander;20import com.beust.jcommander.ParameterException;21import org.openqa.selenium.cli.CliCommand;22import org.openqa.selenium.grid.config.AnnotatedConfig;23import org.openqa.selenium.grid.config.CompoundConfig;24import org.openqa.selenium.grid.config.ConcatenatingConfig;25import org.openqa.selenium.grid.config.Config;26import org.openqa.selenium.grid.config.EnvConfig;27import org.openqa.selenium.grid.distributor.Distributor;28import org.openqa.selenium.grid.distributor.local.LocalDistributor;29import org.openqa.selenium.grid.server.BaseServer;30import org.openqa.selenium.grid.server.BaseServerFlags;31import org.openqa.selenium.grid.server.BaseServerOptions;32import org.openqa.selenium.grid.server.HelpFlags;33import org.openqa.selenium.grid.server.Server;34import org.openqa.selenium.grid.server.W3CCommandHandler;35import org.openqa.selenium.grid.web.Routes;36import org.openqa.selenium.remote.tracing.DistributedTracer;37@AutoService(CliCommand.class)38public class DistributorServer implements CliCommand {39 @Override40 public String getName() {41 return "distributor";42 }43 @Override44 public String getDescription() {45 return "Adds this server as the distributor in a selenium grid.";46 }47 @Override48 public Executable configure(String... args) {49 HelpFlags help = new HelpFlags();50 BaseServerFlags serverFlags = new BaseServerFlags(5553);51 JCommander commander = JCommander.newBuilder()52 .programName(getName())53 .addObject(help)54 .addObject(serverFlags)55 .build();56 return () -> {57 try {58 commander.parse(args);59 } catch (ParameterException e) {60 System.err.println(e.getMessage());61 commander.usage();62 return;63 }64 if (help.displayHelp(commander, System.out)) {65 return;66 }67 Config config = new CompoundConfig(68 new AnnotatedConfig(help),69 new AnnotatedConfig(serverFlags),70 new EnvConfig(),71 new ConcatenatingConfig("distributor", '.', System.getProperties()));72 DistributedTracer tracer = DistributedTracer.builder()73 .registerDetectedTracers()74 .build();75 Distributor distributor = new LocalDistributor(tracer);76 BaseServerOptions serverOptions = new BaseServerOptions(config);77 Server<?> server = new BaseServer<>(tracer, serverOptions);78 server.addRoute(79 Routes.matching(distributor)80 .using(distributor)81 .decorateWith(W3CCommandHandler.class));82 server.start();83 };84 }85}...
add
Using AI Code Generation
1import java.net.URI;2import java.util.Map;3import org.openqa.selenium.Capabilities;4import org.openqa.selenium.ImmutableCapabilities;5import org.openqa.selenium.grid.data.Session;6import org.openqa.selenium.grid.distributor.local.LocalDistributor;7import org.openqa.selenium.grid.node.local.LocalNode;8import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;9import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;10import org.openqa.selenium.grid.web.Routable;11import org.openqa.selenium.internal.Require;12import org.openqa.selenium.remote.http.HttpClient;13import org.openqa.selenium.remote.tracing.DefaultTestTracer;14import org.openqa.selenium.remote.tracing.Tracer;15import com.google.common.collect.ImmutableMap;16public class LocalDistributorExample {17 public static void main(String[] args) {18 Tracer tracer = DefaultTestTracer.createTracer();19 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();20 SessionMapOptions sessionMapOptions = new SessionMapOptions("local");21 LocalSessionMap sessions = new LocalSessionMap(tracer, sessionMapOptions);22 LocalDistributor distributor = new LocalDistributor(tracer, sessions, clientFactory);23 .maxSession(5)24 .add(new Routable() {25 public boolean matches(Capabilities capabilities) {26 return true;27 }28 public Session newSession(Map<String, Object> parameter) {29 return null;30 }31 })32 .build();33 distributor.add(node);34 Capabilities caps = new ImmutableCapabilities("browserName", "chrome");35 Session newSession = distributor.newSession(caps);36 distributor.remove(newSession.getId());37 Require.nonNull("Distributor", distributor).stop();38 Require.nonNull("Node", node).stop();39 Require.nonNull("Session Map", sessions).stop();40 }41}
add
Using AI Code Generation
1import org.openqa.selenium.grid.distributor.local.LocalDistributor;2import org.openqa.selenium.grid.node.local.LocalNode;3public class LocalDistributorExample {4 public static void main(String[] args) {5 LocalDistributor distributor = new LocalDistributor();6 LocalNode node = new LocalNode(distributor);7 distributor.add(node);8 }9}
add
Using AI Code Generation
1LocalDistributor localDistributor = new LocalDistributor();2LocalDistributor localDistributor = new LocalDistributor();3public LocalDistributor()4public void add(RemoteHost host)5public void remove(RemoteHost host)6public Set<RemoteHost> getHosts()7public Set<RemoteHost> getHosts(SessionId sessionId)8public Set<RemoteHost> getHosts(Capabilities capabilities)9public Set<RemoteHost> getHosts(Capabilities capabilities,10public Set<RemoteHost> getHosts(Capabilities capabilities,11public Set<RemoteHost> getHosts(Capabilities capabilities,12public Set<RemoteHost> getHosts(Capabilities capabilities,13public Set<RemoteHost> getHosts(Capabilities capabilities,
add
Using AI Code Generation
1public void addRemoteProxy(RemoteProxy proxy) {2 if (proxy instanceof SelfRegisteringRemoteProxy) {3 SelfRegisteringRemoteProxy selfRegisteringRemoteProxy = (SelfRegisteringRemoteProxy) proxy;4 selfRegisteringRemoteProxy.setDistributor(this);5 }6 proxies.add(proxy);7 }8public void removeRemoteProxy(RemoteProxy proxy) {9 proxies.remove(proxy);10 }11public Set<RemoteProxy> getRemoteProxies() {12 return ImmutableSet.copyOf(proxies);13 }14public Set<RemoteProxy> getRemoteProxies() {15 return ImmutableSet.copyOf(proxies);16 }17public Optional<RemoteProxy> getProxyById(String id) {18 return proxies.stream()19 .filter(proxy -> proxy.getId().equals(id))20 .findFirst();21 }22public Optional<RemoteProxy> getProxyByUri(URI uri) {23 return proxies.stream()24 .filter(proxy -> proxy.getUri().equals(uri))25 .findFirst();26 }27public Optional<RemoteProxy> getProxyByUri(URI uri) {28 return proxies.stream()29 .filter(proxy -> proxy.getUri().equals(uri))30 .findFirst();31 }32public Set<RemoteProxy> getProxies() {33 return ImmutableSet.copyOf(proxies);34 }35public Set<RemoteProxy> getProxies() {36 return ImmutableSet.copyOf(proxies);37 }38public Set<RemoteProxy> getProxies() {39 return ImmutableSet.copyOf(proxies);40 }
add
Using AI Code Generation
1import org.openqa.selenium.grid.distributor.local.LocalDistributor;2import org.openqa.selenium.grid.node.local.LocalNode;3import org.openqa.selenium.remote.http.HttpClient;4import org.openqa.selenium.remote.http.HttpClientFactory;5import org.openqa.selenium.remote.tracing.Tracer;6import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;7import java.net.MalformedURLException;8import java.net.URL;9import java.util.Set;10public class Test {11 public static void main(String[] args) throws MalformedURLException {12 Tracer tracer = OpenTelemetryTracer.create("test");13 HttpClientFactory factory = HttpClientFactory.createDefault();14 LocalDistributor distributor = new LocalDistributor(tracer, client);15 .add(caps -> true)16 .build();17 distributor.add(node);18 System.out.println(distributor.getStatus());19 Set<LocalNode> nodes = distributor.getNodes();20 for (LocalNode localNode : nodes) {21 System.out.println(localNode);22 }23 }24}
add
Using AI Code Generation
1LocalDistributor distributor = new LocalDistributor();2Session session = new Session();3distributor.add(session);4LocalDistributor distributor = new LocalDistributor();5Session session = new Session();6distributor.add(session);7distributor.remove(session);8LocalDistributor distributor = new LocalDistributor();9Session session = new Session();10distributor.add(session);11distributor.get(session.getId());12LocalDistributor distributor = new LocalDistributor();13Session session = new Session();14distributor.add(session);15distributor.getAll();16LocalDistributor distributor = new LocalDistributor();17NewSessionRequestListener listener = distributor.getNewSessionRequestListener();18LocalDistributor distributor = new LocalDistributor();19NewSessionQueue queue = distributor.getNewSessionQueue();20LocalDistributor distributor = new LocalDistributor();
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!