How to use SessionNotCreatedException class of org.openqa.selenium package

Best Selenium code snippet using org.openqa.selenium.SessionNotCreatedException

Source:LocalDistributor.java Github

copy

Full Screen

...19import org.openqa.selenium.Beta;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.ImmutableCapabilities;22import org.openqa.selenium.RetrySessionRequestException;23import org.openqa.selenium.SessionNotCreatedException;24import org.openqa.selenium.WebDriverException;25import org.openqa.selenium.concurrent.Regularly;26import org.openqa.selenium.events.EventBus;27import org.openqa.selenium.grid.config.Config;28import org.openqa.selenium.grid.data.CreateSessionRequest;29import org.openqa.selenium.grid.data.CreateSessionResponse;30import org.openqa.selenium.grid.data.DistributorStatus;31import org.openqa.selenium.grid.data.NewSessionRequestEvent;32import org.openqa.selenium.grid.data.NodeAddedEvent;33import org.openqa.selenium.grid.data.NodeDrainComplete;34import org.openqa.selenium.grid.data.NodeHeartBeatEvent;35import org.openqa.selenium.grid.data.NodeId;36import org.openqa.selenium.grid.data.NodeStatus;37import org.openqa.selenium.grid.data.NodeStatusEvent;38import org.openqa.selenium.grid.data.RequestId;39import org.openqa.selenium.grid.data.SessionRequest;40import org.openqa.selenium.grid.data.SessionRequestCapability;41import org.openqa.selenium.grid.data.Slot;42import org.openqa.selenium.grid.data.SlotId;43import org.openqa.selenium.grid.data.TraceSessionRequest;44import org.openqa.selenium.grid.distributor.Distributor;45import org.openqa.selenium.grid.distributor.config.DistributorOptions;46import org.openqa.selenium.grid.distributor.selector.SlotSelector;47import org.openqa.selenium.grid.log.LoggingOptions;48import org.openqa.selenium.grid.node.HealthCheck;49import org.openqa.selenium.grid.node.Node;50import org.openqa.selenium.grid.node.remote.RemoteNode;51import org.openqa.selenium.grid.security.Secret;52import org.openqa.selenium.grid.security.SecretOptions;53import org.openqa.selenium.grid.server.EventBusOptions;54import org.openqa.selenium.grid.server.NetworkOptions;55import org.openqa.selenium.grid.sessionmap.SessionMap;56import org.openqa.selenium.grid.sessionmap.config.SessionMapOptions;57import org.openqa.selenium.grid.sessionqueue.NewSessionQueue;58import org.openqa.selenium.grid.sessionqueue.config.NewSessionQueueOptions;59import org.openqa.selenium.internal.Either;60import org.openqa.selenium.internal.Require;61import org.openqa.selenium.remote.SessionId;62import org.openqa.selenium.remote.http.HttpClient;63import org.openqa.selenium.remote.tracing.AttributeKey;64import org.openqa.selenium.remote.tracing.EventAttribute;65import org.openqa.selenium.remote.tracing.EventAttributeValue;66import org.openqa.selenium.remote.tracing.Span;67import org.openqa.selenium.remote.tracing.Status;68import org.openqa.selenium.remote.tracing.Tracer;69import org.openqa.selenium.status.HasReadyState;70import java.io.UncheckedIOException;71import java.time.Duration;72import java.util.ArrayList;73import java.util.Collection;74import java.util.HashMap;75import java.util.List;76import java.util.Map;77import java.util.Optional;78import java.util.Set;79import java.util.concurrent.ConcurrentHashMap;80import java.util.concurrent.Executors;81import java.util.concurrent.locks.Lock;82import java.util.concurrent.locks.ReadWriteLock;83import java.util.concurrent.locks.ReentrantReadWriteLock;84import java.util.logging.Level;85import java.util.logging.Logger;86import java.util.stream.Collectors;87import static com.google.common.collect.ImmutableSet.toImmutableSet;88import static org.openqa.selenium.grid.data.Availability.DOWN;89import static org.openqa.selenium.grid.data.Availability.DRAINING;90import static org.openqa.selenium.internal.Debug.getDebugLogLevel;91import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES;92import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES_EVENT;93import static org.openqa.selenium.remote.RemoteTags.SESSION_ID;94import static org.openqa.selenium.remote.RemoteTags.SESSION_ID_EVENT;95import static org.openqa.selenium.remote.tracing.AttributeKey.SESSION_URI;96import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;97public class LocalDistributor extends Distributor {98 private static final Logger LOG = Logger.getLogger(LocalDistributor.class.getName());99 private final Tracer tracer;100 private final EventBus bus;101 private final HttpClient.Factory clientFactory;102 private final SessionMap sessions;103 private final SlotSelector slotSelector;104 private final Secret registrationSecret;105 private final Regularly hostChecker = new Regularly("distributor host checker");106 private final Map<NodeId, Runnable> allChecks = new HashMap<>();107 private final Duration healthcheckInterval;108 private final ReadWriteLock lock = new ReentrantReadWriteLock(/* fair */ true);109 private final GridModel model;110 private final Map<NodeId, Node> nodes;111 private final NewSessionQueue sessionQueue;112 private final Regularly regularly;113 private final boolean rejectUnsupportedCaps;114 public LocalDistributor(115 Tracer tracer,116 EventBus bus,117 HttpClient.Factory clientFactory,118 SessionMap sessions,119 NewSessionQueue sessionQueue,120 SlotSelector slotSelector,121 Secret registrationSecret,122 Duration healthcheckInterval,123 boolean rejectUnsupportedCaps) {124 super(tracer, clientFactory, registrationSecret);125 this.tracer = Require.nonNull("Tracer", tracer);126 this.bus = Require.nonNull("Event bus", bus);127 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);128 this.sessions = Require.nonNull("Session map", sessions);129 this.sessionQueue = Require.nonNull("New Session Request Queue", sessionQueue);130 this.slotSelector = Require.nonNull("Slot selector", slotSelector);131 this.registrationSecret = Require.nonNull("Registration secret", registrationSecret);132 this.healthcheckInterval = Require.nonNull("Health check interval", healthcheckInterval);133 this.model = new GridModel(bus);134 this.nodes = new ConcurrentHashMap<>();135 this.rejectUnsupportedCaps = rejectUnsupportedCaps;136 bus.addListener(NodeStatusEvent.listener(this::register));137 bus.addListener(NodeStatusEvent.listener(model::refresh));138 bus.addListener(NodeHeartBeatEvent.listener(nodeStatus -> {139 if (nodes.containsKey(nodeStatus.getId())) {140 model.touch(nodeStatus.getId());141 } else {142 register(nodeStatus);143 }144 }));145 regularly = new Regularly(146 Executors.newSingleThreadScheduledExecutor(147 r -> {148 Thread thread = new Thread(r);149 thread.setName("New Session Queue");150 thread.setDaemon(true);151 return thread;152 }));153 NewSessionRunnable newSessionRunnable = new NewSessionRunnable();154 bus.addListener(NodeDrainComplete.listener(this::remove));155 bus.addListener(NewSessionRequestEvent.listener(ignored -> newSessionRunnable.run()));156 regularly.submit(model::purgeDeadNodes, Duration.ofSeconds(30), Duration.ofSeconds(30));157 regularly.submit(newSessionRunnable, Duration.ofSeconds(5), Duration.ofSeconds(5));158 }159 public static Distributor create(Config config) {160 Tracer tracer = new LoggingOptions(config).getTracer();161 EventBus bus = new EventBusOptions(config).getEventBus();162 DistributorOptions distributorOptions = new DistributorOptions(config);163 HttpClient.Factory clientFactory = new NetworkOptions(config).getHttpClientFactory(tracer);164 SessionMap sessions = new SessionMapOptions(config).getSessionMap();165 SecretOptions secretOptions = new SecretOptions(config);166 NewSessionQueue sessionQueue = new NewSessionQueueOptions(config).getSessionQueue(167 "org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue");168 return new LocalDistributor(169 tracer,170 bus,171 clientFactory,172 sessions,173 sessionQueue,174 distributorOptions.getSlotSelector(),175 secretOptions.getRegistrationSecret(),176 distributorOptions.getHealthCheckInterval(),177 distributorOptions.shouldRejectUnsupportedCaps());178 }179 @Override180 public boolean isReady() {181 try {182 return ImmutableSet.of(bus, sessions).parallelStream()183 .map(HasReadyState::isReady)184 .reduce(true, Boolean::logicalAnd);185 } catch (RuntimeException e) {186 return false;187 }188 }189 private void register(NodeStatus status) {190 Require.nonNull("Node", status);191 Lock writeLock = lock.writeLock();192 writeLock.lock();193 try {194 if (nodes.containsKey(status.getId())) {195 return;196 }197 Set<Capabilities> capabilities = status.getSlots().stream()198 .map(Slot::getStereotype)199 .map(ImmutableCapabilities::copyOf)200 .collect(toImmutableSet());201 // A new node! Add this as a remote node, since we've not called add202 RemoteNode remoteNode = new RemoteNode(203 tracer,204 clientFactory,205 status.getId(),206 status.getUri(),207 registrationSecret,208 capabilities);209 add(remoteNode);210 } finally {211 writeLock.unlock();212 }213 }214 @Override215 public LocalDistributor add(Node node) {216 Require.nonNull("Node", node);217 LOG.info(String.format("Added node %s at %s.", node.getId(), node.getUri()));218 nodes.put(node.getId(), node);219 model.add(node.getStatus());220 // Extract the health check221 Runnable runnableHealthCheck = asRunnableHealthCheck(node);222 allChecks.put(node.getId(), runnableHealthCheck);223 hostChecker.submit(runnableHealthCheck, healthcheckInterval, Duration.ofSeconds(30));224 bus.fire(new NodeAddedEvent(node.getId()));225 return this;226 }227 private Runnable asRunnableHealthCheck(Node node) {228 HealthCheck healthCheck = node.getHealthCheck();229 NodeId id = node.getId();230 return () -> {231 HealthCheck.Result result;232 try {233 result = healthCheck.check();234 } catch (Exception e) {235 LOG.log(Level.WARNING, "Unable to process node " + id, e);236 result = new HealthCheck.Result(DOWN, "Unable to run healthcheck. Assuming down");237 }238 Lock writeLock = lock.writeLock();239 writeLock.lock();240 try {241 model.setAvailability(id, result.getAvailability());242 } finally {243 writeLock.unlock();244 }245 };246 }247 @Override248 public boolean drain(NodeId nodeId) {249 Node node = nodes.get(nodeId);250 if (node == null) {251 LOG.info("Asked to drain unregistered node " + nodeId);252 return false;253 }254 Lock writeLock = lock.writeLock();255 writeLock.lock();256 try {257 node.drain();258 model.setAvailability(nodeId, DRAINING);259 } finally {260 writeLock.unlock();261 }262 return node.isDraining();263 }264 public void remove(NodeId nodeId) {265 Lock writeLock = lock.writeLock();266 writeLock.lock();267 try {268 model.remove(nodeId);269 Runnable runnable = allChecks.remove(nodeId);270 if (runnable != null) {271 hostChecker.remove(runnable);272 }273 } finally {274 writeLock.unlock();275 }276 }277 @Override278 public DistributorStatus getStatus() {279 Lock readLock = this.lock.readLock();280 readLock.lock();281 try {282 return new DistributorStatus(model.getSnapshot());283 } finally {284 readLock.unlock();285 }286 }287 @Beta288 public void refresh() {289 List<Runnable> allHealthChecks = new ArrayList<>();290 Lock readLock = this.lock.readLock();291 readLock.lock();292 try {293 allHealthChecks.addAll(allChecks.values());294 } finally {295 readLock.unlock();296 }297 allHealthChecks.parallelStream().forEach(Runnable::run);298 }299 protected Set<NodeStatus> getAvailableNodes() {300 Lock readLock = this.lock.readLock();301 readLock.lock();302 try {303 return model.getSnapshot().stream()304 .filter(node -> !DOWN.equals(node.getAvailability()))305 .collect(toImmutableSet());306 } finally {307 readLock.unlock();308 }309 }310 @Override311 public Either<SessionNotCreatedException, CreateSessionResponse> newSession(SessionRequest request)312 throws SessionNotCreatedException {313 Require.nonNull("Requests to process", request);314 Span span = tracer.getCurrentContext().createSpan("distributor.new_session");315 Map<String, EventAttributeValue> attributeMap = new HashMap<>();316 try {317 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),318 EventAttribute.setValue(getClass().getName()));319 attributeMap.put("request.payload", EventAttribute.setValue(request.getDesiredCapabilities().toString()));320 String sessionReceivedMessage = "Session request received by the distributor";321 span.addEvent(sessionReceivedMessage, attributeMap);322 LOG.info(String.format("%s: \n %s", sessionReceivedMessage, request.getDesiredCapabilities()));323 // If there are no capabilities at all, something is horribly wrong324 if (request.getDesiredCapabilities().isEmpty()) {325 SessionNotCreatedException exception =326 new SessionNotCreatedException("No capabilities found in session request payload");327 EXCEPTION.accept(attributeMap, exception);328 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),329 EventAttribute.setValue("Unable to create session. No capabilities found: " +330 exception.getMessage()));331 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);332 return Either.left(exception);333 }334 boolean retry = false;335 SessionNotCreatedException lastFailure = new SessionNotCreatedException("Unable to create new session");336 for (Capabilities caps : request.getDesiredCapabilities()) {337 if (!isSupported(caps)) {338 continue;339 }340 // Try and find a slot that we can use for this session. While we341 // are finding the slot, no other session can possibly be started.342 // Therefore, spend as little time as possible holding the write343 // lock, and release it as quickly as possible. Under no344 // circumstances should we try to actually start the session itself345 // in this next block of code.346 SlotId selectedSlot = reserveSlot(request.getRequestId(), caps);347 if (selectedSlot == null) {348 LOG.info(String.format("Unable to find slot for request %s. May retry: %s ", request.getRequestId(), caps));349 retry = true;350 continue;351 }352 CreateSessionRequest singleRequest = new CreateSessionRequest(353 request.getDownstreamDialects(),354 caps,355 request.getMetadata());356 try {357 CreateSessionResponse response = startSession(selectedSlot, singleRequest);358 sessions.add(response.getSession());359 model.setSession(selectedSlot, response.getSession());360 SessionId sessionId = response.getSession().getId();361 Capabilities sessionCaps = response.getSession().getCapabilities();362 String sessionUri = response.getSession().getUri().toString();363 SESSION_ID.accept(span, sessionId);364 CAPABILITIES.accept(span, sessionCaps);365 SESSION_ID_EVENT.accept(attributeMap, sessionId);366 CAPABILITIES_EVENT.accept(attributeMap, sessionCaps);367 span.setAttribute(SESSION_URI.getKey(), sessionUri);368 attributeMap.put(SESSION_URI.getKey(), EventAttribute.setValue(sessionUri));369 String sessionCreatedMessage = "Session created by the distributor";370 span.addEvent(sessionCreatedMessage, attributeMap);371 LOG.info(String.format("%s. Id: %s, Caps: %s", sessionCreatedMessage, sessionId, sessionCaps));372 return Either.right(response);373 } catch (SessionNotCreatedException e) {374 model.setSession(selectedSlot, null);375 lastFailure = e;376 }377 }378 // If we've made it this far, we've not been able to start a session379 if (retry) {380 lastFailure = new RetrySessionRequestException(381 "Will re-attempt to find a node which can run this session",382 lastFailure);383 attributeMap.put(384 AttributeKey.EXCEPTION_MESSAGE.getKey(),385 EventAttribute.setValue("Will retry session " + request.getRequestId()));386 } else {387 EXCEPTION.accept(attributeMap, lastFailure);388 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),389 EventAttribute.setValue("Unable to create session: " + lastFailure.getMessage()));390 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);391 }392 return Either.left(lastFailure);393 } catch (SessionNotCreatedException e) {394 span.setAttribute(AttributeKey.ERROR.getKey(), true);395 span.setStatus(Status.ABORTED);396 EXCEPTION.accept(attributeMap, e);397 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),398 EventAttribute.setValue("Unable to create session: " + e.getMessage()));399 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);400 return Either.left(e);401 } catch (UncheckedIOException e) {402 span.setAttribute(AttributeKey.ERROR.getKey(), true);403 span.setStatus(Status.UNKNOWN);404 EXCEPTION.accept(attributeMap, e);405 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),406 EventAttribute.setValue("Unknown error in LocalDistributor while creating session: " + e.getMessage()));407 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);408 return Either.left(new SessionNotCreatedException(e.getMessage(), e));409 } finally {410 span.close();411 }412 }413 private CreateSessionResponse startSession(SlotId selectedSlot, CreateSessionRequest singleRequest) {414 Node node = nodes.get(selectedSlot.getOwningNodeId());415 if (node == null) {416 throw new SessionNotCreatedException("Unable to find owning node for slot");417 }418 Either<WebDriverException, CreateSessionResponse> result;419 try {420 result = node.newSession(singleRequest);421 } catch (SessionNotCreatedException e) {422 result = Either.left(e);423 } catch (RuntimeException e) {424 result = Either.left(new SessionNotCreatedException(e.getMessage(), e));425 }426 if (result.isLeft()) {427 WebDriverException exception = result.left();428 if (exception instanceof SessionNotCreatedException) {429 throw exception;430 }431 throw new SessionNotCreatedException(exception.getMessage(), exception);432 }433 return result.right();434 }435 private SlotId reserveSlot(RequestId requestId, Capabilities caps) {436 Lock writeLock = lock.writeLock();437 writeLock.lock();438 try {439 Set<SlotId> slotIds = slotSelector.selectSlot(caps, getAvailableNodes());440 if (slotIds.isEmpty()) {441 LOG.log(442 getDebugLogLevel(),443 String.format("No slots found for request %s and capabilities %s", requestId, caps));444 return null;445 }446 for (SlotId slotId : slotIds) {447 if (reserve(slotId)) {448 return slotId;449 }450 }451 return null;452 } finally {453 writeLock.unlock();454 }455 }456 private boolean isSupported(Capabilities caps) {457 return getAvailableNodes().stream().anyMatch(node -> node.hasCapability(caps));458 }459 private boolean reserve(SlotId id) {460 Require.nonNull("Slot ID", id);461 Lock writeLock = this.lock.writeLock();462 writeLock.lock();463 try {464 Node node = nodes.get(id.getOwningNodeId());465 if (node == null) {466 LOG.log(getDebugLogLevel(), String.format("Unable to find node with id %s", id));467 return false;468 }469 return model.reserve(id);470 } finally {471 writeLock.unlock();472 }473 }474 public void callExecutorShutdown() {475 LOG.info("Shutting down Distributor executor service");476 regularly.shutdown();477 }478 public class NewSessionRunnable implements Runnable {479 @Override480 public void run() {481 List<SessionRequestCapability> queueContents = sessionQueue.getQueueContents();482 if (rejectUnsupportedCaps) {483 checkMatchingSlot(queueContents);484 }485 int initialSize = queueContents.size();486 boolean retry = initialSize != 0;487 while (retry) {488 // We deliberately run this outside of a lock: if we're unsuccessful489 // starting the session, we just put the request back on the queue.490 // This does mean, however, that under high contention, we might end491 // up starving a session request.492 Set<Capabilities> stereotypes =493 getAvailableNodes().stream()494 .filter(NodeStatus::hasCapacity)495 .map(496 node ->497 node.getSlots().stream()498 .map(Slot::getStereotype)499 .collect(Collectors.toSet()))500 .flatMap(Collection::stream)501 .collect(Collectors.toSet());502 Optional<SessionRequest> maybeRequest = sessionQueue.getNextAvailable(stereotypes);503 maybeRequest.ifPresent(this::handleNewSessionRequest);504 int currentSize = sessionQueue.getQueueContents().size();505 retry = currentSize != 0 && currentSize != initialSize;506 initialSize = currentSize;507 }508 }509 private void checkMatchingSlot(List<SessionRequestCapability> sessionRequests) {510 for(SessionRequestCapability request : sessionRequests) {511 long unmatchableCount = request.getDesiredCapabilities().stream()512 .filter(caps -> !isSupported(caps))513 .count();514 if (unmatchableCount == request.getDesiredCapabilities().size()) {515 SessionNotCreatedException exception = new SessionNotCreatedException(516 "No nodes support the capabilities in the request");517 sessionQueue.complete(request.getRequestId(), Either.left(exception));518 }519 }520 }521 private void handleNewSessionRequest(SessionRequest sessionRequest) {522 RequestId reqId = sessionRequest.getRequestId();523 try (Span span = TraceSessionRequest.extract(tracer, sessionRequest).createSpan("distributor.poll_queue")) {524 Map<String, EventAttributeValue> attributeMap = new HashMap<>();525 attributeMap.put(526 AttributeKey.LOGGER_CLASS.getKey(),527 EventAttribute.setValue(getClass().getName()));528 span.setAttribute(AttributeKey.REQUEST_ID.getKey(), reqId.toString());529 attributeMap.put(530 AttributeKey.REQUEST_ID.getKey(),531 EventAttribute.setValue(reqId.toString()));532 attributeMap.put("request", EventAttribute.setValue(sessionRequest.toString()));533 Either<SessionNotCreatedException, CreateSessionResponse> response = newSession(sessionRequest);534 if (response.isLeft() && response.left() instanceof RetrySessionRequestException) {535 try(Span childSpan = span.createSpan("distributor.retry")) {536 LOG.info("Retrying");537 boolean retried = sessionQueue.retryAddToQueue(sessionRequest);538 attributeMap.put("request.retry_add", EventAttribute.setValue(retried));539 childSpan.addEvent("Retry adding to front of queue. No slot available.", attributeMap);540 if (retried) {541 return;542 }543 childSpan.addEvent("retrying_request", attributeMap);544 }545 }546 sessionQueue.complete(reqId, response);547 }...

Full Screen

Full Screen

Source:Distributor.java Github

copy

Full Screen

...17package org.openqa.selenium.grid.distributor;18import com.google.common.collect.ImmutableMap;19import com.google.common.collect.ImmutableSet;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.SessionNotCreatedException;22import org.openqa.selenium.grid.data.CreateSessionRequest;23import org.openqa.selenium.grid.data.CreateSessionResponse;24import org.openqa.selenium.grid.data.DistributorStatus;25import org.openqa.selenium.grid.data.NodeId;26import org.openqa.selenium.grid.data.NodeStatus;27import org.openqa.selenium.grid.data.Session;28import org.openqa.selenium.grid.data.SlotId;29import org.openqa.selenium.grid.distributor.selector.SlotSelector;30import org.openqa.selenium.grid.node.Node;31import org.openqa.selenium.grid.security.RequiresSecretFilter;32import org.openqa.selenium.grid.security.Secret;33import org.openqa.selenium.grid.sessionmap.SessionMap;34import org.openqa.selenium.internal.Require;35import org.openqa.selenium.json.Json;36import org.openqa.selenium.remote.NewSessionPayload;37import org.openqa.selenium.remote.SessionId;38import org.openqa.selenium.remote.http.HttpClient;39import org.openqa.selenium.remote.http.HttpRequest;40import org.openqa.selenium.remote.http.HttpResponse;41import org.openqa.selenium.remote.http.Routable;42import org.openqa.selenium.remote.http.Route;43import org.openqa.selenium.remote.tracing.AttributeKey;44import org.openqa.selenium.remote.tracing.EventAttribute;45import org.openqa.selenium.remote.tracing.EventAttributeValue;46import org.openqa.selenium.remote.tracing.Span;47import org.openqa.selenium.remote.tracing.SpanDecorator;48import org.openqa.selenium.remote.tracing.Status;49import org.openqa.selenium.remote.tracing.Tracer;50import org.openqa.selenium.status.HasReadyState;51import java.io.IOException;52import java.io.Reader;53import java.io.UncheckedIOException;54import java.util.HashMap;55import java.util.Iterator;56import java.util.Map;57import java.util.Objects;58import java.util.Optional;59import java.util.Set;60import java.util.UUID;61import java.util.concurrent.locks.Lock;62import java.util.concurrent.locks.ReadWriteLock;63import java.util.concurrent.locks.ReentrantReadWriteLock;64import java.util.function.Predicate;65import java.util.function.Supplier;66import java.util.stream.Collectors;67import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES;68import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES_EVENT;69import static org.openqa.selenium.remote.RemoteTags.SESSION_ID;70import static org.openqa.selenium.remote.RemoteTags.SESSION_ID_EVENT;71import static org.openqa.selenium.remote.http.Contents.bytes;72import static org.openqa.selenium.remote.http.Contents.reader;73import static org.openqa.selenium.remote.http.Route.delete;74import static org.openqa.selenium.remote.http.Route.get;75import static org.openqa.selenium.remote.http.Route.post;76import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;77import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;78/**79 * Responsible for being the central place where the {@link Node}s80 * on which {@link Session}s run81 * are determined.82 * <p>83 * This class responds to the following URLs:84 * <table summary="HTTP commands the Distributor understands">85 * <tr>86 * <th>Verb</th>87 * <th>URL Template</th>88 * <th>Meaning</th>89 * </tr>90 * <tr>91 * <td>POST</td>92 * <td>/session</td>93 * <td>This is exactly the same as the New Session command94 * from the WebDriver spec.</td>95 * </tr>96 * <tr>97 * <td>POST</td>98 * <td>/se/grid/distributor/node</td>99 * <td>Adds a new {@link Node} to this distributor.100 * Please read the javadocs for {@link Node} for101 * how the Node should be serialized.</td>102 * </tr>103 * <tr>104 * <td>DELETE</td>105 * <td>/se/grid/distributor/node/{nodeId}</td>106 * <td>Remove the {@link Node} identified by {@code nodeId}107 * from this distributor. It is expected108 * that any sessions running on the Node are allowed to complete:109 * this simply means that no new110 * sessions will be scheduled on this Node.</td>111 * </tr>112 * </table>113 */114public abstract class Distributor implements HasReadyState, Predicate<HttpRequest>, Routable {115 private final Route routes;116 protected final Tracer tracer;117 private final SlotSelector slotSelector;118 private final SessionMap sessions;119 private final ReadWriteLock lock = new ReentrantReadWriteLock(true);120 protected Distributor(121 Tracer tracer,122 HttpClient.Factory httpClientFactory,123 SlotSelector slotSelector,124 SessionMap sessions,125 Secret registrationSecret) {126 this.tracer = Require.nonNull("Tracer", tracer);127 Require.nonNull("HTTP client factory", httpClientFactory);128 this.slotSelector = Require.nonNull("Slot selector", slotSelector);129 this.sessions = Require.nonNull("Session map", sessions);130 Require.nonNull("Registration secret", registrationSecret);131 RequiresSecretFilter requiresSecret = new RequiresSecretFilter(registrationSecret);132 Json json = new Json();133 routes = Route.combine(134 post("/session").to(() -> req -> {135 CreateSessionResponse sessionResponse = newSession(req);136 return new HttpResponse().setContent(bytes(sessionResponse.getDownstreamEncodedResponse()));137 }),138 post("/se/grid/distributor/session")139 .to(() -> new CreateSession(this))140 .with(requiresSecret),141 post("/se/grid/distributor/node")142 .to(() -> new AddNode(tracer, this, json, httpClientFactory, registrationSecret))143 .with(requiresSecret),144 post("/se/grid/distributor/node/{nodeId}/drain")145 .to((Map<String, String> params) -> new DrainNode(this, new NodeId(UUID.fromString(params.get("nodeId")))))146 .with(requiresSecret),147 delete("/se/grid/distributor/node/{nodeId}")148 .to(params -> new RemoveNode(this, new NodeId(UUID.fromString(params.get("nodeId")))))149 .with(requiresSecret),150 get("/se/grid/distributor/status")151 .to(() -> new GetDistributorStatus(this))152 .with(new SpanDecorator(tracer, req -> "distributor.status")));153 }154 public CreateSessionResponse newSession(HttpRequest request)155 throws SessionNotCreatedException {156 Span span = newSpanAsChildOf(tracer, request, "distributor.new_session");157 Map<String, EventAttributeValue> attributeMap = new HashMap<>();158 try (159 Reader reader = reader(request);160 NewSessionPayload payload = NewSessionPayload.create(reader)) {161 Objects.requireNonNull(payload, "Requests to process must be set.");162 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),163 EventAttribute.setValue(getClass().getName()));164 Iterator<Capabilities> iterator = payload.stream().iterator();165 attributeMap.put("request.payload", EventAttribute.setValue(payload.toString()));166 span.addEvent("Session request received by the distributor", attributeMap);167 if (!iterator.hasNext()) {168 SessionNotCreatedException exception = new SessionNotCreatedException("No capabilities found");169 EXCEPTION.accept(attributeMap, exception);170 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),171 EventAttribute.setValue("Unable to create session. No capabilities found: "172 + exception.getMessage()));173 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);174 throw exception;175 }176 Optional<Supplier<CreateSessionResponse>> selected;177 CreateSessionRequest firstRequest = new CreateSessionRequest(178 payload.getDownstreamDialects(),179 iterator.next(),180 ImmutableMap.of("span", span));181 Lock writeLock = this.lock.writeLock();182 writeLock.lock();183 try {184 Set<NodeStatus> model = ImmutableSet.copyOf(getAvailableNodes());185 // Find a host that supports the capabilities present in the new session186 Set<SlotId> slotIds = slotSelector.selectSlot(firstRequest.getCapabilities(), model);187 if (!slotIds.isEmpty()) {188 selected = Optional.of(reserve(slotIds.iterator().next(), firstRequest));189 } else {190 selected = Optional.empty();191 }192 } finally {193 writeLock.unlock();194 }195 CreateSessionResponse sessionResponse = selected196 .orElseThrow(197 () -> {198 span.setAttribute("error", true);199 SessionNotCreatedException200 exception =201 new SessionNotCreatedException(202 "Unable to find provider for session: " + payload.stream()203 .map(Capabilities::toString).collect(Collectors.joining(", ")));204 EXCEPTION.accept(attributeMap, exception);205 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),206 EventAttribute.setValue(207 "Unable to find provider for session: "208 + exception.getMessage()));209 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);210 return exception;211 })212 .get();213 sessions.add(sessionResponse.getSession());214 SessionId sessionId = sessionResponse.getSession().getId();215 Capabilities caps = sessionResponse.getSession().getCapabilities();216 String sessionUri = sessionResponse.getSession().getUri().toString();217 SESSION_ID.accept(span, sessionId);218 CAPABILITIES.accept(span, caps);219 SESSION_ID_EVENT.accept(attributeMap, sessionId);220 CAPABILITIES_EVENT.accept(attributeMap, caps);221 span.setAttribute(AttributeKey.SESSION_URI.getKey(), sessionUri);222 attributeMap.put(AttributeKey.SESSION_URI.getKey(), EventAttribute.setValue(sessionUri));223 return sessionResponse;224 } catch (SessionNotCreatedException e) {225 span.setAttribute("error", true);226 span.setStatus(Status.ABORTED);227 EXCEPTION.accept(attributeMap, e);228 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),229 EventAttribute.setValue("Unable to create session: " + e.getMessage()));230 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);231 throw e;232 } catch (IOException e) {233 span.setAttribute("error", true);234 span.setStatus(Status.UNKNOWN);235 EXCEPTION.accept(attributeMap, e);236 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),237 EventAttribute.setValue("Unknown error in LocalDistributor while creating session: " + e.getMessage()));238 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);239 throw new SessionNotCreatedException(e.getMessage(), e);240 } finally {241 span.close();242 }243 }244 public abstract Distributor add(Node node);245 public abstract boolean drain(NodeId nodeId);246 public abstract void remove(NodeId nodeId);247 public abstract DistributorStatus getStatus();248 protected abstract Set<NodeStatus> getAvailableNodes();249 protected abstract Supplier<CreateSessionResponse> reserve(SlotId slot, CreateSessionRequest request);250 @Override251 public boolean test(HttpRequest httpRequest) {252 return matches(httpRequest);253 }...

Full Screen

Full Screen

Source:AppiumProtocolHandshake.java Github

copy

Full Screen

...17import com.google.common.io.CountingOutputStream;18import com.google.common.io.FileBackedOutputStream;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.ImmutableCapabilities;21import org.openqa.selenium.SessionNotCreatedException;22import org.openqa.selenium.WebDriverException;23import org.openqa.selenium.internal.Either;24import org.openqa.selenium.json.Json;25import org.openqa.selenium.json.JsonOutput;26import org.openqa.selenium.remote.Command;27import org.openqa.selenium.remote.NewSessionPayload;28import org.openqa.selenium.remote.ProtocolHandshake;29import org.openqa.selenium.remote.http.HttpHandler;30import java.io.BufferedInputStream;31import java.io.IOException;32import java.io.InputStream;33import java.io.OutputStreamWriter;34import java.io.Writer;35import java.lang.reflect.InvocationTargetException;36import java.lang.reflect.Method;37import java.util.Map;38import java.util.Set;39import java.util.stream.Stream;40import static java.nio.charset.StandardCharsets.UTF_8;41@SuppressWarnings("UnstableApiUsage")42public class AppiumProtocolHandshake extends ProtocolHandshake {43 private static void writeJsonPayload(NewSessionPayload srcPayload, Appendable destination) {44 try (JsonOutput json = new Json().newOutput(destination)) {45 json.beginObject();46 json.name("capabilities");47 json.beginObject();48 json.name("firstMatch");49 json.beginArray();50 json.beginObject();51 json.endObject();52 json.endArray();53 json.name("alwaysMatch");54 try {55 Method getW3CMethod = NewSessionPayload.class.getDeclaredMethod("getW3C");56 getW3CMethod.setAccessible(true);57 //noinspection unchecked58 ((Stream<Map<String, Object>>) getW3CMethod.invoke(srcPayload))59 .findFirst()60 .map(json::write)61 .orElseGet(() -> {62 json.beginObject();63 json.endObject();64 return null;65 });66 } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {67 throw new WebDriverException(e);68 }69 json.endObject(); // Close "capabilities" object70 try {71 Method writeMetaDataMethod = NewSessionPayload.class.getDeclaredMethod(72 "writeMetaData", JsonOutput.class);73 writeMetaDataMethod.setAccessible(true);74 writeMetaDataMethod.invoke(srcPayload, json);75 } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {76 throw new WebDriverException(e);77 }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

...20import static org.openqa.selenium.remote.http.Route.delete;21import static org.openqa.selenium.remote.http.Route.post;22import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;23import org.openqa.selenium.Capabilities;24import org.openqa.selenium.SessionNotCreatedException;25import org.openqa.selenium.grid.data.RequestId;26import org.openqa.selenium.internal.Require;27import org.openqa.selenium.remote.NewSessionPayload;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import org.openqa.selenium.remote.http.Routable;31import org.openqa.selenium.remote.http.Route;32import org.openqa.selenium.remote.tracing.AttributeKey;33import org.openqa.selenium.remote.tracing.EventAttribute;34import org.openqa.selenium.remote.tracing.EventAttributeValue;35import org.openqa.selenium.remote.tracing.Span;36import org.openqa.selenium.remote.tracing.Tracer;37import org.openqa.selenium.status.HasReadyState;38import java.io.IOException;39import java.io.Reader;40import java.util.HashMap;41import java.util.Iterator;42import java.util.Map;43import java.util.Objects;44import java.util.Optional;45import java.util.UUID;46import java.util.logging.Logger;47public abstract class NewSessionQueuer implements HasReadyState, Routable {48 private static final Logger LOG = Logger.getLogger(NewSessionQueuer.class.getName());49 private final Route routes;50 protected final Tracer tracer;51 protected NewSessionQueuer(Tracer tracer) {52 this.tracer = Require.nonNull("Tracer", tracer);53 routes = combine(54 post("/session")55 .to(() -> this::addToQueue),56 post("/se/grid/newsessionqueuer/session")57 .to(() -> new AddToSessionQueue(tracer, this)),58 post("/se/grid/newsessionqueuer/session/retry/{requestId}")59 .to(params -> new AddBackToSessionQueue(tracer, this,60 new RequestId(61 UUID.fromString(params.get("requestId"))))),62 Route.get("/se/grid/newsessionqueuer/session")63 .to(() -> new RemoveFromSessionQueue(tracer, this)),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) {87 SessionNotCreatedException exception = new SessionNotCreatedException(e.getMessage(), e);88 EXCEPTION.accept(attributeMap, exception);89 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),90 EventAttribute.setValue(91 "IOException while reading the request payload. " + exception92 .getMessage()));93 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);94 throw exception;95 }96 }97 }98 public abstract HttpResponse addToQueue(HttpRequest request);99 public abstract boolean retryAddToQueue(HttpRequest request, RequestId reqId);100 public abstract Optional<HttpRequest> remove();101 public abstract int clearQueue();...

Full Screen

Full Screen

Source:FirefoxCapabilitiesTest.java Github

copy

Full Screen

...22import org.junit.Before;23import org.junit.Test;24import org.openqa.selenium.Capabilities;25import org.openqa.selenium.HasCapabilities;26import org.openqa.selenium.SessionNotCreatedException;27import org.openqa.selenium.WebDriver;28import org.openqa.selenium.remote.CapabilityType;29import org.openqa.selenium.remote.DesiredCapabilities;30import org.openqa.selenium.testing.Ignore;31import org.openqa.selenium.testing.JUnit4TestBase;32import org.openqa.selenium.testing.NeedsLocalEnvironment;33import org.openqa.selenium.testing.TestUtilities;34import org.openqa.selenium.testing.drivers.WebDriverBuilder;35@NeedsLocalEnvironment36@Ignore(MARIONETTE)37public class FirefoxCapabilitiesTest extends JUnit4TestBase {38 @Before39 public void checkIsFirefoxDriver() {40 assumeTrue(TestUtilities.isFirefox(driver));41 }42 @Before43 public void avoidRemote() {44 // TODO: Resolve why these tests don't work on the remote server45 assumeTrue(TestUtilities.isLocal());46 }47 @Test(expected = SessionNotCreatedException.class)48 public void testDisableJavascriptCapability() {49 configureCapability(CapabilityType.SUPPORTS_JAVASCRIPT, false);50 }51 @Test(expected = SessionNotCreatedException.class)52 public void testDisableHandlesAlertsCapability() {53 configureCapability(CapabilityType.SUPPORTS_ALERTS, false);54 }55 @Test(expected = SessionNotCreatedException.class)56 public void testDisableCssSelectorCapability() {57 configureCapability(CapabilityType.SUPPORTS_FINDING_BY_CSS, false);58 }59 @Test(expected = SessionNotCreatedException.class)60 public void testDisableScreenshotCapability() {61 configureCapability(CapabilityType.TAKES_SCREENSHOT, false);62 }63 @Test(expected = SessionNotCreatedException.class)64 public void testEnableRotatableCapability() {65 configureCapability(CapabilityType.ROTATABLE, true);66 }67 private void configureCapability(String capability, boolean isEnabled) {68 DesiredCapabilities requiredCaps = new DesiredCapabilities();69 requiredCaps.setCapability(capability, isEnabled);70 WebDriverBuilder builder = new WebDriverBuilder().setRequiredCapabilities(requiredCaps);71 WebDriver localDriver = null;72 try {73 localDriver = builder.get();74 Capabilities caps = ((HasCapabilities) localDriver).getCapabilities();75 assertTrue(String.format("The %s capability should be included in capabilities " +76 "for the session", capability),77 caps.getCapability(capability) != null);78 assertTrue(String.format("Capability %s should be set to %b", capability, isEnabled),79 isEnabled == (Boolean) caps.getCapability(capability));80 } catch (SessionNotCreatedException e) {81 throw e;82 } catch (Exception e) {83 assumeTrue(84 "Browser failed to start, because the connection died. This is a known issue with firefox.",85 e instanceof ConnectionClosedException);86 }87 }88}...

Full Screen

Full Screen

Source:DriverFactory.java Github

copy

Full Screen

1package br.com.dbserver.webdrivers;2import com.aventstack.extentreports.Status;3import com.aventstack.extentreports.service.ExtentTestManager;4import io.github.bonigarcia.wdm.WebDriverManager;5import org.openqa.selenium.SessionNotCreatedException;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebDriverException;8import org.openqa.selenium.chrome.ChromeDriver;9import org.openqa.selenium.edge.EdgeDriver;10import org.openqa.selenium.firefox.FirefoxDriver;11public class DriverFactory {12 public static WebDriver createInstance(BrowserEnum browser) {13 try {14 switch (browser) {15 case CHROME:16 WebDriverManager.chromedriver().setup();17 return new ChromeDriver();18 case FIREFOX:19 WebDriverManager.firefoxdriver().setup();20 return new FirefoxDriver();21 case EDGE:22 WebDriverManager.edgedriver().setup();23 return new EdgeDriver();24 default:25 String message = "DriverFactory.getInstance() recebeu um argumento invalido.";26 ExtentTestManager.getTest().log(Status.FAIL, message);27 throw new IllegalArgumentException(message);28 }29 } catch(SessionNotCreatedException e) {30 String message = "Sessão não criada, versão do driver não suportada.";31 ExtentTestManager.getTest().log(Status.FATAL, message);32 throw new SessionNotCreatedException(message, e);33 } catch(WebDriverException e) {34 String message = "Não foi possivel encontrar o binario do driver.";35 ExtentTestManager.getTest().log(Status.FATAL, message);36 throw new WebDriverException(message, e);37 }38 }39}...

Full Screen

Full Screen

Source:WebDriverManager.java Github

copy

Full Screen

1package drivers;2import org.openqa.selenium.SessionNotCreatedException;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.chrome.ChromeOptions;6import java.util.List;7import java.util.concurrent.TimeUnit;8public class WebDriverManager {9 private static WebDriver currentDriver;10 public static WebDriver getCurrentDriver() {11 return currentDriver;12 }13 public static void initChrome() {14 System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");15 ChromeOptions options = new ChromeOptions();16 options.addArguments(List.of("start-maximized", "disable-infobars", "--no-sandbox"));17 try {18 currentDriver = new ChromeDriver(options);19 } catch (SessionNotCreatedException e) {20 System.out.println("Данный драйвер не совместим с текущим браузером. Используйте другой драйвер");21 }22 setDriverDefaultSettings();23 }24 private static void setDriverDefaultSettings() {25 currentDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);26 currentDriver.manage().deleteAllCookies();27 }28 public static void killCurrentDriver() {29 if (currentDriver != null) {30 currentDriver.quit();31 currentDriver = null;32 }33 }...

Full Screen

Full Screen

Source:DriverUtil.java Github

copy

Full Screen

1package test.utilities;2import org.openqa.selenium.By;3import org.openqa.selenium.NoSuchSessionException;4import org.openqa.selenium.SessionNotCreatedException;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.support.ui.ExpectedConditions;8import org.openqa.selenium.support.ui.WebDriverWait;9public class DriverUtil {10 public static long DEFAULT_WAIT = 20;11 protected static WebDriver driver;12 public static WebDriver getDefaultDriver() {13 if (driver != null) {14 return driver;15 }16 driver = Browser.newDriver();17 return driver;18 }19 public static WebElement waitAndGetElementByCssSelector(WebDriver driver, String selector,20 int seconds) {21 By selection = By.cssSelector(selector);22 return (new WebDriverWait(driver, seconds)).until( // ensure element is visible!23 ExpectedConditions.visibilityOfElementLocated(selection));24 }25 public static void closeDriver() {26 if (driver != null) {27 try {28 driver.close();29 driver.quit(); // fails in current geckodriver! TODO: Fixme30 } catch (NoSuchMethodError nsme) { // in case quit fails31 } catch (NoSuchSessionException nsse) { // in case close fails32 } catch (SessionNotCreatedException snce) {} // in case close fails33 driver = null;34 }35 }36}...

Full Screen

Full Screen

SessionNotCreatedException

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.SessionNotCreatedException;2import org.openqa.selenium.WebDriverException;3import org.openqa.selenium.remote.DesiredCapabilities;4import org.openqa.selenium.remote.RemoteWebDriver;5import java.net.URL;6import java.net.MalformedURLException;7import java.lang.InterruptedException;8public class RemoteWebDriverDemo {9 public static void main(String[] args) {10 RemoteWebDriver driver;11 DesiredCapabilities capability = DesiredCapabilities.chrome();

Full Screen

Full Screen

SessionNotCreatedException

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.SessionNotCreatedException;2import org.openqa.selenium.WebDriverException;3import org.openqa.selenium.remote.DesiredCapabilities;4import org.openqa.selenium.remote.RemoteWebDriver;5import java.net.URL;6import java.net.MalformedURLException;7public class SeleniumGrid {8 public static void main(String[] args) throws MalformedURLException {9 DesiredCapabilities capabilities = DesiredCapabilities.chrome();10 System.out.println(driver.getTitle());11 driver.quit();12 }13}14[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ SeleniumGrid ---15[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ SeleniumGrid ---16[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ SeleniumGrid ---17[INFO] --- maven-compiler-plugin:3.1:testCompile (

Full Screen

Full Screen

SessionNotCreatedException

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.SessionNotCreatedException;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.firefox.FirefoxDriver;5import org.openqa.selenium.ie.InternetExplorerDriver;6import org.openqa.selenium.opera.OperaDriver;7import org.openqa.selenium.remote.DesiredCapabilities;8import org.openqa.selenium.safari.SafariDriver;9public class SeleniumDriverSetup {10 public static void main(String[] args) {11 WebDriver driver;12 String browser = "chrome";13 DesiredCapabilities capabilities = new DesiredCapabilities();14 switch (browser) {15 System.setProperty("webdriver.chrome.driver", "/Users/username/Downloads/chromedriver");16 driver = new ChromeDriver();17 break;18 System.setProperty("webdriver.gecko.driver", "/Users/username/Downloads/geckodriver");19 driver = new FirefoxDriver();20 break;21 System.setProperty("webdriver.ie.driver", "/Users/username/Downloads/IEDriverServer");22 capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);23 driver = new InternetExplorerDriver(capabilities);24 break;25 System.setProperty("webdriver.opera.driver", "/Users/username/Downloads/operadriver");26 driver = new OperaDriver();27 break;28 driver = new SafariDriver();29 break;30 throw new SessionNotCreatedException("Browser not supported");31 }32 driver.quit();33 }34}

Full Screen

Full Screen

SessionNotCreatedException

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.SessionNotCreatedException;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebDriverException;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.chrome.ChromeOptions;6import org.openqa.selenium.remote.DesiredCapabilities;7import org.openqa.selenium.remote.RemoteWebDriver;8import org.openqa.selenium.remote.SessionId;9import java.net.MalformedURLException;10import java.net.URL;11import org.openqa.selenium.SessionNotCreatedException;12import org.openqa.selenium.WebDriver;13import org.openqa.selenium.WebDriverException;14import org.openqa.selenium.chrome.ChromeDriver;15import org.openqa.selenium.chrome.ChromeOptions;16import org.openqa.selenium.remote.DesiredCapabilities;17import org.openqa.selenium.remote.RemoteWebDriver;18import org.openqa.selenium.remote.SessionId;19import java.net.MalformedURLException;20import java.net.URL;21public class SessionNotCreatedExceptionExample {22public static void main(String[] args) throws MalformedURLException {23import org.openqa.selenium.SessionNotCreatedException;24import org.openqa.selenium.WebDriver;25import org.openqa.selenium.WebDriverException;26import org.openqa.selenium.chrome.ChromeDriver;27import org.openqa.selenium.chrome.ChromeOptions;28import org.openqa.selenium.remote.DesiredCapabilities;29import org.openqa.selenium.remote.RemoteWebDriver;30import org.openqa.selenium.remote.SessionId;31import java.net.MalformedURLException;32import java.net.URL;33public class SessionNotCreatedExceptionExample {34public static void main(String[] args) throws MalformedURLException {35import org.openqa.selenium.SessionNotCreatedException;36import org.openqa.selenium.WebDriver;37import org.openqa.selenium.WebDriverException;38import org.openqa.selenium.chrome.ChromeDriver;39import org.openqa.selenium.chrome.ChromeOptions;40import org.openqa.selenium.remote.DesiredCapabilities;41import org.openqa.selenium.remote.RemoteWebDriver;42import org.openqa.selenium.remote.SessionId;43import java.net.MalformedURLException;44import java.net.URL;45public class SessionNotCreatedExceptionExample {46public static void main(String[] args) throws MalformedURLException {47import org.openqa.selenium.SessionNotCreatedException;48import org.openqa.selenium.WebDriver;49import org.openqa.selenium.WebDriverException;50import org.openqa.selenium.chrome.ChromeDriver;51import org.openqa.selenium.chrome.ChromeOptions;52import org.openqa.selenium.remote.DesiredCapabilities;53import org.openqa.selenium.remote.RemoteWebDriver;54import org.openqa.selenium.remote.SessionId;55import java.net.MalformedURLException;56import java.net.URL;

Full Screen

Full Screen

SessionNotCreatedException

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.SessionNotCreatedException;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.firefox.FirefoxDriver;4public class SessionNotCreatedExceptionExample {5public static void main(String[] args) {6WebDriver driver = new FirefoxDriver();7try {8} catch (SessionNotCreatedException e) {9System.out.println("SessionNotCreatedException: " + e.getMessage());10}11driver.quit();12}13}

Full Screen

Full Screen
copy
1<jsp-config>2 <jsp-property-group>3 <url-pattern>*.jsp</url-pattern>4 <scripting-invalid>true</scripting-invalid>5 </jsp-property-group>6</jsp-config>7
Full Screen
copy
1<c:if test="${someAttribute == 'something'}">2 ...3</c:if>4
Full Screen

Selenium 4 Tutorial:

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

Chapters:

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

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

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

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

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

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

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

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

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

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful