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

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

Source:RemoteNode.java Github

copy

Full Screen

...15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.grid.node.remote;18import static org.openqa.selenium.net.Urls.fromUri;19import static org.openqa.selenium.remote.http.Contents.reader;20import static org.openqa.selenium.remote.http.Contents.string;21import static org.openqa.selenium.remote.http.Contents.utf8String;22import static org.openqa.selenium.remote.http.HttpMethod.DELETE;23import static org.openqa.selenium.remote.http.HttpMethod.GET;24import static org.openqa.selenium.remote.http.HttpMethod.POST;25import com.google.common.collect.ImmutableMap;26import com.google.common.collect.ImmutableSet;27import org.openqa.selenium.Capabilities;28import org.openqa.selenium.NoSuchSessionException;29import org.openqa.selenium.grid.component.HealthCheck;30import org.openqa.selenium.grid.data.CreateSessionRequest;31import org.openqa.selenium.grid.data.CreateSessionResponse;32import org.openqa.selenium.grid.data.NodeStatus;33import org.openqa.selenium.grid.data.Session;34import org.openqa.selenium.grid.node.Node;35import org.openqa.selenium.grid.web.Values;36import org.openqa.selenium.json.Json;37import org.openqa.selenium.json.JsonInput;38import org.openqa.selenium.remote.SessionId;39import org.openqa.selenium.remote.http.HttpClient;40import org.openqa.selenium.remote.http.HttpRequest;41import org.openqa.selenium.remote.http.HttpResponse;42import org.openqa.selenium.remote.tracing.DistributedTracer;43import org.openqa.selenium.remote.tracing.Span;44import java.io.IOException;45import java.io.Reader;46import java.io.UncheckedIOException;47import java.net.URI;48import java.util.Collection;49import java.util.Map;50import java.util.Objects;51import java.util.Optional;52import java.util.Set;53import java.util.UUID;54import java.util.function.Function;55public class RemoteNode extends Node {56 public static final Json JSON = new Json();57 private final Function<HttpRequest, HttpResponse> client;58 private final URI externalUri;59 private final Set<Capabilities> capabilities;60 private final HealthCheck healthCheck;61 public RemoteNode(62 DistributedTracer tracer,63 HttpClient.Factory clientFactory,64 UUID id,65 URI externalUri,66 Collection<Capabilities> capabilities) {67 super(tracer, id, externalUri);68 this.externalUri = Objects.requireNonNull(externalUri);69 this.capabilities = ImmutableSet.copyOf(capabilities);70 HttpClient client = Objects.requireNonNull(clientFactory).createClient(fromUri(externalUri));71 this.client = req -> {72 try {73 return client.execute(req);74 } catch (IOException e) {75 throw new UncheckedIOException(e);76 }77 };78 this.healthCheck = new RemoteCheck();79 }80 @Override81 public boolean isSupporting(Capabilities capabilities) {82 return this.capabilities.stream()83 .anyMatch(caps -> caps.getCapabilityNames().stream()84 .allMatch(name -> Objects.equals(85 caps.getCapability(name),86 capabilities.getCapability(name))));87 }88 @Override89 public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {90 Objects.requireNonNull(sessionRequest, "Capabilities for session are not set");91 HttpRequest req = new HttpRequest(POST, "/se/grid/node/session");92 req.setContent(utf8String(JSON.toJson(sessionRequest)));93 HttpResponse res = client.apply(req);94 return Optional.ofNullable(Values.get(res, CreateSessionResponse.class));95 }96 @Override97 protected boolean isSessionOwner(SessionId id) {98 Objects.requireNonNull(id, "Session ID has not been set");99 HttpRequest req = new HttpRequest(GET, "/se/grid/node/owner/" + id);100 HttpResponse res = client.apply(req);101 return Values.get(res, Boolean.class) == Boolean.TRUE;102 }103 @Override104 public Session getSession(SessionId id) throws NoSuchSessionException {105 Objects.requireNonNull(id, "Session ID has not been set");106 HttpRequest req = new HttpRequest(GET, "/se/grid/node/session/" + id);107 HttpResponse res = client.apply(req);108 return Values.get(res, Session.class);109 }110 @Override111 public void executeWebDriverCommand(HttpRequest req, HttpResponse resp) {112 HttpResponse fromUpstream = client.apply(req);113 resp.setStatus(fromUpstream.getStatus());114 for (String name : fromUpstream.getHeaderNames()) {115 for (String value : fromUpstream.getHeaders(name)) {116 resp.addHeader(name, value);117 }118 }119 resp.setContent(fromUpstream.getContent());120 }121 @Override122 public void stop(SessionId id) throws NoSuchSessionException {123 Objects.requireNonNull(id, "Session ID has not been set");124 HttpRequest req = new HttpRequest(DELETE, "/se/grid/node/session/" + id);125 HttpResponse res = client.apply(req);126 Values.get(res, Void.class);127 }128 @Override129 public NodeStatus getStatus() {130 HttpRequest req = new HttpRequest(GET, "/status");131 HttpResponse res = client.apply(req);132 try (Reader reader = reader(res);133 JsonInput in = JSON.newInput(reader)) {134 in.beginObject();135 // Skip everything until we find "value"136 while (in.hasNext()) {137 if ("value".equals(in.nextName())) {138 in.beginObject();139 while (in.hasNext()) {140 if ("node".equals(in.nextName())) {141 return in.read(NodeStatus.class);142 } else {143 in.skipValue();144 }145 }146 in.endObject();147 } else {...

Full Screen

Full Screen

Source:NewSessionQueuer.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.grid.sessionqueue;18import static org.openqa.selenium.remote.http.Contents.reader;19import static org.openqa.selenium.remote.http.Route.combine;20import static org.openqa.selenium.remote.http.Route.delete;21import static org.openqa.selenium.remote.http.Route.post;22import static org.openqa.selenium.remote.tracing.Tags.EXCEPTION;23import org.openqa.selenium.Capabilities;24import org.openqa.selenium.SessionNotCreatedException;25import org.openqa.selenium.grid.data.RequestId;26import org.openqa.selenium.internal.Require;27import org.openqa.selenium.remote.NewSessionPayload;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import org.openqa.selenium.remote.http.Routable;31import org.openqa.selenium.remote.http.Route;32import org.openqa.selenium.remote.tracing.AttributeKey;33import org.openqa.selenium.remote.tracing.EventAttribute;34import org.openqa.selenium.remote.tracing.EventAttributeValue;35import org.openqa.selenium.remote.tracing.Span;36import org.openqa.selenium.remote.tracing.Tracer;37import org.openqa.selenium.status.HasReadyState;38import java.io.IOException;39import java.io.Reader;40import java.util.HashMap;41import java.util.Iterator;42import java.util.Map;43import java.util.Objects;44import java.util.Optional;45import java.util.UUID;46import java.util.logging.Logger;47public abstract class NewSessionQueuer implements HasReadyState, Routable {48 private static final Logger LOG = Logger.getLogger(NewSessionQueuer.class.getName());49 private final Route routes;50 protected final Tracer tracer;51 protected NewSessionQueuer(Tracer tracer) {52 this.tracer = Require.nonNull("Tracer", tracer);53 routes = combine(54 post("/session")55 .to(() -> this::addToQueue),56 post("/se/grid/newsessionqueuer/session")57 .to(() -> new AddToSessionQueue(tracer, this)),58 post("/se/grid/newsessionqueuer/session/retry/{requestId}")59 .to(params -> new AddBackToSessionQueue(tracer, this,60 new RequestId(61 UUID.fromString(params.get("requestId"))))),62 Route.get("/se/grid/newsessionqueuer/session")63 .to(() -> new RemoveFromSessionQueue(tracer, this)),64 delete("/se/grid/newsessionqueuer/queue")65 .to(() -> new ClearSessionQueue(tracer, this)));66 }67 public void validateSessionRequest(HttpRequest request) {68 try (Span span = tracer.getCurrentContext().createSpan("newsession_queuer.validate")) {69 Map<String, EventAttributeValue> attributeMap = new HashMap<>();70 try (71 Reader reader = reader(request);72 NewSessionPayload payload = NewSessionPayload.create(reader)) {73 Objects.requireNonNull(payload, "Requests to process must be set.");74 attributeMap.put("request.payload", EventAttribute.setValue(payload.toString()));75 Iterator<Capabilities> iterator = payload.stream().iterator();76 if (!iterator.hasNext()) {77 SessionNotCreatedException78 exception =79 new SessionNotCreatedException("No capabilities found");80 EXCEPTION.accept(attributeMap, exception);81 attributeMap.put(AttributeKey.EXCEPTION_MESSAGE.getKey(),82 EventAttribute.setValue(exception.getMessage()));83 span.addEvent(AttributeKey.EXCEPTION_EVENT.getKey(), attributeMap);84 throw exception;85 }86 } catch (IOException e) {...

Full Screen

Full Screen

Source:HttpMessage.java Github

copy

Full Screen

...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 }119 /**120 * @deprecated Use {@link Contents#string(HttpMessage)} instead.121 */122 @Deprecated123 public String getContentString() {124 return string(this);125 }126 /**127 * @deprecated Use {@link Contents#reader(HttpMessage)} instead.128 */129 @Deprecated130 public Reader getContentReader() {131 return reader(this);132 }133 /**134 * @deprecated Use {@link #getContent()} and call {@link Supplier#get()}.135 */136 @Deprecated137 public InputStream getContentStream() {138 return getContent().get();139 }140 /**141 * Get the underlying content stream, bypassing the caching mechanisms that allow it to be read142 * again.143 * @deprecated No direct replacement. Use {@link #getContent()} and call {@link Supplier#get()}.144 */145 public InputStream consumeContentStream() {...

Full Screen

Full Screen

Source:BeginSession.java Github

copy

Full Screen

...37import static com.google.common.net.MediaType.JSON_UTF_8;38import static java.net.HttpURLConnection.HTTP_OK;39import static java.nio.charset.StandardCharsets.UTF_8;40import static org.openqa.selenium.remote.http.Contents.bytes;41import static org.openqa.selenium.remote.http.Contents.reader;42public class BeginSession implements HttpHandler {43 private final NewSessionPipeline pipeline;44 private final ActiveSessions allSessions;45 private final Json json;46 public BeginSession(NewSessionPipeline pipeline, ActiveSessions allSessions, Json json) {47 this.pipeline = pipeline;48 this.allSessions = allSessions;49 this.json = json;50 }51 @Override52 public HttpResponse execute(HttpRequest req) throws UncheckedIOException {53 ActiveSession session;54 try (Reader reader = reader(req);55 NewSessionPayload payload = NewSessionPayload.create(reader)) {56 session = pipeline.createNewSession(payload);57 allSessions.put(session);58 } catch (IOException e) {59 throw new UncheckedIOException(e);60 }61 // Force capture of server-side logs since we don't have easy access to the request from the62 // local end.63 LoggingPreferences loggingPrefs = new LoggingPreferences();64 loggingPrefs.enable(LogType.SERVER, Level.INFO);65 Object raw = session.getCapabilities().get(CapabilityType.LOGGING_PREFS);66 if (raw instanceof LoggingPreferences) {67 loggingPrefs.addPreferences((LoggingPreferences) raw);68 }69 LoggingManager.perSessionLogHandler().configureLogging(loggingPrefs);...

Full Screen

Full Screen

Source:Values.java Github

copy

Full Screen

...16// under the License.17package org.openqa.selenium.grid.web;18import static org.openqa.selenium.json.Json.MAP_TYPE;19import static org.openqa.selenium.json.JsonType.END;20import static org.openqa.selenium.remote.http.Contents.reader;21import static org.openqa.selenium.remote.http.Contents.string;22import org.openqa.selenium.json.Json;23import org.openqa.selenium.json.JsonInput;24import org.openqa.selenium.remote.http.HttpResponse;25import java.io.IOException;26import java.io.Reader;27import java.io.UncheckedIOException;28import java.lang.reflect.Type;29public class Values {30 private static final Json JSON = new Json();31 private static final ErrorCodec ERRORS = ErrorCodec.createDefault();32 public static <T> T get(HttpResponse response, Type typeOfT) {33 try (Reader reader = reader(response);34 JsonInput input = JSON.newInput(reader)) {35 // Alright then. We might be dealing with the object we expected, or we might have an36 // error. We shall assume that a non-200 http status code indicates that something is37 // wrong.38 if (response.getStatus() != 200) {39 throw ERRORS.decode(JSON.toType(string(response), MAP_TYPE));40 }41 if (Void.class.equals(typeOfT) && input.peek() == END) {42 return null;43 }44 input.beginObject();45 while (input.hasNext()) {46 if ("value".equals(input.nextName())) {47 return input.read(typeOfT);48 } else {...

Full Screen

Full Screen

reader

Using AI Code Generation

copy

Full Screen

1package com.test;2import java.io.IOException;3import java.nio.charset.Charset;4import java.nio.charset.StandardCharsets;5import java.util.Arrays;6import java.util.List;7import java.util.stream.Collectors;8import org.openqa.selenium.remote.http.Contents;9import org.openqa.selenium.remote.http.HttpRequest;10import org.openqa.selenium.remote.http.HttpResponse;11public class ContentsReader {12 public static void main(String[] args) throws IOException {13 String body = "Hello World";14 Charset charset = StandardCharsets.UTF_8;15 byte[] bytes = body.getBytes(charset);16 HttpRequest request = new HttpRequest("POST", "/session");17 request.setContent(Contents.bytes(bytes));18 System.out.println("Body of the request is: " + Contents.string(request));19 HttpResponse response = new HttpResponse();20 response.setContent(Contents.bytes(bytes));21 System.out.println("Body of the response is: " + Contents.string(response));22 }23}

Full Screen

Full Screen

reader

Using AI Code Generation

copy

Full Screen

1Contents contents = response.getBody();2Reader reader = contents.reader();3BufferedReader bufferedReader = new BufferedReader(reader);4String line = bufferedReader.readLine();5while (line != null) {6 System.out.println(line);7 line = bufferedReader.readLine();8}9Contents contents = response.getBody();10String body = contents.string();11System.out.println(body);12Contents contents = response.getBody();13String body = contents.text();14System.out.println(body);15Contents contents = response.getBody();16byte[] body = contents.bytes();17System.out.println(body);18Contents contents = response.getBody();19String body = contents.as(String.class);20System.out.println(body);21Contents contents = response.getBody();22byte[] body = contents.as(byte[].class);23System.out.println(body);24Contents contents = response.getBody();25InputStream body = contents.as(InputStream.class);26System.out.println(body);27Contents contents = response.getBody();28Reader body = contents.as(Reader.class);29System.out.println(body);30Contents contents = response.getBody();31BufferedReader body = contents.as(BufferedReader.class);32System.out.println(body);33Contents contents = response.getBody();34String body = contents.as(String.class);35System.out.println(body);36Contents contents = response.getBody();37byte[] body = contents.as(byte[].class);38System.out.println(body);

Full Screen

Full Screen

reader

Using AI Code Generation

copy

Full Screen

1Contents contents = response.getBody();2String body = contents.reader().readLine();3Contents contents = response.getBody();4String body = contents.reader().readLine();5Contents contents = response.getBody();6String body = contents.reader().readLine();7Contents contents = response.getBody();8String body = contents.reader().readLine();9Contents contents = response.getBody();10String body = contents.reader().readLine();11Contents contents = response.getBody();12String body = contents.reader().readLine();13Contents contents = response.getBody();14String body = contents.reader().readLine();15Contents contents = response.getBody();16String body = contents.reader().readLine();17Contents contents = response.getBody();18String body = contents.reader().readLine();19Contents contents = response.getBody();20String body = contents.reader().readLine();21Contents contents = response.getBody();22String body = contents.reader().readLine();23Contents contents = response.getBody();24String body = contents.reader().readLine();25Contents contents = response.getBody();26String body = contents.reader().readLine();

Full Screen

Full Screen

reader

Using AI Code Generation

copy

Full Screen

1String str = new String(new char[]{'a', 'b', 'c'});2String str = new String(new StringReader("abc"));3String str = new String(new ByteArrayInputStream(new byte[]{97, 98, 99}));4String str = new String(new byte[]{97, 98, 99});5String str = new String(new StringBuffer("abc"));6String str = new String(new StringBuilder("abc"));7String str = new String(new char[]{'a', 'b', 'c'}, 1, 2);8String str = new String(new byte[]{97, 98, 99}, 1, 2);9String str = new String("abc");10String str = new String(new StringBuffer("abc"), 1, 2);

Full Screen

Full Screen

reader

Using AI Code Generation

copy

Full Screen

1String content = response.getContent().readAsString();2System.out.println(content);3byte[] content = response.getContent().readAsBytes();4System.out.println(content);5InputStream content = response.getContent().readAsStream();6System.out.println(content);7Reader content = response.getContent().readAsReader();8System.out.println(content);9Json json = response.getContent().readAsJson();10System.out.println(json);11Xml xml = response.getContent().readAsXml();12System.out.println(xml);13Image img = response.getContent().readAsImage();14System.out.println(img);15File file = response.getContent().readAsFile();16System.out.println(file);17Object obj = response.getContent().readAsObject(Object.class);18System.out.println(obj);19Object obj = response.getContent().readAsObject(Object.class, Object.class);20System.out.println(obj);21Object obj = response.getContent().readAsObject(Object.class, Object.class, Object.class);22System.out.println(obj);23Object obj = response.getContent().readAsObject(Object.class, Object.class, Object.class, Object.class);24System.out.println(obj);25Object obj = response.getContent().readAsObject(Object.class, Object.class, Object.class, Object.class, Object.class);26System.out.println(obj);27Object obj = response.getContent().readAsObject(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class);28System.out.println(obj);29Object obj = response.getContent().readAsObject(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class);30System.out.println(obj);31Object obj = response.getContent().readAsObject(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class);32System.out.println(obj);

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