Best Selenium code snippet using org.openqa.selenium.remote.tracing.EventAttribute
Source:GridStatusHandler.java
...24import org.openqa.selenium.remote.http.HttpHandler;25import org.openqa.selenium.remote.http.HttpRequest;26import org.openqa.selenium.remote.http.HttpResponse;27import org.openqa.selenium.remote.tracing.AttributeKey;28import org.openqa.selenium.remote.tracing.EventAttribute;29import org.openqa.selenium.remote.tracing.EventAttributeValue;30import org.openqa.selenium.remote.tracing.HttpTracing;31import org.openqa.selenium.remote.tracing.Span;32import org.openqa.selenium.remote.tracing.Status;33import org.openqa.selenium.remote.tracing.Tracer;34import java.io.IOException;35import java.util.HashMap;36import java.util.List;37import java.util.Map;38import java.util.concurrent.CompletableFuture;39import java.util.concurrent.ExecutionException;40import java.util.concurrent.ExecutorService;41import java.util.concurrent.Executors;42import java.util.concurrent.Future;43import java.util.concurrent.ScheduledExecutorService;44import java.util.concurrent.TimeoutException;45import static java.util.concurrent.TimeUnit.MILLISECONDS;46import static java.util.concurrent.TimeUnit.SECONDS;47import static java.util.stream.Collectors.toList;48import static org.openqa.selenium.json.Json.MAP_TYPE;49import static org.openqa.selenium.remote.http.Contents.asJson;50import static org.openqa.selenium.remote.http.Contents.string;51import static org.openqa.selenium.remote.http.HttpMethod.GET;52import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;53import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;54import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE;55import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE_EVENT;56class GridStatusHandler implements HttpHandler {57 private static final ScheduledExecutorService58 SCHEDULED_SERVICE =59 Executors.newScheduledThreadPool(60 1,61 r -> {62 Thread thread = new Thread(r, "Scheduled grid status executor");63 thread.setDaemon(true);64 return thread;65 });66 private static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool(67 r -> {68 Thread thread = new Thread(r, "Grid status executor");69 thread.setDaemon(true);70 return thread;71 });72 private final Json json;73 private final Tracer tracer;74 private final HttpClient.Factory clientFactory;75 private final Distributor distributor;76 GridStatusHandler(Json json, Tracer tracer, HttpClient.Factory clientFactory, Distributor distributor) {77 this.json = Require.nonNull("JSON encoder", json);78 this.tracer = Require.nonNull("Tracer", tracer);79 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);80 this.distributor = Require.nonNull("Distributor", distributor);81 }82 @Override83 public HttpResponse execute(HttpRequest req) {84 long start = System.currentTimeMillis();85 try (Span span = newSpanAsChildOf(tracer, req, "router.status")) {86 Map<String, EventAttributeValue> attributeMap = new HashMap<>();87 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),88 EventAttribute.setValue(getClass().getName()));89 DistributorStatus status;90 try {91 status = EXECUTOR_SERVICE.submit(span.wrap(distributor::getStatus)).get(2, SECONDS);92 } catch (ExecutionException | TimeoutException e) {93 span.setAttribute("error", true);94 span.setStatus(Status.CANCELLED);95 EXCEPTION.accept(attributeMap, e);96 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),97 EventAttribute.setValue("Unable to get distributor status due to execution error or timeout: " + e.getMessage()));98 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);99 return new HttpResponse().setContent(asJson(100 ImmutableMap.of("value", ImmutableMap.of(101 "ready", false,102 "message", "Unable to read distributor status."))));103 } catch (InterruptedException e) {104 span.setAttribute("error", true);105 span.setStatus(Status.ABORTED);106 EXCEPTION.accept(attributeMap, e);107 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),108 EventAttribute.setValue("Interruption while getting distributor status: " + e.getMessage()));109 Thread.currentThread().interrupt();110 return new HttpResponse().setContent(asJson(111 ImmutableMap.of("value", ImmutableMap.of(112 "ready", false,113 "message", "Reading distributor status was interrupted."))));114 }115 boolean ready = status.hasCapacity();116 long remaining = System.currentTimeMillis() + 2000 - start;117 List<Future<Map<String, Object>>> nodeResults = status.getNodes().stream()118 .map(node -> {119 ImmutableMap<String, Object> defaultResponse = ImmutableMap.of(120 "id", node.getId(),121 "uri", node.getUri(),122 "maxSessions", node.getMaxSessionCount(),123 "slots", node.getSlots(),124 "warning", "Unable to read data from node.");125 CompletableFuture<Map<String, Object>> toReturn = new CompletableFuture<>();126 Future<?> future = EXECUTOR_SERVICE.submit(127 () -> {128 try {129 HttpClient client = clientFactory.createClient(node.getUri().toURL());130 HttpRequest nodeStatusReq = new HttpRequest(GET, "/se/grid/node/status");131 HttpTracing.inject(tracer, span, nodeStatusReq);132 HttpResponse res = client.execute(nodeStatusReq);133 toReturn.complete(res.getStatus() == 200134 ? json.toType(string(res), MAP_TYPE)135 : defaultResponse);136 } catch (IOException e) {137 toReturn.complete(defaultResponse);138 }139 });140 SCHEDULED_SERVICE.schedule(141 () -> {142 if (!toReturn.isDone()) {143 toReturn.complete(defaultResponse);144 future.cancel(true);145 }146 },147 remaining,148 MILLISECONDS);149 return toReturn;150 })151 .collect(toList());152 ImmutableMap.Builder<String, Object> value = ImmutableMap.builder();153 value.put("ready", ready);154 value.put("message", ready ? "Selenium Grid ready." : "Selenium Grid not ready.");155 value.put("nodes", nodeResults.stream()156 .map(summary -> {157 try {158 return summary.get();159 } catch (ExecutionException e) {160 span.setAttribute("error", true);161 span.setStatus(Status.NOT_FOUND);162 EXCEPTION.accept(attributeMap, e);163 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),164 EventAttribute.setValue("Unable to get Node information: " + e.getMessage()));165 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);166 throw wrap(e);167 } catch (InterruptedException e) {168 span.setAttribute("error", true);169 span.setStatus(Status.NOT_FOUND);170 EXCEPTION.accept(attributeMap, e);171 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),172 EventAttribute.setValue("Unable to get Node information: " + e.getMessage()));173 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);174 Thread.currentThread().interrupt();175 throw wrap(e);176 }177 })178 .collect(toList()));179 HttpResponse res = new HttpResponse().setContent(asJson(ImmutableMap.of("value", value.build())));180 HTTP_RESPONSE.accept(span, res);181 HTTP_RESPONSE_EVENT.accept(attributeMap, res);182 attributeMap.put("grid.status", EventAttribute.setValue(ready));183 span.setStatus(Status.OK);184 span.addEvent("Computed grid status", attributeMap);185 return res;186 }187 }188 private RuntimeException wrap(Exception e) {189 if (e instanceof InterruptedException) {190 Thread.currentThread().interrupt();191 return new RuntimeException(e);192 }193 Throwable cause = e.getCause();194 if (cause == null) {195 return e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);196 }...
Source:ProtocolConverter.java
...37import org.openqa.selenium.remote.http.HttpHandler;38import org.openqa.selenium.remote.http.HttpRequest;39import org.openqa.selenium.remote.http.HttpResponse;40import org.openqa.selenium.remote.tracing.AttributeKey;41import org.openqa.selenium.remote.tracing.EventAttribute;42import org.openqa.selenium.remote.tracing.EventAttributeValue;43import org.openqa.selenium.remote.tracing.HttpTracing;44import org.openqa.selenium.remote.tracing.Span;45import org.openqa.selenium.remote.tracing.Status;46import org.openqa.selenium.remote.tracing.Tracer;47import java.io.UncheckedIOException;48import java.util.HashMap;49import java.util.Map;50import java.util.Objects;51import java.util.function.Function;52import static java.net.HttpURLConnection.HTTP_OK;53import static java.nio.charset.StandardCharsets.UTF_8;54import static org.openqa.selenium.json.Json.MAP_TYPE;55import static org.openqa.selenium.remote.Dialect.W3C;56import static org.openqa.selenium.remote.RemoteTags.SESSION_ID;57import static org.openqa.selenium.remote.RemoteTags.SESSION_ID_EVENT;58import static org.openqa.selenium.remote.http.Contents.bytes;59import static org.openqa.selenium.remote.http.Contents.string;60import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;61import static org.openqa.selenium.remote.tracing.Tags.HTTP_REQUEST;62import static org.openqa.selenium.remote.tracing.Tags.HTTP_REQUEST_EVENT;63import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE;64import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE_EVENT;65import static org.openqa.selenium.remote.tracing.Tags.KIND;66public class ProtocolConverter implements HttpHandler {67 private static final Json JSON = new Json();68 private static final ImmutableSet<String> IGNORED_REQ_HEADERS = ImmutableSet.<String>builder()69 .add("connection")70 .add("content-length")71 .add("content-type")72 .add("keep-alive")73 .add("proxy-authorization")74 .add("proxy-authenticate")75 .add("proxy-connection")76 .add("te")77 .add("trailer")78 .add("transfer-encoding")79 .add("upgrade")80 .build();81 private final Tracer tracer;82 private final HttpClient client;83 private final CommandCodec<HttpRequest> downstream;84 private final CommandCodec<HttpRequest> upstream;85 private final ResponseCodec<HttpResponse> downstreamResponse;86 private final ResponseCodec<HttpResponse> upstreamResponse;87 private final JsonToWebElementConverter converter;88 private final Function<HttpResponse, HttpResponse> newSessionConverter;89 public ProtocolConverter(90 Tracer tracer,91 HttpClient client,92 Dialect downstream,93 Dialect upstream) {94 this.tracer = Require.nonNull("Tracer", tracer);95 this.client = Require.nonNull("HTTP client", client);96 this.downstream = getCommandCodec(Require.nonNull("Downstream dialect", downstream));97 this.downstreamResponse = getResponseCodec(downstream);98 this.upstream = getCommandCodec(Require.nonNull("Upstream dialect", upstream));99 this.upstreamResponse = getResponseCodec(upstream);100 converter = new JsonToWebElementConverter(null);101 newSessionConverter = downstream == W3C ? this::createW3CNewSessionResponse : this::createJwpNewSessionResponse;102 }103 @Override104 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {105 try (Span span = newSpanAsChildOf(tracer, req, "protocol_converter")) {106 Map<String, EventAttributeValue> attributeMap = new HashMap<>();107 attributeMap.put(AttributeKey.HTTP_HANDLER_CLASS.getKey(),108 EventAttribute.setValue(getClass().getName()));109 Command command = downstream.decode(req);110 KIND.accept(span, Span.Kind.SERVER);111 HTTP_REQUEST.accept(span, req);112 HTTP_REQUEST_EVENT.accept(attributeMap, req);113 SessionId sessionId = command.getSessionId();114 SESSION_ID.accept(span, sessionId);115 SESSION_ID_EVENT.accept(attributeMap, sessionId);116 String commandName = command.getName();117 span.setAttribute("command.name", commandName);118 attributeMap.put("command.name", EventAttribute.setValue(commandName));119 attributeMap.put("downstream.command.parameters", EventAttribute.setValue(command.getParameters().toString()));120 // Massage the webelements121 @SuppressWarnings("unchecked")122 Map<String, ?> parameters = (Map<String, ?>) converter.apply(command.getParameters());123 command = new Command(124 command.getSessionId(),125 command.getName(),126 parameters);127 attributeMap.put("upstream.command.parameters", EventAttribute.setValue(command.getParameters().toString()));128 HttpRequest request = upstream.encode(command);129 HttpTracing.inject(tracer, span, request);130 HttpResponse res = makeRequest(request);131 if(!res.isSuccessful()) {132 span.setAttribute("error", true);133 span.setStatus(Status.UNKNOWN);134 }135 HTTP_RESPONSE.accept(span, res);136 HTTP_RESPONSE_EVENT.accept(attributeMap, res);137 HttpResponse toReturn;138 if (DriverCommand.NEW_SESSION.equals(command.getName()) && res.getStatus() == HTTP_OK) {139 toReturn = newSessionConverter.apply(res);140 } else {141 Response decoded = upstreamResponse.decode(res);...
Source:DockerSessionFactory.java
...37import org.openqa.selenium.remote.http.HttpClient;38import org.openqa.selenium.remote.http.HttpRequest;39import org.openqa.selenium.remote.http.HttpResponse;40import org.openqa.selenium.remote.tracing.AttributeKey;41import org.openqa.selenium.remote.tracing.EventAttribute;42import org.openqa.selenium.remote.tracing.EventAttributeValue;43import org.openqa.selenium.remote.tracing.Span;44import org.openqa.selenium.remote.tracing.Status;45import org.openqa.selenium.remote.tracing.Tracer;46import org.openqa.selenium.support.ui.FluentWait;47import org.openqa.selenium.support.ui.Wait;48import java.io.IOException;49import java.io.UncheckedIOException;50import java.net.MalformedURLException;51import java.net.URL;52import java.time.Duration;53import java.time.Instant;54import java.util.HashMap;55import java.util.Map;56import java.util.Objects;57import java.util.Optional;58import java.util.logging.Level;59import java.util.logging.Logger;60import static org.openqa.selenium.docker.ContainerInfo.image;61import static org.openqa.selenium.remote.Dialect.W3C;62import static org.openqa.selenium.remote.http.Contents.string;63import static org.openqa.selenium.remote.http.HttpMethod.GET;64import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;65public class DockerSessionFactory implements SessionFactory {66 private static final Logger LOG = Logger.getLogger(DockerSessionFactory.class.getName());67 private final Tracer tracer;68 private final HttpClient.Factory clientFactory;69 private final Docker docker;70 private final Image image;71 private final Capabilities stereotype;72 public DockerSessionFactory(73 Tracer tracer,74 HttpClient.Factory clientFactory,75 Docker docker,76 Image image,77 Capabilities stereotype) {78 this.tracer = Require.nonNull("Tracer", tracer);79 this.clientFactory = Require.nonNull("HTTP client", clientFactory);80 this.docker = Require.nonNull("Docker command", docker);81 this.image = Require.nonNull("Docker image", image);82 this.stereotype = ImmutableCapabilities.copyOf(83 Require.nonNull("Stereotype", stereotype));84 }85 @Override86 public boolean test(Capabilities capabilities) {87 return stereotype.getCapabilityNames().stream()88 .map(name -> Objects.equals(stereotype.getCapability(name), capabilities.getCapability(name)))89 .reduce(Boolean::logicalAnd)90 .orElse(false);91 }92 @Override93 public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {94 LOG.info("Starting session for " + sessionRequest.getCapabilities());95 int port = PortProber.findFreePort();96 URL remoteAddress = getUrl(port);97 HttpClient client = clientFactory.createClient(remoteAddress);98 try (Span span = tracer.getCurrentContext().createSpan("docker_session_factory.apply")) {99 Map<String, EventAttributeValue> attributeMap = new HashMap<>();100 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),101 EventAttribute.setValue(this.getClass().getName()));102 LOG.info("Creating container, mapping container port 4444 to " + port);103 Container container = docker.create(image(image).map(Port.tcp(4444), Port.tcp(port)));104 container.start();105 attributeMap.put("docker.image", EventAttribute.setValue(image.toString()));106 attributeMap.put("container.port", EventAttribute.setValue(port));107 attributeMap.put("container.id", EventAttribute.setValue(container.getId().toString()));108 attributeMap.put("docker.server.url", EventAttribute.setValue(remoteAddress.toString()));109 LOG.info(String.format("Waiting for server to start (container id: %s)", container.getId()));110 try {111 waitForServerToStart(client, Duration.ofMinutes(1));112 span.addEvent("Container started. Docker server ready.", attributeMap);113 } catch (TimeoutException e) {114 span.setAttribute("error", true);115 span.setStatus(Status.CANCELLED);116 EXCEPTION.accept(attributeMap, e);117 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),118 EventAttribute.setValue("Unable to connect to docker server. Stopping container: " + e.getMessage()));119 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);120 container.stop(Duration.ofMinutes(1));121 container.delete();122 LOG.warning(String.format(123 "Unable to connect to docker server (container id: %s)", container.getId()));124 return Optional.empty();125 }126 LOG.info(String.format("Server is ready (container id: %s)", container.getId()));127 Command command = new Command(128 null,129 DriverCommand.NEW_SESSION(sessionRequest.getCapabilities()));130 ProtocolHandshake.Result result;131 Response response;132 try {133 result = new ProtocolHandshake().createSession(client, command);134 response = result.createResponse();135 attributeMap.put(AttributeKey.DRIVER_RESPONSE.getKey(), EventAttribute.setValue(response.toString()));136 } catch (IOException | RuntimeException e) {137 span.setAttribute("error", true);138 span.setStatus(Status.CANCELLED);139 EXCEPTION.accept(attributeMap, e);140 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),141 EventAttribute.setValue("Unable to create session. Stopping and container: " + e.getMessage()));142 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);143 container.stop(Duration.ofMinutes(1));144 container.delete();145 LOG.log(Level.WARNING, "Unable to create session: " + e.getMessage(), e);146 return Optional.empty();147 }148 SessionId id = new SessionId(response.getSessionId());149 Capabilities capabilities = new ImmutableCapabilities((Map<?, ?>) response.getValue());150 Dialect downstream = sessionRequest.getDownstreamDialects().contains(result.getDialect()) ?151 result.getDialect() :152 W3C;153 attributeMap.put(AttributeKey.DOWNSTREAM_DIALECT.getKey(), EventAttribute.setValue(downstream.toString()));154 attributeMap.put(AttributeKey.DRIVER_RESPONSE.getKey(), EventAttribute.setValue(response.toString()));155 span.addEvent("Docker driver service created session", attributeMap);156 LOG.info(String.format(157 "Created session: %s - %s (container id: %s)",158 id,159 capabilities,160 container.getId()));161 return Optional.of(new DockerSession(162 container,163 tracer,164 client,165 id,166 remoteAddress,167 stereotype,168 capabilities,...
Source:DriverServiceSessionFactory.java
...33import org.openqa.selenium.remote.SessionId;34import org.openqa.selenium.remote.http.HttpClient;35import org.openqa.selenium.remote.service.DriverService;36import org.openqa.selenium.remote.tracing.AttributeKey;37import org.openqa.selenium.remote.tracing.EventAttribute;38import org.openqa.selenium.remote.tracing.EventAttributeValue;39import org.openqa.selenium.remote.tracing.Span;40import org.openqa.selenium.remote.tracing.Status;41import org.openqa.selenium.remote.tracing.Tracer;42import java.net.URI;43import java.net.URL;44import java.time.Instant;45import java.util.HashMap;46import java.util.Map;47import java.util.Optional;48import java.util.Set;49import java.util.function.Predicate;50import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES;51import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES_EVENT;52import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;53public class DriverServiceSessionFactory implements SessionFactory {54 private final Tracer tracer;55 private final HttpClient.Factory clientFactory;56 private final Predicate<Capabilities> predicate;57 private final DriverService.Builder builder;58 private final Capabilities stereotype;59 public DriverServiceSessionFactory(60 Tracer tracer,61 HttpClient.Factory clientFactory,62 Capabilities stereotype,63 Predicate<Capabilities> predicate,64 DriverService.Builder builder) {65 this.tracer = Require.nonNull("Tracer", tracer);66 this.clientFactory = Require.nonNull("HTTP client factory", clientFactory);67 this.stereotype = ImmutableCapabilities.copyOf(Require.nonNull("Stereotype", stereotype));68 this.predicate = Require.nonNull("Accepted capabilities predicate", predicate);69 this.builder = Require.nonNull("Driver service bulder", builder);70 }71 @Override72 public boolean test(Capabilities capabilities) {73 return predicate.test(capabilities);74 }75 @Override76 public Optional<ActiveSession> apply(CreateSessionRequest sessionRequest) {77 if (sessionRequest.getDownstreamDialects().isEmpty()) {78 return Optional.empty();79 }80 if (!test(sessionRequest.getCapabilities())) {81 return Optional.empty();82 }83 try (Span span = tracer.getCurrentContext().createSpan("driver_service_factory.apply")) {84 Map<String, EventAttributeValue> attributeMap = new HashMap<>();85 Capabilities capabilities = sessionRequest.getCapabilities();86 CAPABILITIES.accept(span, capabilities);87 CAPABILITIES_EVENT.accept(attributeMap, capabilities);88 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(), EventAttribute.setValue(this.getClass().getName()));89 DriverService service = builder.build();90 try {91 service.start();92 URL serviceURL = service.getUrl();93 attributeMap.put(AttributeKey.DRIVER_URL.getKey(), EventAttribute.setValue(serviceURL.toString()));94 HttpClient client = clientFactory.createClient(serviceURL);95 Command command = new Command(96 null,97 DriverCommand.NEW_SESSION(sessionRequest.getCapabilities()));98 ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);99 Set<Dialect> downstreamDialects = sessionRequest.getDownstreamDialects();100 Dialect upstream = result.getDialect();101 Dialect downstream = downstreamDialects.contains(result.getDialect()) ?102 result.getDialect() :103 downstreamDialects.iterator().next();104 Response response = result.createResponse();105 attributeMap.put(AttributeKey.UPSTREAM_DIALECT.getKey(), EventAttribute.setValue(upstream.toString()));106 attributeMap.put(AttributeKey.DOWNSTREAM_DIALECT.getKey(), EventAttribute.setValue(downstream.toString()));107 attributeMap.put(AttributeKey.DRIVER_RESPONSE.getKey(), EventAttribute.setValue(response.toString()));108 // TODO: This is a nasty hack. Try and make it elegant.109 Capabilities caps = new ImmutableCapabilities((Map<?, ?>) response.getValue());110 Optional<URI> reportedUri = ChromiumDevToolsLocator.getReportedUri("goog:chromeOptions", caps);111 if (reportedUri.isPresent()) {112 caps = addCdpCapability(caps, reportedUri.get());113 } else {114 reportedUri = ChromiumDevToolsLocator.getReportedUri("ms:edgeOptions", caps);115 if (reportedUri.isPresent()) {116 caps = addCdpCapability(caps, reportedUri.get());117 }118 }119 span.addEvent("Driver service created session", attributeMap);120 return Optional.of(121 new ProtocolConvertingSession(122 tracer,123 client,124 new SessionId(response.getSessionId()),125 service.getUrl(),126 downstream,127 upstream,128 stereotype,129 caps,130 Instant.now()) {131 @Override132 public void stop() {133 service.stop();134 }135 });136 } catch (Exception e) {137 span.setAttribute("error", true);138 span.setStatus(Status.CANCELLED);139 EXCEPTION.accept(attributeMap, e);140 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),141 EventAttribute.setValue("Error while creating session with the driver service. Stopping driver service: " + e.getMessage()));142 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);143 service.stop();144 return Optional.empty();145 }146 } catch (Exception e) {147 return Optional.empty();148 }149 }150 private Capabilities addCdpCapability(Capabilities caps, URI uri) {151 Object raw = caps.getCapability("se:options");152 if (!(raw instanceof Map)) {153 return new PersistentCapabilities(caps).setCapability("se:options", ImmutableMap.of("cdp", uri));154 }155 //noinspection unchecked...
Source:HandleSession.java
...28import org.openqa.selenium.remote.http.HttpHandler;29import org.openqa.selenium.remote.http.HttpRequest;30import org.openqa.selenium.remote.http.HttpResponse;31import org.openqa.selenium.remote.tracing.AttributeKey;32import org.openqa.selenium.remote.tracing.EventAttribute;33import org.openqa.selenium.remote.tracing.EventAttributeValue;34import org.openqa.selenium.remote.tracing.HttpTracing;35import org.openqa.selenium.remote.tracing.Span;36import org.openqa.selenium.remote.tracing.Status;37import org.openqa.selenium.remote.tracing.Tracer;38import java.time.Duration;39import java.util.HashMap;40import java.util.Map;41import java.util.concurrent.Callable;42import java.util.concurrent.ExecutionException;43import static org.openqa.selenium.remote.HttpSessionId.getSessionId;44import static org.openqa.selenium.remote.RemoteTags.SESSION_ID;45import static org.openqa.selenium.remote.RemoteTags.SESSION_ID_EVENT;46import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;47import static org.openqa.selenium.remote.tracing.Tags.HTTP_REQUEST;48import static org.openqa.selenium.remote.tracing.Tags.HTTP_REQUEST_EVENT;49import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE;50import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE_EVENT;51class HandleSession implements HttpHandler {52 private final Tracer tracer;53 private final HttpClient.Factory httpClientFactory;54 private final SessionMap sessions;55 private final Cache<SessionId, HttpHandler> knownSessions;56 HandleSession(57 Tracer tracer,58 HttpClient.Factory httpClientFactory,59 SessionMap sessions) {60 this.tracer = Require.nonNull("Tracer", tracer);61 this.httpClientFactory = Require.nonNull("HTTP client factory", httpClientFactory);62 this.sessions = Require.nonNull("Sessions", sessions);63 this.knownSessions = CacheBuilder.newBuilder()64 .expireAfterAccess(Duration.ofMinutes(1))65 .build();66 }67 @Override68 public HttpResponse execute(HttpRequest req) {69 try (Span span = HttpTracing.newSpanAsChildOf(tracer, req, "router.handle_session")) {70 Map<String, EventAttributeValue> attributeMap = new HashMap<>();71 attributeMap.put(AttributeKey.HTTP_HANDLER_CLASS.getKey(),72 EventAttribute.setValue(getClass().getName()));73 HTTP_REQUEST.accept(span, req);74 HTTP_REQUEST_EVENT.accept(attributeMap, req);75 SessionId id = getSessionId(req.getUri()).map(SessionId::new)76 .orElseThrow(() -> {77 NoSuchSessionException exception = new NoSuchSessionException("Cannot find session: " + req);78 EXCEPTION.accept(attributeMap, exception);79 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),80 EventAttribute.setValue(81 "Unable to execute request for an existing session: " + exception.getMessage()));82 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);83 return exception;84 });85 SESSION_ID.accept(span, id);86 SESSION_ID_EVENT.accept(attributeMap, id);87 try {88 HttpTracing.inject(tracer, span, req);89 HttpResponse res = knownSessions.get(id, loadSessionId(tracer, span, id)).execute(req);90 HTTP_RESPONSE.accept(span, res);91 HTTP_RESPONSE_EVENT.accept(attributeMap, res);92 span.addEvent("Session request execution complete", attributeMap);93 return res;94 } catch (ExecutionException e) {95 span.setAttribute("error", true);96 span.setStatus(Status.CANCELLED);97 EXCEPTION.accept(attributeMap, e);98 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),99 EventAttribute.setValue("Unable to execute request for an existing session: " + e.getMessage()));100 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);101 Throwable cause = e.getCause();102 if (cause instanceof RuntimeException) {103 throw (RuntimeException) cause;104 }105 throw new RuntimeException(cause);106 }107 }108 }109 private Callable<HttpHandler> loadSessionId(Tracer tracer, Span span, SessionId id) {110 return span.wrap(111 () -> {112 Session session = sessions.get(id);113 if (session instanceof HttpHandler) {...
Source:NewSessionQueuer.java
...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();102 @Override103 public boolean matches(HttpRequest req) {104 return routes.matches(req);...
Source:ReverseProxyHandler.java
...21import org.openqa.selenium.remote.http.HttpHandler;22import org.openqa.selenium.remote.http.HttpRequest;23import org.openqa.selenium.remote.http.HttpResponse;24import org.openqa.selenium.remote.tracing.AttributeKey;25import org.openqa.selenium.remote.tracing.EventAttribute;26import org.openqa.selenium.remote.tracing.EventAttributeValue;27import org.openqa.selenium.remote.tracing.Span;28import org.openqa.selenium.remote.tracing.Tracer;29import java.io.UncheckedIOException;30import java.util.HashMap;31import java.util.Map;32import java.util.logging.Logger;33import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;34import static org.openqa.selenium.remote.tracing.Tags.HTTP_REQUEST;35import static org.openqa.selenium.remote.tracing.Tags.HTTP_REQUEST_EVENT;36import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE;37import static org.openqa.selenium.remote.tracing.Tags.HTTP_RESPONSE_EVENT;38import static org.openqa.selenium.remote.tracing.Tags.KIND;39public class ReverseProxyHandler implements HttpHandler {40 private static final Logger LOG = Logger.getLogger(ReverseProxyHandler.class.getName());41 private static final ImmutableSet<String> IGNORED_REQ_HEADERS = ImmutableSet.<String>builder()42 .add("connection")43 .add("keep-alive")44 .add("proxy-authorization")45 .add("proxy-authenticate")46 .add("proxy-connection")47 .add("te")48 .add("trailer")49 .add("transfer-encoding")50 .add("upgrade")51 .build();52 private final Tracer tracer;53 private final HttpClient upstream;54 public ReverseProxyHandler(Tracer tracer, HttpClient httpClient) {55 this.tracer = Require.nonNull("Tracer", tracer);56 this.upstream = Require.nonNull("HTTP client", httpClient);57 }58 @Override59 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {60 try (Span span = newSpanAsChildOf(tracer, req, "reverse_proxy")) {61 Map<String, EventAttributeValue> attributeMap = new HashMap<>();62 attributeMap.put(AttributeKey.HTTP_HANDLER_CLASS.getKey(),63 EventAttribute.setValue(getClass().getName()));64 KIND.accept(span, Span.Kind.SERVER);65 HTTP_REQUEST.accept(span, req);66 HTTP_REQUEST_EVENT.accept(attributeMap, req);67 HttpRequest toUpstream = new HttpRequest(req.getMethod(), req.getUri());68 for (String name : req.getQueryParameterNames()) {69 for (String value : req.getQueryParameters(name)) {70 toUpstream.addQueryParameter(name, value);71 }72 }73 for (String name : req.getHeaderNames()) {74 if (IGNORED_REQ_HEADERS.contains(name.toLowerCase())) {75 continue;76 }77 for (String value : req.getHeaders(name)) {...
Source:RemoteTags.java
...16// under the License.17package org.openqa.selenium.remote;18import org.openqa.selenium.Capabilities;19import org.openqa.selenium.remote.tracing.AttributeKey;20import org.openqa.selenium.remote.tracing.EventAttribute;21import org.openqa.selenium.remote.tracing.EventAttributeValue;22import org.openqa.selenium.remote.tracing.Span;23import java.util.Map;24import java.util.function.BiConsumer;25public class RemoteTags {26 private RemoteTags() {27 // Utility class28 }29 public static final BiConsumer<Span, Capabilities>30 CAPABILITIES =31 (span, caps) -> span32 .setAttribute(AttributeKey.SESSION_CAPABILITIES.getKey(), String.valueOf(caps));33 public static final BiConsumer<Span, SessionId> SESSION_ID = (span, id) ->34 span.setAttribute(AttributeKey.SESSION_ID.getKey(), String.valueOf(id));35 public static final BiConsumer<Map<String, EventAttributeValue>, Capabilities>36 CAPABILITIES_EVENT =37 (map, caps) ->38 map.put(AttributeKey.SESSION_CAPABILITIES.getKey(),39 EventAttribute.setValue(String.valueOf(caps)));40 public static final BiConsumer<Map<String, EventAttributeValue>, SessionId>41 SESSION_ID_EVENT =42 (map, id) ->43 map.put(AttributeKey.SESSION_ID.getKey(), EventAttribute.setValue(String.valueOf(id)));44}...
EventAttribute
Using AI Code Generation
1package com.selenium;2import org.openqa.selenium.remote.tracing.EventAttribute;3import org.openqa.selenium.remote.tracing.EventAttributeValue;4public class EventAttributeDemo {5 public static void main(String[] args) {6 EventAttribute attribute = EventAttribute.create("key", EventAttributeValue.stringAttributeValue("value"));7 System.out.println(attribute.getKey());8 System.out.println(attribute.getValue().asString());9 }10}
EventAttribute
Using AI Code Generation
1package com.test;2import org.openqa.selenium.remote.tracing.EventAttribute;3import org.openqa.selenium.remote.tracing.EventAttributeValue;4public class EventAttributeSample {5 public static void main(String[] args) {6 EventAttribute attribute = EventAttribute.newBuilder().setName("attributeName").setValue(EventAttributeValue.stringAttributeValue("attributeValue")).build();7 System.out.println(attribute.getName());8 System.out.println(attribute.getValue().getValue());9 }10}
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!!