How to use bytes method of org.openqa.selenium.remote.http.Contents class

Best Selenium code snippet using org.openqa.selenium.remote.http.Contents.bytes

Source:NettyDomainSocketClient.java Github

copy

Full Screen

...66import java.util.concurrent.atomic.AtomicReference;67import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;68import static java.nio.charset.StandardCharsets.UTF_8;69import static java.util.concurrent.TimeUnit.MILLISECONDS;70import static org.openqa.selenium.remote.http.Contents.bytes;71import static org.openqa.selenium.remote.http.Contents.utf8String;72class NettyDomainSocketClient extends RemoteCall implements HttpClient {73 private final EventLoopGroup eventLoopGroup;74 private final Class<? extends Channel> channelClazz;75 private final String path;76 public NettyDomainSocketClient(ClientConfig config) {77 super(config);78 URI uri = config.baseUri();79 Require.argument("URI scheme", uri.getScheme()).equalTo("unix");80 if (Epoll.isAvailable()) {81 this.eventLoopGroup = new EpollEventLoopGroup();82 this.channelClazz = EpollDomainSocketChannel.class;83 } else if (KQueue.isAvailable()) {84 this.eventLoopGroup = new KQueueEventLoopGroup();85 this.channelClazz = KQueueDomainSocketChannel.class;86 } else {87 throw new IllegalStateException("No native library for unix domain sockets is available");88 }89 this.path = uri.getPath();90 }91 @Override92 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {93 Require.nonNull("Request to send", req);94 AtomicReference<HttpResponse> outRef = new AtomicReference<>();95 CountDownLatch latch = new CountDownLatch(1);96 Channel channel = createChannel(outRef, latch);97 StringBuilder uri = new StringBuilder(req.getUri());98 List<String> queryPairs = new ArrayList<>();99 req.getQueryParameterNames().forEach(100 name -> req.getQueryParameters(name).forEach(101 value -> {102 try {103 queryPairs.add(URLEncoder.encode(name, UTF_8.toString()) + "=" + URLEncoder.encode(value, UTF_8.toString()));104 } catch (UnsupportedEncodingException e) {105 Thread.currentThread().interrupt();106 throw new UncheckedIOException(e);107 }108 }));109 if (!queryPairs.isEmpty()) {110 uri.append("?");111 Joiner.on('&').appendTo(uri, queryPairs);112 }113 byte[] bytes = bytes(req.getContent());114 DefaultFullHttpRequest fullRequest = new DefaultFullHttpRequest(115 HttpVersion.HTTP_1_1,116 HttpMethod.valueOf(req.getMethod().toString()),117 uri.toString(),118 Unpooled.wrappedBuffer(bytes));119 req.getHeaderNames().forEach(name -> req.getHeaders(name).forEach(value -> fullRequest.headers().add(name, value)));120 if (req.getHeader("User-Agent") == null) {121 fullRequest.headers().set("User-Agent", AddSeleniumUserAgent.USER_AGENT);122 }123 fullRequest.headers().set(HttpHeaderNames.HOST, "localhost");124 fullRequest.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);125 fullRequest.headers().set(HttpHeaderNames.CONTENT_LENGTH, bytes.length);126 ChannelFuture future = channel.writeAndFlush(fullRequest);127 try {128 future.get();129 channel.closeFuture().sync();130 } catch (InterruptedException | ExecutionException e) {131 Thread.currentThread().interrupt();132 throw new UncheckedIOException(new IOException(e));133 }134 try {135 if (!latch.await(getConfig().readTimeout().toMillis(), MILLISECONDS)) {136 throw new UncheckedIOException(new IOException("Timed out waiting for response"));137 }138 } catch (InterruptedException e) {139 Thread.currentThread().interrupt();140 throw new RuntimeException(e);141 }142 return outRef.get();143 }144 @Override145 public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) {146 throw new UnsupportedOperationException("openSocket");147 }148 private Channel createChannel(AtomicReference<HttpResponse> outRef, CountDownLatch latch) {149 Bootstrap bootstrap = new Bootstrap()150 .group(eventLoopGroup)151 .channel(channelClazz)152 .handler(new ChannelInitializer<UnixChannel>() {153 @Override154 public void initChannel(UnixChannel ch) {155 ch156 .pipeline()157 .addLast(new HttpClientCodec())158 .addLast(new HttpContentDecompressor())159 .addLast(new HttpObjectAggregator(Integer.MAX_VALUE))160 .addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {161 @Override162 public void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {163 HttpResponse res = new HttpResponse().setStatus(msg.status().code());164 msg.headers().forEach(entry -> res.addHeader(entry.getKey(), entry.getValue()));165 try (InputStream is = new ByteBufInputStream(msg.content());166 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {167 ByteStreams.copy(is, bos);168 res.setContent(bytes(bos.toByteArray()));169 outRef.set(res);170 latch.countDown();171 } catch (IOException e) {172 outRef.set(new HttpResponse()173 .setStatus(HTTP_INTERNAL_ERROR)174 .setContent(utf8String(Throwables.getStackTraceAsString(e))));175 latch.countDown();176 }177 }178 @Override179 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {180 outRef.set(new HttpResponse()181 .setStatus(HTTP_INTERNAL_ERROR)182 .setContent(utf8String(Throwables.getStackTraceAsString(cause))));...

Full Screen

Full Screen

Source:NetworkInterceptionTest.java Github

copy

Full Screen

...87 Routable replaceImage = Route88 .matching(req -> req.getUri().contains("unsplash.com"))89 .to(() -> req -> new HttpResponse()90 .addHeader("Content-Type", JPEG.toString())91 .setContent(Contents.bytes(sauceBotImage)));92 try (NetworkInterceptor ignore = new NetworkInterceptor(driver, replaceImage)) {93 driver.get(APP_URL.toString());94 String inputFieldLocator = "input[data-testid='new-item-text']";95 WebElement inputField = wait.until(presenceOfElementLocated(By.cssSelector(inputFieldLocator)));96 inputField.sendKeys(item);97 driver.findElement(By.cssSelector("button[data-testid='new-item-button']")).click();98 String itemLocator = String.format("div[data-testid='%s']", item);99 List<WebElement> addedItem = wait.until(presenceOfAllElementsLocatedBy(By.cssSelector(itemLocator)));100 Assertions.assertEquals(1, addedItem.size());101 }102 // Sleep only meant for demo purposes!103 sleepTight(4000);104 }105 @Test...

Full Screen

Full Screen

Source:ResourceHandler.java Github

copy

Full Screen

...39import static com.google.common.net.MediaType.XML_UTF_8;40import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;41import static java.net.HttpURLConnection.HTTP_NOT_FOUND;42import static java.nio.charset.StandardCharsets.UTF_8;43import static org.openqa.selenium.remote.http.Contents.bytes;44import static org.openqa.selenium.remote.http.Contents.utf8String;45import static org.openqa.selenium.remote.http.HttpMethod.GET;46public class ResourceHandler implements Routable {47 private final Resource resource;48 public ResourceHandler(Resource resource) {49 this.resource = Require.nonNull("Resource", resource);50 }51 @Override52 public boolean matches(HttpRequest req) {53 return GET == req.getMethod() && resource.get(req.getUri()).isPresent();54 }55 @Override56 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {57 Optional<Resource> result = resource.get(req.getUri());58 if (!result.isPresent()) {59 return new HttpResponse()60 .setStatus(HTTP_NOT_FOUND)61 .setContent(utf8String("Unable to find " + req.getUri()));62 }63 Resource resource = result.get();64 if (resource.isDirectory()) {65 Optional<Resource> index = resource.get("index.html");66 if (index.isPresent()) {67 return readFile(req, index.get());68 }69 return readDirectory(req, resource);70 }71 return readFile(req, resource);72 }73 private HttpResponse readDirectory(HttpRequest req, Resource resource) {74 if (!req.getUri().endsWith("/")) {75 String dest = UrlPath.relativeToContext(req, req.getUri() + "/");76 return new HttpResponse()77 .setStatus(HTTP_MOVED_TEMP)78 .addHeader("Location", dest);79 }80 String links = resource.list().stream()81 .map(res -> String.format("<li><a href=\"%s\">%s</a>", res.name(), res.name()))82 .sorted()83 .collect(Collectors.joining("\n", "<ul>\n", "</ul>\n"));84 String html = String.format(85 "<html><title>Listing of %s</title><body><h1>%s</h1>%s",86 resource.name(),87 resource.name(),88 links);89 return new HttpResponse()90 .addHeader("Content-Type", HTML_UTF_8.toString())91 .setContent(utf8String(html));92 }93 private HttpResponse readFile(HttpRequest req, Resource resource) {94 Optional<byte[]> bytes = resource.read();95 if (bytes.isPresent()) {96 return new HttpResponse()97 .addHeader("Content-Type", mediaType(req.getUri()))98 .setContent(bytes(bytes.get()));99 }100 return get404(req);101 }102 private HttpResponse get404(HttpRequest req) {103 return new HttpResponse()104 .setStatus(HTTP_NOT_FOUND)105 .setContent(utf8String("Unable to read " + req.getUri()));106 }107 private String mediaType(String uri) {108 int index = uri.lastIndexOf(".");109 String extension = (index == -1 || uri.length() == index) ? "" : uri.substring(index + 1);110 MediaType type;111 switch (extension.toLowerCase()) {112 case "appcache":...

Full Screen

Full Screen

Source:JreAppServer.java Github

copy

Full Screen

...40import static com.google.common.net.MediaType.JSON_UTF_8;41import static java.nio.charset.StandardCharsets.UTF_8;42import static java.util.Collections.singletonMap;43import static org.openqa.selenium.build.InProject.locate;44import static org.openqa.selenium.remote.http.Contents.bytes;45import static org.openqa.selenium.remote.http.Contents.string;46import static org.openqa.selenium.remote.http.Route.get;47import static org.openqa.selenium.remote.http.Route.matching;48import static org.openqa.selenium.remote.http.Route.post;49public class JreAppServer implements AppServer {50 private final Server<?> server;51 public JreAppServer() {52 this(emulateJettyAppServer());53 }54 public JreAppServer(HttpHandler handler) {55 Require.nonNull("Handler", handler);56 int port = PortProber.findFreePort();57 server = new JreServer(58 new BaseServerOptions(new MapConfig(singletonMap("server", singletonMap("port", port)))),59 handler);60 }61 private static Route emulateJettyAppServer() {62 Path common = locate("common/src/web").toAbsolutePath();63 return Route.combine(64 new ResourceHandler(new PathResource(common)),65 get("/encoding").to(EncodingHandler::new),66 matching(req -> req.getUri().startsWith("/page/")).to(PageHandler::new),67 get("/redirect").to(() -> new RedirectHandler()),68 get("/sleep").to(SleepingHandler::new),69 post("/upload").to(UploadHandler::new));70 }71 @Override72 public void start() {73 server.start();74 }75 @Override76 public void stop() {77 server.stop();78 }79 @Override80 public String whereIs(String relativeUrl) {81 return createUrl("http", getHostName(), relativeUrl);82 }83 @Override84 public String whereElseIs(String relativeUrl) {85 return createUrl("http", getAlternateHostName(), relativeUrl);86 }87 @Override88 public String whereIsSecure(String relativeUrl) {89 return createUrl("https", getHostName(), relativeUrl);90 }91 @Override92 public String whereIsWithCredentials(String relativeUrl, String user, String password) {93 return String.format94 ("http://%s:%s@%s:%d/%s",95 user,96 password,97 getHostName(),98 server.getUrl().getPort(),99 relativeUrl);100 }101 private String createUrl(String protocol, String hostName, String relativeUrl) {102 if (!relativeUrl.startsWith("/")) {103 relativeUrl = "/" + relativeUrl;104 }105 try {106 return new URL(107 protocol,108 hostName,109 server.getUrl().getPort(),110 relativeUrl)111 .toString();112 } catch (MalformedURLException e) {113 throw new UncheckedIOException(e);114 }115 }116 @Override117 public String create(Page page) {118 try {119 byte[] data = new Json()120 .toJson(ImmutableMap.of("content", page.toString()))121 .getBytes(UTF_8);122 HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/")));123 HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage");124 request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());125 request.setContent(bytes(data));126 HttpResponse response = client.execute(request);127 return string(response);128 } catch (IOException ex) {129 throw new RuntimeException(ex);130 }131 }132 @Override133 public String getHostName() {134 return "localhost";135 }136 @Override137 public String getAlternateHostName() {138 throw new UnsupportedOperationException("getAlternateHostName");139 }...

Full Screen

Full Screen

Source:HttpMessage.java Github

copy

Full Screen

...16// under the License.17package org.openqa.selenium.remote.http;18import static com.google.common.net.HttpHeaders.CONTENT_TYPE;19import static java.nio.charset.StandardCharsets.UTF_8;20import static org.openqa.selenium.remote.http.Contents.bytes;21import static org.openqa.selenium.remote.http.Contents.reader;22import static org.openqa.selenium.remote.http.Contents.string;23import com.google.common.collect.ArrayListMultimap;24import com.google.common.collect.Multimap;25import com.google.common.net.MediaType;26import java.io.InputStream;27import java.io.Reader;28import java.nio.charset.Charset;29import java.util.HashMap;30import java.util.Iterator;31import java.util.Map;32import java.util.Objects;33import java.util.function.Supplier;34import java.util.stream.Collectors;35class HttpMessage {36 private final Multimap<String, String> headers = ArrayListMultimap.create();37 private final Map<String, Object> attributes = new HashMap<>();38 private Supplier<InputStream> content = Contents.empty();39 /**40 * Retrieves a user-defined attribute of this message. Attributes are stored as simple key-value41 * pairs and are not included in a message's serialized form.42 *43 * @param key attribute name44 * @return attribute object45 */46 public Object getAttribute(String key) {47 return attributes.get(key);48 }49 public void setAttribute(String key, Object value) {50 attributes.put(key, value);51 }52 public void removeAttribute(String key) {53 attributes.remove(key);54 }55 public Iterable<String> getHeaderNames() {56 return headers.keySet();57 }58 public Iterable<String> getHeaders(String name) {59 return headers.entries().stream()60 .filter(e -> Objects.nonNull(e.getKey()))61 .filter(e -> e.getKey().equalsIgnoreCase(name.toLowerCase()))62 .map(Map.Entry::getValue)63 .collect(Collectors.toList());64 }65 public String getHeader(String name) {66 Iterable<String> initialHeaders = getHeaders(name);67 if (initialHeaders == null) {68 return null;69 }70 Iterator<String> headers = initialHeaders.iterator();71 if (headers.hasNext()) {72 return headers.next();73 }74 return null;75 }76 public void setHeader(String name, String value) {77 removeHeader(name);78 addHeader(name, value);79 }80 public void addHeader(String name, String value) {81 headers.put(name, value);82 }83 public void removeHeader(String name) {84 headers.removeAll(name);85 }86 public Charset getContentEncoding() {87 Charset charset = UTF_8;88 try {89 String contentType = getHeader(CONTENT_TYPE);90 if (contentType != null) {91 MediaType mediaType = MediaType.parse(contentType);92 charset = mediaType.charset().or(UTF_8);93 }94 } catch (IllegalArgumentException ignored) {95 // Do nothing.96 }97 return charset;98 }99 /**100 * @deprecated Pass {@link Contents#bytes(byte[])} to {@link #setContent(Supplier)}.101 */102 @Deprecated103 public void setContent(byte[] data) {104 setContent(bytes(data));105 }106 /**107 * @deprecated Pass {@code () -> toStreamFrom} to {@link #setContent(Supplier)}.108 */109 @Deprecated110 public void setContent(InputStream toStreamFrom) {111 setContent(() -> toStreamFrom);112 }113 public void setContent(Supplier<InputStream> supplier) {114 this.content = Objects.requireNonNull(supplier, "Supplier must be set.");115 }116 public Supplier<InputStream> getContent() {117 return content;118 }...

Full Screen

Full Screen

Source:ResourceHandlerTest.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.web;18import org.junit.Before;19import org.junit.Rule;20import org.junit.Test;21import org.junit.rules.TemporaryFolder;22import org.openqa.selenium.remote.http.Contents;23import org.openqa.selenium.remote.http.HttpHandler;24import org.openqa.selenium.remote.http.HttpRequest;25import org.openqa.selenium.remote.http.HttpResponse;26import org.openqa.selenium.remote.http.Route;27import java.io.File;28import java.io.IOException;29import java.nio.file.Files;30import java.nio.file.Path;31import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;32import static java.net.HttpURLConnection.HTTP_OK;33import static java.nio.charset.StandardCharsets.UTF_8;34import static org.assertj.core.api.Assertions.assertThat;35import static org.openqa.selenium.remote.http.HttpMethod.GET;36public class ResourceHandlerTest {37 @Rule38 public TemporaryFolder temp = new TemporaryFolder();39 private Path base;40 @Before41 public void getPath() throws IOException {42 File folder = temp.newFolder();43 this.base = folder.toPath();44 }45 @Test46 public void shouldLoadContent() throws IOException {47 Files.write(base.resolve("content.txt"), "I like cheese".getBytes(UTF_8));48 HttpHandler handler = new ResourceHandler(new PathResource(base));49 HttpResponse res = handler.execute(new HttpRequest(GET, "/content.txt"));50 assertThat(Contents.string(res)).isEqualTo("I like cheese");51 }52 @Test53 public void shouldRedirectIfDirectoryButPathDoesNotEndInASlash() throws IOException {54 Path dir = base.resolve("cheese");55 Files.createDirectories(dir);56 HttpHandler handler = new ResourceHandler(new PathResource(base));57 HttpResponse res = handler.execute(new HttpRequest(GET, "/cheese"));58 assertThat(res.getStatus()).isEqualTo(HTTP_MOVED_TEMP);59 assertThat(res.getHeader("Location")).endsWith("/cheese/");60 }61 @Test62 public void shouldLoadAnIndexPage() throws IOException {63 Path subdir = base.resolve("subdir");64 Files.createDirectories(subdir);65 Files.write(subdir.resolve("1.txt"), new byte[0]);66 Files.write(subdir.resolve("2.txt"), new byte[0]);67 HttpHandler handler = new ResourceHandler(new PathResource(base));68 HttpResponse res = handler.execute(new HttpRequest(GET, "/subdir/"));69 String text = Contents.string(res);70 assertThat(text).contains("1.txt");71 assertThat(text).contains("2.txt");72 }73 @Test74 public void canBeNestedWithinARoute() throws IOException {75 Path contents = base.resolve("cheese").resolve("cake.txt");76 Files.createDirectories(contents.getParent());77 Files.write(contents, "delicious".getBytes(UTF_8));78 HttpHandler handler = Route.prefix("/peas").to(Route.combine(new ResourceHandler(new PathResource(base))));79 // Check redirect works as expected80 HttpResponse res = handler.execute(new HttpRequest(GET, "/peas/cheese"));81 assertThat(res.getStatus()).isEqualTo(HTTP_MOVED_TEMP);82 assertThat(res.getHeader("Location")).isEqualTo("/peas/cheese/");83 // And now that content can be read84 res = handler.execute(new HttpRequest(GET, "/peas/cheese/cake.txt"));85 assertThat(res.getStatus()).isEqualTo(HTTP_OK);86 assertThat(Contents.string(res)).isEqualTo("delicious");87 }88 @Test89 public void shouldRedirectToIndexPageIfOneExists() throws IOException {90 Path index = base.resolve("index.html");91 Files.write(index, "Cheese".getBytes(UTF_8));92 ResourceHandler handler = new ResourceHandler(new PathResource(base));93 HttpResponse res = handler.execute(new HttpRequest(GET, "/"));94 assertThat(res.isSuccessful()).isTrue();95 String content = Contents.string(res);96 assertThat(content).isEqualTo("Cheese");97 }98}...

Full Screen

Full Screen

Source:OkMessages.java Github

copy

Full Screen

...28import java.io.InputStream;29import java.io.UncheckedIOException;30import java.net.URI;31import java.util.Optional;32import static org.openqa.selenium.remote.http.Contents.bytes;33import static org.openqa.selenium.remote.http.Contents.empty;34class OkMessages {35 private OkMessages() {36 // Utility classes.37 }38 static Request toOkHttpRequest(URI baseUrl, HttpRequest request) {39 Request.Builder builder = new Request.Builder();40 HttpUrl.Builder url;41 String rawUrl;42 if (request.getUri().startsWith("ws://")) {43 rawUrl = "http://" + request.getUri().substring("ws://".length());44 } else if (request.getUri().startsWith("wss://")) {45 rawUrl = "https://" + request.getUri().substring("wss://".length());46 } else if (request.getUri().startsWith("http://") || request.getUri().startsWith("https://")) {47 rawUrl = request.getUri();48 } else {49 rawUrl = baseUrl.toString().replaceAll("/$", "") + request.getUri();50 }51 HttpUrl parsed = HttpUrl.parse(rawUrl);52 if (parsed == null) {53 throw new UncheckedIOException(54 new IOException("Unable to parse URL: " + baseUrl.toString() + request.getUri()));55 }56 url = parsed.newBuilder();57 for (String name : request.getQueryParameterNames()) {58 for (String value : request.getQueryParameters(name)) {59 url.addQueryParameter(name, value);60 }61 }62 builder.url(url.build());63 for (String name : request.getHeaderNames()) {64 for (String value : request.getHeaders(name)) {65 builder.addHeader(name, value);66 }67 }68 switch (request.getMethod()) {69 case GET:70 builder.get();71 break;72 case POST:73 String rawType = Optional.ofNullable(request.getHeader("Content-Type"))74 .orElse("application/json; charset=utf-8");75 MediaType type = MediaType.parse(rawType);76 RequestBody body = RequestBody.create(bytes(request.getContent()), type);77 builder.post(body);78 break;79 case DELETE:80 builder.delete();81 }82 return builder.build();83 }84 static HttpResponse toSeleniumResponse(Response response) {85 HttpResponse toReturn = new HttpResponse();86 toReturn.setStatus(response.code());87 toReturn.setContent(response.body() == null ? empty() : Contents.memoize(() -> {88 InputStream stream = response.body().byteStream();89 return new InputStream() {90 @Override...

Full Screen

Full Screen

Source:NetworkInterceptTest.java Github

copy

Full Screen

...20 @Test21 public void replaceContent() throws IOException {22 ChromeDriver chromeDriver = new ChromeDriver();23 Path path = Paths.get("src/test/resources/kitten.jpeg");24 byte[] bytes = Files.readAllBytes(path);25 Route route = Route.matching(req -> req.toString().contains("jpg"))26 .to(() -> req -> {27 return new HttpResponse()28 .addHeader("Content-Type", MediaType.JPEG.toString())29 .setContent(Contents.bytes(bytes));30 });31 try (NetworkInterceptor interceptor = new NetworkInterceptor(chromeDriver, route)) {32 chromeDriver.get("https://www.saucedemo.com/inventory.html");33 }34 Files.write(Paths.get("kittens.png"), ((TakesScreenshot) chromeDriver).getScreenshotAs(BYTES));35 Dimension imageSize = chromeDriver.findElements(By.tagName("img")).get(0).getSize();36 double ratio = (double) imageSize.width / (double) imageSize.height;37 Assert.assertEquals(1.50, ratio, .05);38 chromeDriver.quit();39 }40}...

Full Screen

Full Screen

bytes

Using AI Code Generation

copy

Full Screen

1byte[] bytes = Contents.bytes(response.getContent());2String string = Contents.string(response.getContent());3byte[] bytes = Contents.bytes(response.getContent());4String string = Contents.string(response.getContent());5byte[] bytes = Contents.bytes(response.getContent());6String string = Contents.string(response.getContent());7byte[] bytes = Contents.bytes(response.getContent());8String string = Contents.string(response.getContent());9byte[] bytes = Contents.bytes(response.getContent());10String string = Contents.string(response.getContent());11byte[] bytes = Contents.bytes(response.getContent());12String string = Contents.string(response.getContent());13byte[] bytes = Contents.bytes(response.getContent());14String string = Contents.string(response.getContent());15byte[] bytes = Contents.bytes(response.getContent());16String string = Contents.string(response.getContent());17byte[] bytes = Contents.bytes(response.getContent());18String string = Contents.string(response.getContent());19byte[] bytes = Contents.bytes(response.getContent());20String string = Contents.string(response.getContent());21byte[] bytes = Contents.bytes(response.getContent

Full Screen

Full Screen

bytes

Using AI Code Generation

copy

Full Screen

1package com.test;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.remote.http.Contents;5public class ContentsTest {6 public static void main(String[] args) throws Exception {7 System.setProperty("webdriver.chrome.driver", "C:\\\\chromedriver.exe");8 WebDriver driver = new ChromeDriver();9 byte[] bytes = Contents.bytes(driver.getPageSource());10 System.out.println(new String(bytes));11 driver.quit();12 }13}14package com.test;15import org.openqa.selenium.WebDriver;16import org.openqa.selenium.chrome.ChromeDriver;17import org.openqa.selenium.remote.http.Contents;18public class ContentsTest {19 public static void main(String[] args) throws Exception {20 System.setProperty("webdriver.chrome.driver", "C:\\\\chromedriver.exe");21 WebDriver driver = new ChromeDriver();22 String str = Contents.string(driver.getPageSource());23 System.out.println(str);24 driver.quit();25 }26}

Full Screen

Full Screen

bytes

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.Contents;2String text = "Hello World";3import org.openqa.selenium.remote.http.Contents;4byte[] bytes = new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };5import org.openqa.selenium.remote.http.Contents;6String text = "Hello World";7import org.openqa.selenium.remote.http.Contents;8byte[] bytes = new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };

Full Screen

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful