Best Selenium code snippet using org.openqa.selenium.remote.http.Contents.asJson
Source:RemoteNewSessionQueue.java
...80 @Override81 public HttpResponse addToQueue(SessionRequest request) {82 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session");83 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);84 upstream.setContent(Contents.asJson(request));85 return client.with(addSecret).execute(upstream);86 }87 @Override88 public boolean retryAddToQueue(SessionRequest request) {89 Require.nonNull("Session request", request);90 HttpRequest upstream =91 new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/retry", request.getRequestId()));92 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);93 upstream.setContent(Contents.asJson(request));94 HttpResponse response = client.with(addSecret).execute(upstream);95 return Values.get(response, Boolean.class);96 }97 @Override98 public Optional<SessionRequest> remove(RequestId reqId) {99 HttpRequest upstream = new HttpRequest(POST, "/se/grid/newsessionqueue/session/" + reqId);100 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);101 HttpResponse response = client.with(addSecret).execute(upstream);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);125 Require.nonNull("Result", result);126 HttpRequest upstream;127 if (result.isRight()) {128 upstream = new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/success", reqId))129 .setContent(Contents.asJson(result.right()));130 } else {131 upstream = new HttpRequest(POST, String.format("/se/grid/newsessionqueue/session/%s/failure", reqId))132 .setContent(Contents.asJson(result.left().getRawMessage()));133 }134 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);135 client.with(addSecret).execute(upstream);136 }137 @Override138 public int clearQueue() {139 HttpRequest upstream = new HttpRequest(DELETE, "/se/grid/newsessionqueue/queue");140 HttpTracing.inject(tracer, tracer.getCurrentContext(), upstream);141 HttpResponse response = client.with(addSecret).execute(upstream);142 return Values.get(response, Integer.class);143 }144 @Override145 public List<SessionRequestCapability> getQueueContents() {146 HttpRequest upstream = new HttpRequest(GET, "/se/grid/newsessionqueue/queue");...
Source:CreateContainer.java
...32import java.util.logging.Logger;33import java.util.stream.Collectors;34import static org.openqa.selenium.json.Json.JSON_UTF_8;35import static org.openqa.selenium.json.Json.MAP_TYPE;36import static org.openqa.selenium.remote.http.Contents.asJson;37import static org.openqa.selenium.remote.http.HttpMethod.POST;38class CreateContainer {39 private static final Json JSON = new Json();40 private static final Logger LOG = Logger.getLogger(CreateContainer.class.getName());41 private final DockerProtocol protocol;42 private final HttpHandler client;43 public CreateContainer(DockerProtocol protocol, HttpHandler client) {44 this.protocol = Require.nonNull("Protocol", protocol);45 this.client = Require.nonNull("HTTP client", client);46 }47 public Container apply(ContainerInfo info) {48 HttpResponse res = DockerMessages.throwIfNecessary(49 client.execute(50 new HttpRequest(POST, "/v1.40/containers/create")51 .addHeader("Content-Type", JSON_UTF_8)52 .setContent(asJson(info))),53 "Unable to create container: ",54 info);55 try {56 Map<String, Object> rawContainer = JSON.toType(Contents.string(res), MAP_TYPE);57 if (!(rawContainer.get("Id") instanceof String)) {58 throw new DockerException("Unable to read container id: " + rawContainer);59 }60 ContainerId id = new ContainerId((String) rawContainer.get("Id"));61 if (rawContainer.get("Warnings") instanceof Collection) {62 String allWarnings = ((Collection<?>) rawContainer.get("Warnings")).stream()63 .map(String::valueOf)64 .collect(Collectors.joining("\n", " * ", ""));65 LOG.info(String.format("Warnings while creating %s from %s: %s", id, info, allWarnings));66 }...
Source:AddToSessionMap.java
...26import org.openqa.selenium.remote.tracing.Tracer;27import java.util.Objects;28import static org.openqa.selenium.remote.RemoteTags.CAPABILITIES;29import static org.openqa.selenium.remote.RemoteTags.SESSION_ID;30import static org.openqa.selenium.remote.http.Contents.asJson;31import static org.openqa.selenium.remote.http.Contents.string;32import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;33import static org.openqa.selenium.remote.tracing.Tags.HTTP_REQUEST;34class AddToSessionMap implements HttpHandler {35 private final Tracer tracer;36 private final Json json;37 private final SessionMap sessions;38 AddToSessionMap(Tracer tracer, Json json, SessionMap sessions) {39 this.tracer = Require.nonNull("Tracer", tracer);40 this.json = Require.nonNull("Json converter", json);41 this.sessions = Require.nonNull("Session map", sessions);42 }43 @Override44 public HttpResponse execute(HttpRequest req) {45 try (Span span = newSpanAsChildOf(tracer, req, "sessions.add_session")) {46 HTTP_REQUEST.accept(span, req);47 Session session = json.toType(string(req), Session.class);48 Objects.requireNonNull(session, "Session to add must be set");49 SESSION_ID.accept(span, session.getId());50 CAPABILITIES.accept(span, session.getCapabilities());51 span.setAttribute("session.uri", session.getUri().toString());52 sessions.add(session);53 return new HttpResponse().setContent(asJson(ImmutableMap.of("value", true)));54 }55 }56}...
Source:DrainNode.java
...21import org.openqa.selenium.remote.http.HttpRequest;22import org.openqa.selenium.remote.http.HttpResponse;23import java.io.UncheckedIOException;24import java.util.Objects;25import static org.openqa.selenium.remote.http.Contents.asJson;26public class DrainNode implements HttpHandler {27 private final Distributor distributor;28 private final NodeId nodeId;29 public DrainNode(Distributor distributor, NodeId nodeId) {30 this.distributor = Objects.requireNonNull(distributor);31 this.nodeId = Objects.requireNonNull(nodeId);32 }33 @Override34 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {35 HttpResponse response = new HttpResponse();36 boolean value = distributor.drain(nodeId);37 if (value) {38 response.setContent(39 asJson(ImmutableMap.of(40 "value", value,41 "message", "Node status was successfully set to draining.")));42 } else {43 response.setContent(44 asJson(ImmutableMap.of(45 "value", value,46 "message", "Unable to drain node. Please check the node exists by using /status. If so, try again.")));47 }48 return response;49 }50}...
Source:NewNodeSession.java
...23import org.openqa.selenium.remote.http.HttpRequest;24import org.openqa.selenium.remote.http.HttpResponse;25import java.io.UncheckedIOException;26import java.util.HashMap;27import static org.openqa.selenium.remote.http.Contents.asJson;28import static org.openqa.selenium.remote.http.Contents.string;29class NewNodeSession implements HttpHandler {30 private final Node node;31 private final Json json;32 NewNodeSession(Node node, Json json) {33 this.node = Require.nonNull("Node", node);34 this.json = Require.nonNull("Json converter", json);35 }36 @Override37 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {38 CreateSessionRequest incoming = json.toType(string(req), CreateSessionRequest.class);39 CreateSessionResponse sessionResponse = node.newSession(incoming).orElse(null);40 HashMap<String, Object> value = new HashMap<>();41 value.put("value", sessionResponse);42 return new HttpResponse().setContent(asJson(value));43 }44}
Source:StatusHandler.java
...20import org.openqa.selenium.internal.Require;21import org.openqa.selenium.remote.http.HttpHandler;22import org.openqa.selenium.remote.http.HttpRequest;23import org.openqa.selenium.remote.http.HttpResponse;24import static org.openqa.selenium.remote.http.Contents.asJson;25class StatusHandler implements HttpHandler {26 private final Distributor distributor;27 StatusHandler(Distributor distributor) {28 this.distributor = Require.nonNull("Distributor", distributor);29 }30 @Override31 public HttpResponse execute(HttpRequest req) {32 DistributorStatus status = distributor.getStatus();33 ImmutableMap<String, Object> report = ImmutableMap.of(34 "value", ImmutableMap.of(35 "ready", status.hasCapacity(),36 "message", status.hasCapacity() ? "Ready" : "No free slots available",37 "grid", status));38 return new HttpResponse().setContent(asJson(report));39 }40}...
Source:CreateSession.java
...20import org.openqa.selenium.internal.Require;21import org.openqa.selenium.remote.http.HttpHandler;22import org.openqa.selenium.remote.http.HttpRequest;23import org.openqa.selenium.remote.http.HttpResponse;24import static org.openqa.selenium.remote.http.Contents.asJson;25class CreateSession implements HttpHandler {26 private final Distributor distributor;27 CreateSession(Distributor distributor) {28 this.distributor = Require.nonNull("Distributor", distributor);29 }30 @Override31 public HttpResponse execute(HttpRequest req) {32 CreateSessionResponse sessionResponse = distributor.newSession(req);33 return new HttpResponse().setContent(asJson(ImmutableMap.of("value", sessionResponse)));34 }35}...
Source:GetDistributorStatus.java
...14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.distributor;18import static org.openqa.selenium.remote.http.Contents.asJson;19import com.google.common.collect.ImmutableMap;20import org.openqa.selenium.grid.data.DistributorStatus;21import org.openqa.selenium.internal.Require;22import org.openqa.selenium.remote.http.HttpHandler;23import org.openqa.selenium.remote.http.HttpRequest;24import org.openqa.selenium.remote.http.HttpResponse;25class GetDistributorStatus implements HttpHandler {26 private final Distributor distributor;27 GetDistributorStatus(Distributor distributor) {28 this.distributor = Require.nonNull("Distributor", distributor);29 }30 @Override31 public HttpResponse execute(HttpRequest req) {32 DistributorStatus status = distributor.getStatus();33 return new HttpResponse().setContent(asJson(ImmutableMap.of("value", status)));34 }35}...
asJson
Using AI Code Generation
1package org.openqa.selenium.remote.http;2import java.io.IOException;3import java.io.InputStream;4import java.nio.charset.StandardCharsets;5import java.util.List;6import java.util.Map;7import java.util.stream.Collectors;8import org.openqa.selenium.json.Json;9import org.openqa.selenium.json.JsonInput;10public class Contents {11 public static Contents binary(byte[] data) {12 return new Contents(data, "application/octet-stream");13 }14 public static Contents json(Object data) {15 return new Contents(new Json().toJson(data), "application/json");16 }17 public static Contents text(String data) {18 return new Contents(data.getBytes(StandardCharsets.UTF_8), "text/plain");19 }20 private final byte[] data;21 private final String contentType;22 private Contents(byte[] data, String contentType) {23 this.data = data;24 this.contentType = contentType;25 }26 public String getContentType() {27 return contentType;28 }29 public byte[] asBytes() {30 return data;31 }32 public String asString() {33 return new String(data, StandardCharsets.UTF_8);34 }35 public <T> T as(Class<T> type) {36 if (type.isAssignableFrom(byte[].class)) {37 return type.cast(data);38 }39 if (type.isAssignableFrom(String.class)) {40 return type.cast(asString());41 }42 if (type.isAssignableFrom(Map.class)) {43 try (JsonInput input = new Json().newInput(asString())) {44 return type.cast(input.read(Map.class));45 } catch (IOException e) {46 throw new IllegalStateException(e);47 }48 }49 if (type.isAssignableFrom(List.class)) {50 try (JsonInput input = new Json().newInput(asString())) {51 return type.cast(input.read(List.class));52 } catch (IOException e) {53 throw new IllegalStateException(e);54 }55 }56 throw new IllegalArgumentException("Unable to convert to " + type);57 }58 public <T> T asJson(Class<T> type) {59 try (JsonInput input = new Json().newInput(asString())) {60 return type.cast(input.read(type));61 } catch (IOException e) {62 throw new IllegalStateException(e);63 }64 }65 public InputStream asStream() {66 return new InputStream() {67 private int index = 0;68 public int read() {69 if (index >= data.length) {70 return -1;71 }
asJson
Using AI Code Generation
1String json = "{'name':'test'}";2Contents contents = new Contents(json.getBytes(StandardCharsets.UTF_8), "application/json");3String json2 = new String(contents.asBytes(), StandardCharsets.UTF_8);4System.out.println(json2);5String json = "{'name':'test'}";6HttpResponse response = new HttpResponse();7response.setContent(new StringContent(json));8String json2 = new String(response.getContent().asBytes(), StandardCharsets.UTF_8);9System.out.println(json2);10String json = "{'name':'test'}";11HttpResponse response = new HttpResponse();12response.setContent(new StringContent(json));13String json2 = new String(response.getContent().asBytes(), StandardCharsets.UTF_8);14System.out.println(json2);
asJson
Using AI Code Generation
1Contents contents = new Contents(response);2String responseString = contents.asString();3System.out.println(responseString);4JSONObject responseJson = contents.asJson();5System.out.println(responseJson);6String responseString = new String(response.getContent(), StandardCharsets.UTF_8);7System.out.println(responseString);8JSONObject responseJson = new JSONObject(responseString);9System.out.println(responseJson);10String responseString = new String(response.getContent(), StandardCharsets.UTF_8);11System.out.println(responseString);12JSONObject responseJson = (JSONObject) JSONValue.parse(responseString);13System.out.println(responseJson);14String responseString = new String(response.getContent(), StandardCharsets.UTF_8);15System.out.println(responseString);16JSONArray responseJson = new JSONArray(responseString);17System.out.println(responseJson);18String responseString = new String(response.getContent(), StandardCharsets.UTF_8);19System.out.println(responseString);20JSONArray responseJson = (JSONArray) JSONValue.parse(responseString);21System.out.println(responseJson);22String responseString = new String(response.getContent(), StandardCharsets.UTF_8);23System.out.println(responseString);24Document responseXml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(responseString)));25System.out.println(responseXml);26String responseString = new String(response.getContent(), StandardCharsets.UTF_8);27System.out.println(responseString);28Document responseHtml = Jsoup.parse(responseString);29System.out.println(responseHtml);30String responseString = new String(response.getContent(), StandardCharsets.UTF_8);31System.out.println(responseString);32byte[] responseBytes = response.getContent();33System.out.println(responseBytes);34InputStream responseInputStream = response.getContentAsStream();35System.out.println(responseInputStream);36File responseFile = response.save(Paths.get("C:\\Users\\username\\Downloads", "responseFile.json").toFile());37System.out.println(responseFile);38Object responseObject = response.getContent();39System.out.println(response
asJson
Using AI Code Generation
1import org.openqa.selenium.remote.http.Contents2import org.openqa.selenium.remote.http.HttpResponse3def response = context.get("response")4String responseBody = Contents.asString(response.getBody())5def json = Contents.asJson(responseBody)6def newBody = Contents.json(json)7response.setBody(newBody)8import org.openqa.selenium.remote.http.Contents9import org.openqa.selenium.remote.http.HttpResponse10def response = context.get("response")11def responseBody = response.getBody()12def json = Contents.asJson(responseBody)13def newBody = Contents.json(json)14response.setBody(newBody)15import org.openqa.selenium.remote.http.Contents16import org.openqa.selenium.remote.http.HttpResponse17def response = context.get("response")18String responseBody = Contents.asString(response.getBody())19def json = Contents.asJson(responseBody)20def newBody = Contents.json(json)21response.setBody(newBody)22import org.openqa.selenium.remote.http.Contents23import org.openqa.selenium.remote.http.HttpResponse24def response = context.get("response")25def responseBody = response.getBody()26def json = Contents.asJson(responseBody)27def newBody = Contents.json(json)28response.setBody(newBody)
asJson
Using AI Code Generation
1import org.openqa.selenium.remote.http.Contents2def json = Contents.json(response).as()3import org.openqa.selenium.remote.http.Contents4def text = Contents.text(response).as()5import org.openqa.selenium.remote.http.Contents6def bytes = Contents.bytes(response).as()
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!!