Best Selenium code snippet using org.openqa.selenium.docker.Port.toString
Source:SauceDockerSessionFactory.java
...128 return Either.left(new SessionNotCreatedException(message));129 }130 @SuppressWarnings("OptionalGetWithoutIsPresent")131 UsernameAndPassword usernameAndPassword =132 new UsernameAndPassword(userName.get().toString(), accessKey.get().toString());133 Optional<Object> dc =134 getSauceCapability(sessionRequest.getDesiredCapabilities(), "dataCenter");135 DataCenter dataCenter = DataCenter.US_WEST;136 if (dc.isPresent()) {137 dataCenter = DataCenter.fromString(String.valueOf(dc.get()));138 }139 Capabilities sessionReqCaps = removeSauceKey(sessionRequest.getDesiredCapabilities());140 LOG.info("Starting session for " + sessionReqCaps);141 int port = runningInDocker ? 4444 : PortProber.findFreePort();142 try (Span span = tracer.getCurrentContext().createSpan("docker_session_factory.apply")) {143 Map<String, EventAttributeValue> attributeMap = new HashMap<>();144 attributeMap.put(AttributeKey.LOGGER_CLASS.getKey(),145 EventAttribute.setValue(this.getClass().getName()));146 String logMessage = runningInDocker ? "Creating container..." :147 "Creating container, mapping container port 4444 to " + port;148 LOG.info(logMessage);149 Container container = createBrowserContainer(port, sessionReqCaps);150 container.start();151 ContainerInfo containerInfo = container.inspect();152 String containerIp = containerInfo.getIp();153 URL remoteAddress = getUrl(port, containerIp);154 HttpClient client = clientFactory.createClient(remoteAddress);155 attributeMap.put("docker.browser.image", EventAttribute.setValue(browserImage.toString()));156 attributeMap.put("container.port", EventAttribute.setValue(port));157 attributeMap.put("container.id", EventAttribute.setValue(container.getId().toString()));158 attributeMap.put("container.ip", EventAttribute.setValue(containerInfo.getIp()));159 attributeMap.put("docker.server.url", EventAttribute.setValue(remoteAddress.toString()));160 LOG.info(161 String.format("Waiting for server to start (container id: %s, url %s)",162 container.getId(),163 remoteAddress));164 try {165 waitForServerToStart(client, Duration.ofMinutes(1));166 } catch (TimeoutException e) {167 span.setAttribute("error", true);168 span.setStatus(Status.CANCELLED);169 EXCEPTION.accept(attributeMap, e);170 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),171 EventAttribute.setValue(172 "Unable to connect to docker server. Stopping container: " +173 e.getMessage()));174 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);175 container.stop(Duration.ofMinutes(1));176 String message = String.format(177 "Unable to connect to docker server (container id: %s)", container.getId());178 LOG.warning(message);179 return Either.left(new RetrySessionRequestException(message));180 }181 LOG.info(String.format("Server is ready (container id: %s)", container.getId()));182 Command command = new Command(183 null,184 DriverCommand.NEW_SESSION(sessionReqCaps));185 ProtocolHandshake.Result result;186 Response response;187 try {188 result = new ProtocolHandshake().createSession(client, command);189 response = result.createResponse();190 attributeMap.put(191 AttributeKey.DRIVER_RESPONSE.getKey(),192 EventAttribute.setValue(response.toString()));193 } catch (IOException | RuntimeException e) {194 span.setAttribute("error", true);195 span.setStatus(Status.CANCELLED);196 EXCEPTION.accept(attributeMap, e);197 attributeMap.put(198 AttributeKey.EXCEPTION_MESSAGE.getKey(),199 EventAttribute200 .setValue("Unable to create session. Stopping and container: " + e.getMessage()));201 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);202 container.stop(Duration.ofMinutes(1));203 String message = "Unable to create session: " + e.getMessage();204 LOG.log(Level.WARNING, message);205 return Either.left(new SessionNotCreatedException(message));206 }207 SessionId id = new SessionId(response.getSessionId());208 Capabilities capabilities = new ImmutableCapabilities((Map<?, ?>) response.getValue());209 Capabilities mergedCapabilities = capabilities.merge(sessionReqCaps);210 Container videoContainer = null;211 Optional<DockerAssetsPath> path = ofNullable(this.assetsPath);212 if (path.isPresent()) {213 // Seems we can store session assets214 String containerPath = path.get().getContainerPath(id);215 saveSessionCapabilities(mergedCapabilities, containerPath);216 String hostPath = path.get().getHostPath(id);217 videoContainer = startVideoContainer(mergedCapabilities, containerInfo.getIp(), hostPath);218 }219 Instant startTime = Instant.now();220 Instant videoStartTime = Instant.now();221 Dialect downstream = sessionRequest.getDownstreamDialects().contains(result.getDialect()) ?222 result.getDialect() :223 W3C;224 attributeMap.put(225 AttributeKey.DOWNSTREAM_DIALECT.getKey(),226 EventAttribute.setValue(downstream.toString()));227 attributeMap.put(228 AttributeKey.DRIVER_RESPONSE.getKey(),229 EventAttribute.setValue(response.toString()));230 SauceCommandInfo commandInfo = new SauceCommandInfo.Builder()231 .setStartTime(startTime.toEpochMilli())232 .setVideoStartTime(videoStartTime.toEpochMilli())233 .setEndTime(Instant.now().toEpochMilli())234 .setRequest(sessionReqCaps)235 .setResult(mergedCapabilities)236 .setPath("/session")237 .setHttpStatus(response.getStatus())238 .setHttpMethod(POST.name())239 .setStatusCode(0)240 .setScreenshotId(-1)241 .build();242 span.addEvent("Docker driver service created session", attributeMap);243 LOG.fine(String.format(244 "Created session: %s - %s (container id: %s)",245 id,246 capabilities,247 container.getId()));248 return Either.right(new SauceDockerSession(249 container,250 videoContainer,251 tracer,252 client,253 id,254 remoteAddress,255 stereotype,256 mergedCapabilities,257 downstream,258 result.getDialect(),259 startTime,260 assetsPath,261 usernameAndPassword,262 dataCenter,263 assetsUploaderImage,264 commandInfo,265 docker));266 }267 }268 private Container createBrowserContainer(int port, Capabilities sessionCapabilities) {269 Map<String, String> browserContainerEnvVars = getBrowserContainerEnvVars(sessionCapabilities);270 long browserContainerShmMemorySize = 2147483648L; //2GB271 ContainerConfig containerConfig = image(browserImage)272 .env(browserContainerEnvVars)273 .shmMemorySize(browserContainerShmMemorySize)274 .network(networkName);275 if (!runningInDocker) {276 containerConfig = containerConfig.map(Port.tcp(4444), Port.tcp(port));277 }278 return docker.create(containerConfig);279 }280 private Map<String, String> getBrowserContainerEnvVars(Capabilities sessionRequestCapabilities) {281 Optional<Dimension> screenResolution =282 ofNullable(getScreenResolution(sessionRequestCapabilities));283 Map<String, String> envVars = new HashMap<>();284 if (screenResolution.isPresent()) {285 envVars.put("SCREEN_WIDTH", String.valueOf(screenResolution.get().getWidth()));286 envVars.put("SCREEN_HEIGHT", String.valueOf(screenResolution.get().getHeight()));287 }288 Optional<TimeZone> timeZone = ofNullable(getTimeZone(sessionRequestCapabilities));289 timeZone.ifPresent(zone -> envVars.put("TZ", zone.getID()));290 return envVars;291 }292 private Container startVideoContainer(Capabilities sessionCapabilities,293 String browserContainerIp, String hostPath) {294 if (!recordVideoForSession(sessionCapabilities)) {295 return null;296 }297 int videoPort = 9000;298 Map<String, String> envVars = getVideoContainerEnvVars(299 sessionCapabilities,300 browserContainerIp);301 Map<String, String> volumeBinds = Collections.singletonMap(hostPath, "/videos");302 ContainerConfig containerConfig = image(videoImage)303 .env(envVars)304 .bind(volumeBinds)305 .network(networkName);306 if (!runningInDocker) {307 videoPort = PortProber.findFreePort();308 containerConfig = containerConfig.map(Port.tcp(9000), Port.tcp(videoPort));309 }310 Container videoContainer = docker.create(containerConfig);311 videoContainer.start();312 String videoContainerIp = runningInDocker ? videoContainer.inspect().getIp() : "localhost";313 try {314 URL videoContainerUrl = new URL(String.format("http://%s:%s", videoContainerIp, videoPort));315 HttpClient videoClient = clientFactory.createClient(videoContainerUrl);316 LOG.fine(String.format("Waiting for video recording... (id: %s)", videoContainer.getId()));317 waitForServerToStart(videoClient, Duration.ofMinutes(1));318 } catch (Exception e) {319 videoContainer.stop(Duration.ofSeconds(10));320 String message = String.format(321 "Unable to verify video recording started (container id: %s), %s", videoContainer.getId(),322 e.getMessage());323 LOG.warning(message);324 }325 LOG.info(String.format("Video container started (id: %s)", videoContainer.getId()));326 return videoContainer;327 }328 private Map<String, String> getVideoContainerEnvVars(Capabilities sessionRequestCapabilities,329 String containerIp) {330 Map<String, String> envVars = new HashMap<>();331 envVars.put("DISPLAY_CONTAINER_NAME", containerIp);332 Optional<Dimension> screenResolution =333 ofNullable(getScreenResolution(sessionRequestCapabilities));334 screenResolution.ifPresent(dimension -> envVars335 .put("VIDEO_SIZE", String.format("%sx%s", dimension.getWidth(), dimension.getHeight())));336 return envVars;337 }338 private TimeZone getTimeZone(Capabilities sessionRequestCapabilities) {339 Optional<Object> timeZone =340 getSauceCapability(sessionRequestCapabilities, "timeZone");341 if (timeZone.isPresent()) {342 String tz = timeZone.get().toString();343 if (Arrays.asList(TimeZone.getAvailableIDs()).contains(tz)) {344 return TimeZone.getTimeZone(tz);345 }346 }347 return null;348 }349 private Dimension getScreenResolution(Capabilities sessionRequestCapabilities) {350 Optional<Object> screenResolution =351 getSauceCapability(sessionRequestCapabilities, "screenResolution");352 if (!screenResolution.isPresent()) {353 return null;354 }355 try {356 String[] resolution = screenResolution.get().toString().split("x");357 int screenWidth = Integer.parseInt(resolution[0]);358 int screenHeight = Integer.parseInt(resolution[1]);359 if (screenWidth > 0 && screenHeight > 0) {360 return new Dimension(screenWidth, screenHeight);361 } else {362 LOG.warning("One of the values provided for screenResolution is negative, " +363 "defaults will be used. Received value: " + screenResolution);364 }365 } catch (Exception e) {366 LOG.warning("Values provided for screenResolution are not valid integers or " +367 "either width or height are missing, defaults will be used." +368 "Received value: " + screenResolution);369 }370 return null;371 }372 private boolean recordVideoForSession(Capabilities sessionRequestCapabilities) {373 boolean recordVideo = true;374 Optional<Object> recordVideoCapability =375 getSauceCapability(sessionRequestCapabilities, "recordVideo");376 if (recordVideoCapability.isPresent()) {377 recordVideo = Boolean.parseBoolean(recordVideoCapability.get().toString());378 }379 return recordVideo;380 }381 private void saveSessionCapabilities(Capabilities sessionRequestCapabilities, String path) {382 String capsToJson = JSON.toJson(sessionRequestCapabilities);383 try {384 Files.createDirectories(Paths.get(path));385 Files.write(386 Paths.get(path, "sessionCapabilities.json"),387 capsToJson.getBytes(Charset.defaultCharset()));388 } catch (IOException e) {389 LOG.log(Level.WARNING,390 "Failed to save session capabilities", e);391 }...
Source:DockerSessionFactory.java
...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:Port.java
...31 }32 public int getPort() {33 return port;34 }35 public String toString() {36 return port + "/" + protocol;37 }38}...
toString
Using AI Code Generation
1import org.openqa.selenium.docker.Port;2import org.openqa.selenium.docker.Container;3import org.openqa.selenium.docker.Vnc;4import org.openqa.selenium.docker.Docker;5import org.openqa.selenium.docker.Image;6import org.openqa.selenium.docker.Vnc;7import org.openqa.selenium.remote.http.HttpClient;8import org.openqa.selenium.remote.http.HttpResponse;9import org.openqa.selenium.remote.http.HttpRequest;10import org.openqa.selenium.remote.http.Route;11import org.openqa.selenium.remote.http.Filters;12import org.openqa.selenium.remote.http.Contents;13import java.net.URL;14import java.net.URI;15import java.net.URISyntaxException;16import java.io.IOException;17import java.util.Map;18import java.util.HashMap;19import java.util.concurrent.TimeUnit;20import java.time.Duration;21import java.util.function.Function;22import java.util.logging.Logger;23import java.util.logging.Level;24import java.util.stream.Collectors;25import java.util.Optional;26import static java.net.HttpURLConnection.HTTP_OK;27import static java.net.HttpURLConnection.HTTP_NOT_FOUND;28import static java.util.logging.Logger.getLogger;29import static org.openqa.selenium.docker.Port.toPort;30import static org.openqa.selenium.docker.Port.toString;31import static org.openqa.selenium.docker.Container.toContainer;32import static org.openqa.selenium.docker.Container.toString;33import static org.openqa.selenium.docker.Image.toImage;34import static org.openqa.selenium.docker.Image.toString;35import static org.openqa.selenium.docker.Vnc.toVnc;36import static org.openqa.selenium.docker.Vnc.toString;37import static org.openqa.selenium.docker.Docker.toDocker;38import static org.openqa.selenium.docker.Docker.toString;39import static org.openqa.selenium.remote.http.HttpMethod.GET;40import static org.openqa.selenium.remote.http.HttpMethod.POST;41import static org.openqa.selenium.remote.http.HttpMethod.DELETE;42import static org.openqa.selenium.remote.http.Route.combine;43import static org.openqa.selenium.remote.http.Route.get;44import static org.openqa.selenium.remote.http.Route.post;45import static org.openqa.selenium.remote.http.Route.delete;46import static org.openqa.selenium.remote.http.Filters.addResponseHeaders;47import static org.openqa.selenium.remote.http.Contents.utf8String;48import static java.util.logging.Level.FINE;49import static java.util.stream.Collectors.toList;50import static java.util.Optional.ofNullable;51public class DockerExample {52 private static final Logger LOG = getLogger(DockerExample.class.getName());53 public static void main(String[] args) throws Exception {54 Docker docker = new Docker();55 if (!docker.isRunning()) {56 throw new IllegalStateException("Docker is not running");57 }
toString
Using AI Code Generation
1System.out.println(port.toString());2Port port = Port.valueOf("4444/tcp");3Constructor Description Port(int port, String protocol) Creates a Port object with the given port number and protocol4Method Description toString() Returns string representation of the port object5package org.seleniumhq.selenium.docker.example;6import org.openqa.selenium.docker.Docker;7import org.openqa.selenium.docker.Port;8public class PortExample {9 public static void main(String[] args) {10 Port port = new Port(4444, "tcp");11 System.out.println(port.toString());12 port = Port.valueOf("4444/tcp");13 System.out.println(port.toString());14 }15}16Constructor Description PortBinding(String hostIp, int hostPort, int containerPort, String protocol) Creates a PortBinding object with the given host IP, host port, container port and protocol17Method Description toString() Returns string representation of the port binding object18package org.seleniumhq.selenium.docker.example;19import org.openqa.selenium.docker.Docker;20import org.openqa.selenium.docker.PortBinding;21public class PortBindingExample {22 public static void main(String
toString
Using AI Code Generation
1String portNumber = port.toString().split(":")[1];2System.out.println(portNumber);3String portNumber = port.toString().split(":")[1];4System.out.println(portNumber);5String portNumber = port.toString().split(":")[1];6System.out.println(portNumber);7String portNumber = port.toString().split(":")[1];8System.out.println(portNumber);9String portNumber = port.toString().split(":")[1];10System.out.println(portNumber);11String portNumber = port.toString().split(":")[1];12System.out.println(portNumber);13String portNumber = port.toString().split(":")[1];14System.out.println(portNumber);15String portNumber = port.toString().split(":")[1];16System.out.println(portNumber);17String portNumber = port.toString().split(":")[1];18System.out.println(portNumber);
toString
Using AI Code Generation
1int port = container.getPort(80).toString();2System.out.println(port);3int hostPort = container.getPort(80).getHostPort();4System.out.println(hostPort);5int containerPort = container.getPort(80).getContainerPort();6System.out.println(containerPort);7String protocol = container.getPort(80).getProtocol();8System.out.println(protocol);9String host = container.getPort(80).getHost();10System.out.println(host);11String host1 = container.getPort(80).getHost();12System.out.println(host1);13String host2 = container.getPort(80).getHost();14System.out.println(host2);15String host3 = container.getPort(80).getHost();16System.out.println(host3);17String host4 = container.getPort(80).getHost();18System.out.println(host4);
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!!