Best Selenium code snippet using org.openqa.selenium.grid.data.SessionClosedEvent
Source:OneShotNode.java
...33import org.openqa.selenium.grid.data.NodeDrainStarted;34import org.openqa.selenium.grid.data.NodeId;35import org.openqa.selenium.grid.data.NodeStatus;36import org.openqa.selenium.grid.data.Session;37import org.openqa.selenium.grid.data.SessionClosedEvent;38import org.openqa.selenium.grid.data.Slot;39import org.openqa.selenium.grid.data.SlotId;40import org.openqa.selenium.grid.log.LoggingOptions;41import org.openqa.selenium.grid.node.HealthCheck;42import org.openqa.selenium.grid.node.Node;43import org.openqa.selenium.grid.node.config.NodeOptions;44import org.openqa.selenium.grid.security.Secret;45import org.openqa.selenium.grid.security.SecretOptions;46import org.openqa.selenium.grid.server.BaseServerOptions;47import org.openqa.selenium.grid.server.EventBusOptions;48import org.openqa.selenium.internal.Either;49import org.openqa.selenium.internal.Require;50import org.openqa.selenium.json.Json;51import org.openqa.selenium.remote.CommandExecutor;52import org.openqa.selenium.remote.RemoteWebDriver;53import org.openqa.selenium.remote.SessionId;54import org.openqa.selenium.remote.http.HttpClient;55import org.openqa.selenium.remote.http.HttpRequest;56import org.openqa.selenium.remote.http.HttpResponse;57import org.openqa.selenium.remote.tracing.Tracer;58import java.lang.reflect.Field;59import java.net.URI;60import java.net.URISyntaxException;61import java.time.Duration;62import java.time.Instant;63import java.util.Map;64import java.util.Optional;65import java.util.ServiceLoader;66import java.util.UUID;67import java.util.logging.Logger;68import java.util.stream.StreamSupport;69import static java.nio.charset.StandardCharsets.UTF_8;70import static org.openqa.selenium.grid.data.Availability.DRAINING;71import static org.openqa.selenium.grid.data.Availability.UP;72import static org.openqa.selenium.json.Json.MAP_TYPE;73import static org.openqa.selenium.remote.http.HttpMethod.DELETE;74/**75 * An implementation of {@link Node} that marks itself as draining immediately76 * after starting, and which then shuts down after usage. This will allow an77 * appropriately configured Kubernetes cluster to start a new node once the78 * session is finished.79 */80public class OneShotNode extends Node {81 private static final Logger LOG = Logger.getLogger(OneShotNode.class.getName());82 private static final Json JSON = new Json();83 private final EventBus events;84 private final WebDriverInfo driverInfo;85 private final Capabilities stereotype;86 private final Duration heartbeatPeriod;87 private final URI gridUri;88 private final UUID slotId = UUID.randomUUID();89 private RemoteWebDriver driver;90 private SessionId sessionId;91 private HttpClient client;92 private Capabilities capabilities;93 private Instant sessionStart = Instant.EPOCH;94 private OneShotNode(95 Tracer tracer,96 EventBus events,97 Secret registrationSecret,98 Duration heartbeatPeriod,99 NodeId id,100 URI uri,101 URI gridUri,102 Capabilities stereotype,103 WebDriverInfo driverInfo) {104 super(tracer, id, uri, registrationSecret);105 this.heartbeatPeriod = heartbeatPeriod;106 this.events = Require.nonNull("Event bus", events);107 this.gridUri = Require.nonNull("Public Grid URI", gridUri);108 this.stereotype = ImmutableCapabilities.copyOf(Require.nonNull("Stereotype", stereotype));109 this.driverInfo = Require.nonNull("Driver info", driverInfo);110 }111 public static Node create(Config config) {112 LoggingOptions loggingOptions = new LoggingOptions(config);113 EventBusOptions eventOptions = new EventBusOptions(config);114 BaseServerOptions serverOptions = new BaseServerOptions(config);115 SecretOptions secretOptions = new SecretOptions(config);116 NodeOptions nodeOptions = new NodeOptions(config);117 Map<String, Object> raw = new Json().toType(118 config.get("k8s", "stereotype")119 .orElseThrow(() -> new ConfigException("Unable to find node stereotype")),120 MAP_TYPE);121 Capabilities stereotype = new ImmutableCapabilities(raw);122 Optional<String> driverName = config.get("k8s", "driver_name").map(String::toLowerCase);123 // Find the webdriver info corresponding to the driver name124 WebDriverInfo driverInfo = StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false)125 .filter(info -> info.isSupporting(stereotype))126 .filter(info -> driverName.map(name -> name.equals(info.getDisplayName().toLowerCase())).orElse(true))127 .findFirst()128 .orElseThrow(() -> new ConfigException(129 "Unable to find matching driver for %s and %s", stereotype, driverName.orElse("any driver")));130 LOG.info(String.format("Creating one-shot node for %s with stereotype %s", driverInfo, stereotype));131 LOG.info("Grid URI is: " + nodeOptions.getPublicGridUri());132 return new OneShotNode(133 loggingOptions.getTracer(),134 eventOptions.getEventBus(),135 secretOptions.getRegistrationSecret(),136 nodeOptions.getHeartbeatPeriod(),137 new NodeId(UUID.randomUUID()),138 serverOptions.getExternalUri(),139 nodeOptions.getPublicGridUri().orElseThrow(() -> new ConfigException("Unable to determine public grid address")),140 stereotype,141 driverInfo);142 }143 @Override144 public Either<WebDriverException, CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {145 if (driver != null) {146 throw new IllegalStateException("Only expected one session at a time");147 }148 Optional<WebDriver> driver = driverInfo.createDriver(sessionRequest.getDesiredCapabilities());149 if (!driver.isPresent()) {150 return Either.left(new WebDriverException("Unable to create a driver instance"));151 }152 if (!(driver.get() instanceof RemoteWebDriver)) {153 driver.get().quit();154 return Either.left(new WebDriverException("Driver is not a RemoteWebDriver instance"));155 }156 this.driver = (RemoteWebDriver) driver.get();157 this.sessionId = this.driver.getSessionId();158 this.client = extractHttpClient(this.driver);159 this.capabilities = rewriteCapabilities(this.driver);160 this.sessionStart = Instant.now();161 LOG.info("Encoded response: " + JSON.toJson(ImmutableMap.of(162 "value", ImmutableMap.of(163 "sessionId", sessionId,164 "capabilities", capabilities))));165 events.fire(new NodeDrainStarted(getId()));166 return Either.right(167 new CreateSessionResponse(168 getSession(sessionId),169 JSON.toJson(ImmutableMap.of(170 "value", ImmutableMap.of(171 "sessionId", sessionId,172 "capabilities", capabilities))).getBytes(UTF_8)));173 }174 private HttpClient extractHttpClient(RemoteWebDriver driver) {175 CommandExecutor executor = driver.getCommandExecutor();176 try {177 Field client = null;178 Class<?> current = executor.getClass();179 while (client == null && (current != null || Object.class.equals(current))) {180 client = findClientField(current);181 current = current.getSuperclass();182 }183 if (client == null) {184 throw new IllegalStateException("Unable to find client field in " + executor.getClass());185 }186 if (!HttpClient.class.isAssignableFrom(client.getType())) {187 throw new IllegalStateException("Client field is not assignable to http client");188 }189 client.setAccessible(true);190 return (HttpClient) client.get(executor);191 } catch (ReflectiveOperationException e) {192 throw new IllegalStateException(e);193 }194 }195 private Field findClientField(Class<?> clazz) {196 try {197 return clazz.getDeclaredField("client");198 } catch (NoSuchFieldException e) {199 return null;200 }201 }202 private Capabilities rewriteCapabilities(RemoteWebDriver driver) {203 // Rewrite the se:options if necessary to add cdp url204 if (driverInfo.isSupportingCdp()) {205 String cdpPath = String.format("/session/%s/se/cdp", driver.getSessionId());206 return new PersistentCapabilities(driver.getCapabilities()).setCapability("se:cdp", rewrite(cdpPath));207 }208 return ImmutableCapabilities.copyOf(driver.getCapabilities());209 }210 private URI rewrite(String path) {211 try {212 return new URI(213 gridUri.getScheme(),214 gridUri.getUserInfo(),215 gridUri.getHost(),216 gridUri.getPort(),217 path,218 null,219 null);220 } catch (URISyntaxException e) {221 throw new RuntimeException(e);222 }223 }224 @Override225 public HttpResponse executeWebDriverCommand(HttpRequest req) {226 LOG.info("Executing " + req);227 HttpResponse res = client.execute(req);228 if (DELETE.equals(req.getMethod()) && req.getUri().equals("/session/" + sessionId)) {229 // Ensure the response is sent before we viciously kill the node230 new Thread(231 () -> {232 try {233 Thread.sleep(500);234 } catch (InterruptedException e) {235 Thread.currentThread().interrupt();236 throw new RuntimeException(e);237 }238 LOG.info("Stopping session: " + sessionId);239 stop(sessionId);240 },241 "Node clean up: " + getId())242 .start();243 }244 return res;245 }246 @Override247 public Session getSession(SessionId id) throws NoSuchSessionException {248 if (!isSessionOwner(id)) {249 throw new NoSuchSessionException("Unable to find session with id: " + id);250 }251 return new Session(252 sessionId,253 getUri(),254 stereotype,255 capabilities,256 sessionStart);257 }258 @Override259 public HttpResponse uploadFile(HttpRequest req, SessionId id) {260 return null;261 }262 @Override263 public void stop(SessionId id) throws NoSuchSessionException {264 LOG.info("Stop has been called: " + id);265 Require.nonNull("Session ID", id);266 if (!isSessionOwner(id)) {267 throw new NoSuchSessionException("Unable to find session " + id);268 }269 LOG.info("Quitting session " + id);270 try {271 driver.quit();272 } catch (Exception e) {273 // It's possible that the driver has already quit.274 }275 events.fire(new SessionClosedEvent(id));276 LOG.info("Firing node drain complete message");277 events.fire(new NodeDrainComplete(getId()));278 }279 @Override280 public boolean isSessionOwner(SessionId id) {281 return driver != null && sessionId.equals(id);282 }283 @Override284 public boolean isSupporting(Capabilities capabilities) {285 return driverInfo.isSupporting(capabilities);286 }287 @Override288 public NodeStatus getStatus() {289 return new NodeStatus(...
Source:GridModel.java
...25import org.openqa.selenium.grid.data.NodeRemovedEvent;26import org.openqa.selenium.grid.data.NodeStatus;27import org.openqa.selenium.grid.data.NodeStatusEvent;28import org.openqa.selenium.grid.data.Session;29import org.openqa.selenium.grid.data.SessionClosedEvent;30import org.openqa.selenium.grid.data.Slot;31import org.openqa.selenium.grid.data.SlotId;32import org.openqa.selenium.grid.security.Secret;33import org.openqa.selenium.internal.Require;34import org.openqa.selenium.remote.SessionId;35import java.time.Instant;36import java.util.HashSet;37import java.util.Iterator;38import java.util.Map;39import java.util.Objects;40import java.util.Optional;41import java.util.Set;42import java.util.concurrent.ConcurrentHashMap;43import java.util.concurrent.locks.Lock;44import java.util.concurrent.locks.ReadWriteLock;45import java.util.concurrent.locks.ReentrantReadWriteLock;46import java.util.logging.Logger;47import static org.openqa.selenium.grid.data.Availability.DOWN;48import static org.openqa.selenium.grid.data.Availability.DRAINING;49import static org.openqa.selenium.grid.data.Availability.UP;50public class GridModel {51 private static final Logger LOG = Logger.getLogger(GridModel.class.getName());52 private static final SessionId RESERVED = new SessionId("reserved");53 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);54 private final Map<Availability, Set<NodeStatus>> nodes = new ConcurrentHashMap<>();55 private final EventBus events;56 public GridModel(EventBus events, Secret registrationSecret) {57 this.events = Require.nonNull("Event bus", events);58 events.addListener(NodeDrainStarted.listener(nodeId -> setAvailability(nodeId, DRAINING)));59 events.addListener(NodeDrainComplete.listener(this::remove));60 events.addListener(NodeRemovedEvent.listener(this::remove));61 events.addListener(NodeStatusEvent.listener(status -> refresh(registrationSecret, status)));62 events.addListener(SessionClosedEvent.listener(this::release));63 }64 public GridModel add(NodeStatus node) {65 Require.nonNull("Node", node);66 Lock writeLock = lock.writeLock();67 writeLock.lock();68 try {69 // If we've already added the node, remove it.70 for (Set<NodeStatus> nodes : nodes.values()) {71 Iterator<NodeStatus> iterator = nodes.iterator();72 while (iterator.hasNext()) {73 NodeStatus next = iterator.next();74 // If the ID is the same, we're re-adding a node. If the URI is the same a node probably restarted75 if (next.getId().equals(node.getId()) || next.getUri().equals(node.getUri())) {76 LOG.info(String.format("Re-adding node with id %s and URI %s.", node.getId(), node.getUri()));...
Source:AddingNodesTest.java
...32import org.openqa.selenium.grid.data.DistributorStatus;33import org.openqa.selenium.grid.data.NodeStatus;34import org.openqa.selenium.grid.data.NodeStatusEvent;35import org.openqa.selenium.grid.data.Session;36import org.openqa.selenium.grid.data.SessionClosedEvent;37import org.openqa.selenium.grid.distributor.local.LocalDistributor;38import org.openqa.selenium.grid.distributor.remote.RemoteDistributor;39import org.openqa.selenium.grid.node.CapabilityResponseEncoder;40import org.openqa.selenium.grid.node.Node;41import org.openqa.selenium.grid.node.local.LocalNode;42import org.openqa.selenium.events.local.GuavaEventBus;43import org.openqa.selenium.grid.testing.TestSessionFactory;44import org.openqa.selenium.grid.sessionmap.local.LocalSessionMap;45import org.openqa.selenium.grid.web.CombinedHandler;46import org.openqa.selenium.grid.web.RoutableHttpClientFactory;47import org.openqa.selenium.remote.SessionId;48import org.openqa.selenium.remote.http.HttpClient;49import org.openqa.selenium.remote.http.HttpRequest;50import org.openqa.selenium.remote.http.HttpResponse;51import org.openqa.selenium.remote.tracing.DistributedTracer;52import org.openqa.selenium.support.ui.FluentWait;53import org.openqa.selenium.support.ui.Wait;54import java.net.MalformedURLException;55import java.net.URI;56import java.net.URISyntaxException;57import java.net.URL;58import java.time.Duration;59import java.util.HashSet;60import java.util.Objects;61import java.util.Optional;62import java.util.Set;63import java.util.UUID;64import java.util.function.Function;65public class AddingNodesTest {66 private static final Capabilities CAPS = new ImmutableCapabilities("cheese", "gouda");67 private Distributor distributor;68 private DistributedTracer tracer;69 private EventBus bus;70 private HttpClient.Factory clientFactory;71 private Wait<Object> wait;72 private URL externalUrl;73 private CombinedHandler handler;74 @Before75 public void setUpDistributor() throws MalformedURLException {76 tracer = DistributedTracer.builder().build();77 bus = new GuavaEventBus();78 handler = new CombinedHandler();79 externalUrl = new URL("http://example.com");80 clientFactory = new RoutableHttpClientFactory(81 externalUrl,82 handler,83 HttpClient.Factory.createDefault());84 LocalSessionMap sessions = new LocalSessionMap(tracer, bus);85 Distributor local = new LocalDistributor(tracer, bus, clientFactory, sessions);86 handler.addHandler(local);87 distributor = new RemoteDistributor(tracer, clientFactory, externalUrl);88 wait = new FluentWait<>(new Object()).withTimeout(Duration.ofSeconds(2));89 }90 @Test91 public void shouldBeAbleToRegisterALocalNode() throws URISyntaxException {92 URI sessionUri = new URI("http://example:1234");93 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())94 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))95 .build();96 handler.addHandler(node);97 distributor.add(node);98 wait.until(obj -> distributor.getStatus().hasCapacity());99 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());100 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());101 }102 @Test103 public void shouldBeAbleToRegisterACustomNode() throws URISyntaxException {104 URI sessionUri = new URI("http://example:1234");105 Node node = new CustomNode(106 tracer,107 bus,108 UUID.randomUUID(),109 externalUrl.toURI(),110 c -> new Session(new SessionId(UUID.randomUUID()), sessionUri, c));111 handler.addHandler(node);112 distributor.add(node);113 wait.until(obj -> distributor.getStatus().hasCapacity());114 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());115 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());116 }117 @Test118 public void shouldBeAbleToRegisterNodesByListeningForEvents() throws URISyntaxException {119 URI sessionUri = new URI("http://example:1234");120 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())121 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))122 .build();123 handler.addHandler(node);124 bus.fire(new NodeStatusEvent(node.getStatus()));125 wait.until(obj -> distributor.getStatus().hasCapacity());126 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());127 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());128 }129 @Test130 public void distributorShouldUpdateStateOfExistingNodeWhenNodePublishesStateChange()131 throws URISyntaxException {132 URI sessionUri = new URI("http://example:1234");133 Node node = LocalNode.builder(tracer, bus, clientFactory, externalUrl.toURI())134 .add(CAPS, new TestSessionFactory((id, caps) -> new Session(id, sessionUri, caps)))135 .build();136 handler.addHandler(node);137 bus.fire(new NodeStatusEvent(node.getStatus()));138 // Start empty139 wait.until(obj -> distributor.getStatus().hasCapacity());140 DistributorStatus.NodeSummary summary = getOnlyElement(distributor.getStatus().getNodes());141 assertEquals(1, summary.getStereotypes().get(CAPS).intValue());142 // Craft a status that makes it look like the node is busy, and post it on the bus.143 NodeStatus status = node.getStatus();144 NodeStatus crafted = new NodeStatus(145 status.getNodeId(),146 status.getUri(),147 status.getMaxSessionCount(),148 status.getStereotypes(),149 ImmutableSet.of(new NodeStatus.Active(CAPS, new SessionId(UUID.randomUUID()), CAPS)));150 bus.fire(new NodeStatusEvent(crafted));151 // We claimed the only slot is filled. Life is good.152 wait.until(obj -> !distributor.getStatus().hasCapacity());153 }154 static class CustomNode extends Node {155 private final EventBus bus;156 private final Function<Capabilities, Session> factory;157 private Session running;158 protected CustomNode(159 DistributedTracer tracer,160 EventBus bus,161 UUID nodeId,162 URI uri,163 Function<Capabilities, Session> factory) {164 super(tracer, nodeId, uri);165 this.bus = bus;166 this.factory = Objects.requireNonNull(factory);167 }168 @Override169 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {170 Objects.requireNonNull(sessionRequest);171 if (running != null) {172 return Optional.empty();173 }174 Session session = factory.apply(sessionRequest.getCapabilities());175 running = session;176 return Optional.of(177 new CreateSessionResponse(178 session,179 CapabilityResponseEncoder.getEncoder(W3C).apply(session)));180 }181 @Override182 public void executeWebDriverCommand(HttpRequest req, HttpResponse resp) {183 throw new UnsupportedOperationException("executeWebDriverCommand");184 }185 @Override186 public Session getSession(SessionId id) throws NoSuchSessionException {187 if (running == null || !running.getId().equals(id)) {188 throw new NoSuchSessionException();189 }190 return running;191 }192 @Override193 public void stop(SessionId id) throws NoSuchSessionException {194 getSession(id);195 running = null;196 bus.fire(new SessionClosedEvent(id));197 }198 @Override199 protected boolean isSessionOwner(SessionId id) {200 return running != null && running.getId().equals(id);201 }202 @Override203 public boolean isSupporting(Capabilities capabilities) {204 return Objects.equals("cake", capabilities.getCapability("cheese"));205 }206 @Override207 public NodeStatus getStatus() {208 Set<NodeStatus.Active> actives = new HashSet<>();209 if (running != null) {210 actives.add(new NodeStatus.Active(CAPS, running.getId(), running.getCapabilities()));...
Source:SessionSlot.java
...21import org.openqa.selenium.NoSuchSessionException;22import org.openqa.selenium.events.EventBus;23import org.openqa.selenium.grid.data.CreateSessionRequest;24import org.openqa.selenium.grid.data.Session;25import org.openqa.selenium.grid.data.SessionClosedEvent;26import org.openqa.selenium.grid.node.ActiveSession;27import org.openqa.selenium.grid.node.SessionFactory;28import org.openqa.selenium.grid.web.CommandHandler;29import org.openqa.selenium.remote.SessionId;30import org.openqa.selenium.remote.http.HttpRequest;31import org.openqa.selenium.remote.http.HttpResponse;32import java.io.IOException;33import java.util.Objects;34import java.util.Optional;35import java.util.function.Function;36import java.util.function.Predicate;37import java.util.logging.Level;38import java.util.logging.Logger;39public class SessionSlot implements40 CommandHandler,41 Function<CreateSessionRequest, Optional<ActiveSession>>,42 Predicate<Capabilities> {43 public static final Logger LOG = Logger.getLogger(SessionSlot.class.getName());44 private final EventBus bus;45 private final Capabilities stereotype;46 private final SessionFactory factory;47 private ActiveSession currentSession;48 public SessionSlot(EventBus bus, Capabilities stereotype, SessionFactory factory) {49 this.bus = Objects.requireNonNull(bus);50 this.stereotype = ImmutableCapabilities.copyOf(Objects.requireNonNull(stereotype));51 this.factory = Objects.requireNonNull(factory);52 }53 public Capabilities getStereotype() {54 return stereotype;55 }56 public boolean isAvailable() {57 return currentSession == null;58 }59 public ActiveSession getSession() {60 if (isAvailable()) {61 throw new NoSuchSessionException("Session is not running");62 }63 return currentSession;64 }65 public void stop() {66 if (isAvailable()) {67 return;68 }69 SessionId id = currentSession.getId();70 currentSession.stop();71 currentSession = null;72 bus.fire(new SessionClosedEvent(id));73 }74 @Override75 public void execute(HttpRequest req, HttpResponse resp) throws IOException {76 if (currentSession == null) {77 throw new NoSuchSessionException("No session currently running: " + req.getUri());78 }79 currentSession.execute(req, resp);80 if (req.getMethod() == DELETE && req.getUri().equals("/session/" + currentSession.getId())) {81 stop();82 }83 }84 @Override85 public boolean test(Capabilities capabilities) {86 return factory.test(capabilities);...
Source:LocalSessionMap.java
...14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.sessionmap.local;18import static org.openqa.selenium.grid.data.SessionClosedEvent.SESSION_CLOSED;19import org.openqa.selenium.NoSuchSessionException;20import org.openqa.selenium.events.EventBus;21import org.openqa.selenium.grid.data.Session;22import org.openqa.selenium.grid.data.SessionClosedEvent;23import org.openqa.selenium.grid.sessionmap.SessionMap;24import org.openqa.selenium.remote.SessionId;25import org.openqa.selenium.remote.tracing.DistributedTracer;26import org.openqa.selenium.remote.tracing.Span;27import java.util.HashMap;28import java.util.Map;29import java.util.Objects;30import java.util.concurrent.locks.Lock;31import java.util.concurrent.locks.ReadWriteLock;32import java.util.concurrent.locks.ReentrantReadWriteLock;33public class LocalSessionMap extends SessionMap {34 private final DistributedTracer tracer;35 private final EventBus bus;36 private final Map<SessionId, Session> knownSessions = new HashMap<>();...
Source:SessionFactory.java
...20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.events.EventBus;23import org.openqa.selenium.grid.data.Session;24import org.openqa.selenium.grid.data.SessionClosedEvent;25import org.openqa.selenium.grid.web.CommandHandler;26import org.openqa.selenium.grid.web.ReverseProxyHandler;27import org.openqa.selenium.remote.http.HttpClient;28import java.util.Objects;29import java.util.Optional;30import java.util.function.Function;31import java.util.function.Predicate;32class SessionFactory33 implements Predicate<Capabilities>, Function<Capabilities, Optional<TrackedSession>> {34 private final EventBus bus;35 private final HttpClient.Factory httpClientFactory;36 private final Capabilities capabilities;37 private final Function<Capabilities, Session> generator;38 private volatile boolean available = true;39 SessionFactory(40 EventBus bus,41 HttpClient.Factory httpClientFactory,42 Capabilities capabilities,43 Function<Capabilities, Session> generator) {44 this.bus = Objects.requireNonNull(bus);45 this.httpClientFactory = Objects.requireNonNull(httpClientFactory);46 this.capabilities = Objects.requireNonNull(ImmutableCapabilities.copyOf(capabilities));47 this.generator = Objects.requireNonNull(generator);48 }49 public Capabilities getCapabilities() {50 return capabilities;51 }52 public boolean isAvailable() {53 return available;54 }55 @Override56 public boolean test(Capabilities capabilities) {57 if (!isAvailable()) {58 return false;59 }60 return this.capabilities.getCapabilityNames().stream()61 .allMatch(name -> Objects.equals(62 this.capabilities.getCapability(name), capabilities.getCapability(name)));63 }64 @Override65 public Optional<TrackedSession> apply(Capabilities capabilities) {66 if (!test(capabilities)) {67 return Optional.empty();68 }69 this.available = false;70 Session session;71 try {72 session = generator.apply(capabilities);73 } catch (Throwable throwable) {74 this.available = true;75 return Optional.empty();76 }77 CommandHandler handler;78 if (session instanceof CommandHandler) {79 handler = (CommandHandler) session;80 } else {81 HttpClient client = httpClientFactory.createClient(fromUri(session.getUri()));82 handler = new ReverseProxyHandler(client);83 }84 String killUrl = "/session/" + session.getId();85 CommandHandler killingHandler = (req, res) -> {86 handler.execute(req, res);87 if (req.getMethod() == DELETE && killUrl.equals(req.getUri())) {88 available = true;89 bus.fire(new SessionClosedEvent(session.getId()));90 }91 };92 return Optional.of(new TrackedSession(this, session, killingHandler));93 }94}...
Source:SessionClosedEvent.java
...17package org.openqa.selenium.grid.data;18import org.openqa.selenium.events.Event;19import org.openqa.selenium.events.Type;20import org.openqa.selenium.remote.SessionId;21public class SessionClosedEvent extends Event {22 public static final Type SESSION_CLOSED = new Type("session-closed");23 public SessionClosedEvent(SessionId id) {24 super(SESSION_CLOSED, id);25 }26}...
SessionClosedEvent
Using AI Code Generation
1import org.openqa.selenium.grid.data.SessionClosedEvent;2import org.openqa.selenium.grid.data.SessionId;3import org.openqa.selenium.grid.data.SessionInfo;4import org.openqa.selenium.grid.data.SessionRequest;5import org.openqa.selenium.grid.data.SessionRequestEvent;6import org.openqa.selenium.grid.data.SessionRequestEvent.State;7import org.openqa.selenium.grid.data.SessionRequestEvent.State.Finished;8import org.openqa.selenium.grid.data.SessionRequestEvent.State.New;9import org.openqa.selenium.grid.data.SessionRequestEvent.State.Received;10import org.openqa.selenium.grid.data.SessionRequestEvent.State.Rejected;11import org.openqa.selenium.grid.data.SessionRequestEvent.State.Sent;12import org.openqa.selenium.grid.data.SessionRequestEvent.State.Stopped;13import org.openqa.selenium.grid.data.SessionRequestEvent.State.TimedOut;14import org.openqa.selenium.grid.data.SessionRequestEvent.State.Triggered;15import org.openqa.selenium.grid.data.SessionRequestEvent.State.Waiting;16import org.openqa.selenium.grid.data.SessionRequestEvent.State.WaitingForSlot;17import org.openqa.selenium.grid.data.SessionStartedEvent;18import org.openqa.selenium.grid.data.SessionTerminatedEvent;19import org.openqa.selenium.grid.data.Source;20import org.openqa.selenium.grid.data.Status;21import org.openqa.selenium.grid.data.Stereotypes;22import org.openqa.selenium.grid.data.StickySession;23import org.openqa.selenium.grid.data.StickySessionId;24import org.openqa.selenium.grid.data.StickySessionRequest;25import org.openqa.selenium.grid.data.StickySessionRequestEvent;26import org.openqa.selenium.grid.data.StickySessionRequestEvent.State;27import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.Finished;28import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.New;29import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.Received;30import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.Rejected;31import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.Sent;32import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.Stopped;33import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.TimedOut;34import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.Triggered;35import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.Waiting;36import org.openqa.selenium.grid.data.StickySessionRequestEvent.State.WaitingForSlot;37import org.openqa.selenium.grid.data.StickySessionStartedEvent;38import org.openqa.selenium.grid.data.StickySessionTerminatedEvent;39import org.openqa.selenium.grid.data.StickySession;40import org.openqa.selenium.grid.data.StickySessionId;41import org.openqa.selenium
SessionClosedEvent
Using AI Code Generation
1package com.selenium4beginners.java.seleniumsessions;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.devtools.DevTools;7import org.openqa.selenium.devtools.v91.log.Log;8import org.openqa.selenium.devtools.v91.log.model.LogEntry;9import org.openqa.selenium.devtools.v91.network.Network;10import org.openqa.selenium.devtools.v91.network.model.ConnectionType;11import org.openqa.selenium.devtools.v91.network.model.ConnectionTypeChanged;12import org.openqa.selenium.devtools.v91.network.model.Request;13import org.openqa.selenium.devtools.v91.network.model.Response;14import org.openqa.selenium.devtools.v91.network.model.ResourceType;15import org.openqa.selenium.devtools.v91.network.model.RequestWillBeSent;16import org.openqa.selenium.devtools.v91.network.model.RequestServedFromCache;17import org.openqa.selenium.devtools.v91.network.model.ResponseReceived;18import org.openqa.selenium.devtools.v91.network.model.LoadingFinished;19import org.openqa.selenium.devtools.v91.network.model.LoadingFailed;20import org.openqa.selenium.devtools.v91.network.model.DataReceived;21import org.openqa.selenium.devtools.v91.network.model.WebSocketCreated;22import org.openqa.selenium.devtools.v91.network.model.WebSocketClosed;23import org.openqa.selenium.devtools.v91.network.model.WebSocketFrameSent;24import org.openqa.selenium.devtools.v91.network.model.WebSocketFrameReceived;25import org.openqa.selenium.devtools.v91.network.model.WebSocketFrameError;26import org.openqa.selenium.devtools.v91.network.model.EventSourceMessageReceived;27import org.openqa.selenium.devtools.v91.network.model.InterceptedRequest;28import org.openqa.selenium.devtools.v91.network.model.InterceptedResponse;29import org.openqa.selenium.devtools.v91.network.model.InterceptionId;30import org.openqa.selenium.devtools.v91.network.model.AuthChallenge;31import org.openqa.selenium.devtools.v91.network.model.InterceptionChallengeResponse;32import org.openqa.selenium.devtools.v91.network.model.InterceptionContinueRequest;33import org.openqa.selenium.devtools.v91.network.model.InterceptionContinueResponse;34import org.openqa.selenium.devtools.v91.network.model.InterceptionResponse;35import org.openqa.selenium.devtools.v91.network.model.InterceptionErrorResponse;36import org.openqa.selenium.devtools.v91.network.model.InterceptionRequestPattern;37import org.openqa.selenium.devtools.v91.network.model.InterceptionRequestPatternResourceType;38import org.openqa.selenium.devtools.v91.network.model.InterceptionRequestPatternUrlPattern;39import org
SessionClosedEvent
Using AI Code Generation
1 public class SessionClosedEvent implements Event {2 private final SessionId id;3 private final SessionId source;4 private final Instant eventTime;5 private final Map<String, Object> data;6 public SessionClosedEvent(SessionId id, SessionId source, Map<String, Object> data) {7 this(id, source, Instant.now(), data);8 }9 public SessionClosedEvent(SessionId id, SessionId source, Instant eventTime, Map<String, Object> data) {10 this.id = Objects.requireNonNull(id, "Session id must be set.");11 this.source = Objects.requireNonNull(source, "Source session id must be set.");12 this.eventTime = Objects.requireNonNull(eventTime, "Event time must be set.");13 this.data = Objects.requireNonNull(data, "Data must be set.");14 }15 public SessionId getId() {16 return id;17 }18 public SessionId getSource() {19 return source;20 }21 public Instant getEventTime() {22 return eventTime;23 }24 public Map<String, Object> getData() {25 return data;26 }27 public String toString() {28 return String.format("SessionClosedEvent %s", getId());29 }30}31public class SessionClosedEventTest {32 public void shouldCreateEventWithAllValues() {33 SessionId id = new SessionId(UUID.randomUUID());34 SessionId source = new SessionId(UUID.randomUUID());35 Instant eventTime = Instant.now();36 Map<String, Object> data = ImmutableMap.of("foo", "bar");37 SessionClosedEvent event = new SessionClosedEvent(id, source, eventTime, data);38 assertThat(event.getId()).isEqualTo(id);39 assertThat(event.getSource()).isEqualTo(source);40 assertThat(event.getEventTime()).isEqualTo(eventTime);41 assertThat(event.getData()).isEqualTo(data);42 }43 public void shouldCreateEventWithDefaultValues() {44 SessionId id = new SessionId(UUID.randomUUID());45 SessionId source = new SessionId(UUID.randomUUID());46 SessionClosedEvent event = new SessionClosedEvent(id, source, Collections.emptyMap());47 assertThat(event.getId()).isEqualTo(id);48 assertThat(event.getSource()).isEqualTo(source);49 assertThat(event.getEventTime()).isNotNull();50 assertThat(event.getData()).isEmpty();51 }52 public void shouldCreateEventWithDefaultValuesAndData() {
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!!