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

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

Source:RemoteNewSessionQueue.java Github

copy

Full Screen

...102 if (response.isSuccessful()) {103 // TODO: This should work cleanly with just a TypeToken of <Optional<SessionRequest>>104 String rawValue = Contents.string(response);105 if (rawValue == null || rawValue.trim().isEmpty()) {106 return Optional.empty();107 }108 return Optional.of(JSON.toType(rawValue, SessionRequest.class));109 }110 return Optional.empty();111 }112 @Override113 public Optional<SessionRequest> getNextAvailable(Set<Capabilities> stereotypes) {114 Require.nonNull("Stereotypes", stereotypes);115 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session/next")116 .setContent(Contents.asJson(stereotypes));117 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);118 HttpResponse response = client.with(addSecret).execute(upstream);119 SessionRequest value = Values.get(response, SessionRequest.class);120 return Optional.ofNullable(value);121 }122 @Override123 public void complete(RequestId reqId, Either<SessionNotCreatedException, CreateSessionResponse> result) {124 Require.nonNull("Request ID", reqId);...

Full Screen

Full Screen

Source:OkMessages.java Github

copy

Full Screen

...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 @Override91 public int read() throws IOException {92 return stream.read();93 }94 @Override95 public void close() throws IOException {96 response.close();97 super.close();98 }99 };100 }));101 response.headers().names().forEach(...

Full Screen

Full Screen

Source:BaseServerTest.java Github

copy

Full Screen

...31import org.openqa.selenium.remote.http.HttpResponse;32import java.io.IOException;33import java.net.URL;34public class BaseServerTest {35 private BaseServerOptions emptyOptions = new BaseServerOptions(new MapConfig(ImmutableMap.of()));36 @Test37 public void baseServerStartsAndDoesNothing() throws IOException {38 Server<?> server = new BaseServer<>(emptyOptions).start();39 URL url = server.getUrl();40 HttpClient client = HttpClient.Factory.createDefault().createClient(url);41 HttpResponse response = client.execute(new HttpRequest(GET, "/status"));42 // Although we don't expect the server to be ready, we do expect the request to succeed.43 assertEquals(HTTP_OK, response.getStatus());44 // And we expect the content to be UTF-8 encoded JSON.45 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(response.getHeader("Content-Type")));46 }47 @Test48 public void shouldAllowAHandlerToBeRegistered() throws IOException {49 Server<?> server = new BaseServer<>(emptyOptions);50 server.addRoute(get("/cheese").using((req, res) -> res.setContent(utf8String("cheddar"))));51 server.start();52 URL url = server.getUrl();53 HttpClient client = HttpClient.Factory.createDefault().createClient(url);54 HttpResponse response = client.execute(new HttpRequest(GET, "/cheese"));55 assertEquals("cheddar", string(response));56 }57 @Test58 public void ifTwoHandlersRespondToTheSameRequestTheLastOneAddedWillBeUsed() throws IOException {59 Server<?> server = new BaseServer<>(emptyOptions);60 server.addRoute(get("/status").using((req, res) -> res.setContent(utf8String("one"))));61 server.addRoute(get("/status").using((req, res) -> res.setContent(utf8String("two"))));62 server.start();63 URL url = server.getUrl();64 HttpClient client = HttpClient.Factory.createDefault().createClient(url);65 HttpResponse response = client.execute(new HttpRequest(GET, "/status"));66 assertEquals("two", string(response));67 }68 @Test69 public void addHandlersOnceServerIsStartedIsAnError() {70 Server<BaseServer> server = new BaseServer<>(emptyOptions);71 server.start();72 Assertions.assertThatExceptionOfType(IllegalStateException.class).isThrownBy(73 () -> server.addRoute(get("/foo").using((req, res) -> {})));74 }75}...

Full Screen

Full Screen

Source:ReactorMessages.java Github

copy

Full Screen

...15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.remote.http.reactor;18import static org.asynchttpclient.Dsl.request;19import static org.openqa.selenium.remote.http.Contents.empty;20import static org.openqa.selenium.remote.http.Contents.memoize;21import com.google.common.base.Strings;22import org.asynchttpclient.Dsl;23import org.asynchttpclient.Request;24import org.asynchttpclient.RequestBuilder;25import org.asynchttpclient.Response;26import org.openqa.selenium.remote.http.AddSeleniumUserAgent;27import org.openqa.selenium.remote.http.HttpMethod;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import java.net.URI;31public class ReactorMessages {32 private ReactorMessages() {33 // Utility classes.34 }35 protected static Request toReactorRequest(URI baseUrl, HttpRequest request) {36 String rawUrl;37 String uri = request.getUri();38 if (uri.startsWith("ws://")) {39 rawUrl = "http://" + uri.substring("ws://".length());40 } else if (uri.startsWith("wss://")) {41 rawUrl = "https://" + uri.substring("wss://".length());42 } else if (uri.startsWith("http://") || uri.startsWith("https://")) {43 rawUrl = uri;44 } else {45 rawUrl = baseUrl.toString().replaceAll("/$", "") + uri;46 }47 RequestBuilder builder = request(request.getMethod().toString(), rawUrl);48 for (String name : request.getQueryParameterNames()) {49 for (String value : request.getQueryParameters(name)) {50 builder.addQueryParam(name, value);51 }52 }53 for (String name : request.getHeaderNames()) {54 for (String value : request.getHeaders(name)) {55 builder.addHeader(name, value);56 }57 }58 if (request.getHeader("User-Agent") == null) {59 builder.addHeader("User-Agent", AddSeleniumUserAgent.USER_AGENT);60 }61 String info = baseUrl.getUserInfo();62 if (!Strings.isNullOrEmpty(info)) {63 String[] parts = info.split(":", 2);64 String user = parts[0];65 String pass = parts.length > 1 ? parts[1] : null;66 builder.setRealm(Dsl.basicAuthRealm(user, pass).setUsePreemptiveAuth(true).build());67 }68 if (request.getMethod().equals(HttpMethod.POST)) {69 builder.setBody(request.getContent().get());70 }71 return builder.build();72 }73 public static HttpResponse toSeleniumResponse(Response response) {74 HttpResponse toReturn = new HttpResponse();75 toReturn.setStatus(response.getStatusCode());76 toReturn.setContent(! response.hasResponseBody()77 ? empty()78 : memoize(response::getResponseBodyAsStream));79 response.getHeaders().names().forEach(80 name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));81 return toReturn;82 }83}...

Full Screen

Full Screen

Source:NettyMessages.java Github

copy

Full Screen

...14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.remote.http.netty;18import static org.openqa.selenium.remote.http.Contents.empty;19import org.asynchttpclient.Request;20import org.asynchttpclient.RequestBuilder;21import org.asynchttpclient.Response;22import org.openqa.selenium.remote.http.Contents;23import org.openqa.selenium.remote.http.HttpMethod;24import org.openqa.selenium.remote.http.HttpRequest;25import org.openqa.selenium.remote.http.HttpResponse;26import java.net.URI;27import static org.asynchttpclient.Dsl.request;28class NettyMessages {29 private NettyMessages() {30 // Utility classes.31 }32 protected static Request toNettyRequest(URI baseUrl, HttpRequest request) {33 String rawUrl;34 if (request.getUri().startsWith("ws://")) {35 rawUrl = "http://" + request.getUri().substring("ws://".length());36 } else if (request.getUri().startsWith("wss://")) {37 rawUrl = "https://" + request.getUri().substring("wss://".length());38 } else if (request.getUri().startsWith("http://") || request.getUri().startsWith("https://")) {39 rawUrl = request.getUri();40 } else {41 rawUrl = baseUrl.toString().replaceAll("/$", "") + request.getUri();42 }43 RequestBuilder builder = request(request.getMethod().toString(), rawUrl);44 for (String name : request.getQueryParameterNames()) {45 for (String value : request.getQueryParameters(name)) {46 builder.addQueryParam(name, value);47 }48 }49 for (String name : request.getHeaderNames()) {50 for (String value : request.getHeaders(name)) {51 builder.addHeader(name, value);52 }53 }54 if (request.getMethod().equals(HttpMethod.POST)) {55 builder.setBody(request.getContent().get());56 }57 return builder.build();58 }59 public static HttpResponse toSeleniumResponse(Response response) {60 HttpResponse toReturn = new HttpResponse();61 toReturn.setStatus(response.getStatusCode());62 toReturn.setContent(! response.hasResponseBody()63 ? empty()64 : Contents.memoize(response::getResponseBodyAsStream));65 response.getHeaders().names().forEach(66 name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));67 return toReturn;68 }69}...

Full Screen

Full Screen

Source:VersionCommand.java Github

copy

Full Screen

...42 public Optional<DockerProtocol> getDockerProtocol() {43 try {44 HttpResponse res = handler.execute(new HttpRequest(GET, "/version"));45 if (!res.isSuccessful()) {46 return Optional.empty();47 }48 Map<String, Object> raw = JSON.toType(Contents.string(res), MAP_TYPE);49 Version maxVersion = new Version((String) raw.get("ApiVersion"));50 Version minVersion = new Version((String) raw.get("MinAPIVersion"));51 return SUPPORTED_VERSIONS.entrySet().stream()52 .filter(entry -> {53 Version version = entry.getKey();54 if (version.equalTo(maxVersion) || version.equalTo(minVersion)) {55 return true;56 }57 return version.isLessThan(maxVersion) && version.isGreaterThan(minVersion);58 })59 .map(Map.Entry::getValue)60 .map(func -> func.apply(handler))61 .findFirst();62 } catch (ClassCastException | JsonException | NullPointerException | UncheckedIOException e) {63 return Optional.empty();64 }65 }66}...

Full Screen

Full Screen

Source:ChromiumDevToolsLocator.java Github

copy

Full Screen

...37 Capabilities caps,38 String capabilityKey) {39 Object raw = caps.getCapability(capabilityKey);40 if (!(raw instanceof Map)) {41 return Optional.empty();42 }43 raw = ((Map<?, ?>) raw).get("debuggerAddress");44 if (!(raw instanceof String)) {45 return Optional.empty();46 }47 int index = ((String) raw).lastIndexOf(":");48 if (index == -1 || index == ((String) raw).length() - 1) {49 return Optional.empty();50 }51 try {52 URL url = new URL(String.format("http://%s", raw));53 HttpClient client = clientFactory.createClient(url);54 HttpResponse res = client.execute(new HttpRequest(GET, "/json/version"));55 if (res.getStatus() != HTTP_OK) {56 return Optional.empty();57 }58 Map<String, Object> versionData = JSON.toType(string(res), MAP_TYPE);59 raw = versionData.get("webSocketDebuggerUrl");60 if (!(raw instanceof String)) {61 return Optional.empty();62 }63 String debuggerUrl = (String) raw;64 return Optional.of(new Connection(client, debuggerUrl));65 } catch (IOException | JsonException e) {66 return Optional.empty();67 }68 }69}...

Full Screen

Full Screen

Source:ContainerExists.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.docker.v1_40;18import com.google.common.collect.ImmutableMap;19import com.google.common.collect.ImmutableSet;20import org.openqa.selenium.docker.ContainerId;21import org.openqa.selenium.internal.Require;22import org.openqa.selenium.json.Json;23import org.openqa.selenium.remote.http.Contents;24import org.openqa.selenium.remote.http.HttpHandler;25import org.openqa.selenium.remote.http.HttpRequest;26import org.openqa.selenium.remote.http.HttpResponse;27import java.util.List;28import java.util.Map;29import static org.openqa.selenium.docker.v1_40.DockerMessages.throwIfNecessary;30import static org.openqa.selenium.json.Json.JSON_UTF_8;31import static org.openqa.selenium.remote.http.HttpMethod.GET;32class ContainerExists {33 private static final Json JSON = new Json();34 private final HttpHandler client;35 public ContainerExists(HttpHandler client) {36 this.client = Require.nonNull("HTTP client", client);37 }38 boolean apply(ContainerId id) {39 Require.nonNull("Container id", id);40 Map<String, Object> filters = ImmutableMap.of("id", ImmutableSet.of(id));41 HttpResponse res = throwIfNecessary(42 client.execute(43 new HttpRequest(GET, "/v1.40/containers/json")44 .addHeader("Content-Length", "0")45 .addHeader("Content-Type", JSON_UTF_8)46 .addQueryParameter("filters", JSON.toJson(filters))47 ),48 "Unable to list container %s",49 id);50 List<?> allContainers = JSON.toType(Contents.string(res), List.class);51 return !allContainers.isEmpty();52 }53}...

Full Screen

Full Screen

empty

Using AI Code Generation

copy

Full Screen

1Contents contents = new StringContents("Hello World");2Contents emptyContents = new StringContents("");3Contents contents = new StringContents("Hello World");4Contents emptyContents = new StringContents("");5Contents contents = new StringContents("Hello World");6Contents emptyContents = new StringContents("");7Contents contents = new StringContents("Hello World");8Contents emptyContents = new StringContents("");9Contents contents = new StringContents("Hello World");10Contents emptyContents = new StringContents("");11Contents contents = new StringContents("Hello World");12Contents emptyContents = new StringContents("");13Contents contents = new StringContents("Hello World");14Contents emptyContents = new StringContents("");15Contents contents = new StringContents("Hello World");16Contents emptyContents = new StringContents("");17Contents contents = new StringContents("Hello World");18Contents emptyContents = new StringContents("");19Contents contents = new StringContents("Hello World");20Contents emptyContents = new StringContents("");21Contents contents = new StringContents("Hello World");

Full Screen

Full Screen

empty

Using AI Code Generation

copy

Full Screen

1Contents contents = new Contents("text/plain", "Hello World".getBytes());2if (contents.isEmpty()) {3 System.out.println("Contents is empty");4}5else {6 System.out.println("Contents is not empty");7}

Full Screen

Full Screen

empty

Using AI Code Generation

copy

Full Screen

1public class EmptyContentTest {2 public static void main(String[] args) {3 Contents contents = new Contents(new byte[0]);4 System.out.println(contents.isEmpty());5 }6}7public class Contents {8 private final byte[] bytes;9 public Contents(byte[] bytes) {10 this.bytes = bytes;11 }12 public boolean isEmpty() {13 return bytes.length == 0;14 }15 public byte[] asBytes() {16 return bytes;17 }18}

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