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

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

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);...

Full Screen

Full Screen

Source:Docker.java Github

copy

Full Screen

...16// under the License.17package org.openqa.selenium.docker;18import static com.google.common.collect.ImmutableList.toImmutableList;19import static org.openqa.selenium.json.Json.MAP_TYPE;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.GET;23import static org.openqa.selenium.remote.http.HttpMethod.POST;24import com.google.common.reflect.TypeToken;25import org.openqa.selenium.WebDriverException;26import org.openqa.selenium.json.Json;27import org.openqa.selenium.json.JsonException;28import org.openqa.selenium.json.JsonOutput;29import org.openqa.selenium.remote.http.Contents;30import org.openqa.selenium.remote.http.HttpClient;31import org.openqa.selenium.remote.http.HttpRequest;32import org.openqa.selenium.remote.http.HttpResponse;33import java.io.IOException;34import java.io.UncheckedIOException;35import java.net.HttpURLConnection;36import java.util.List;37import java.util.Map;38import java.util.Objects;39import java.util.Optional;40import java.util.function.Function;41import java.util.function.Predicate;42import java.util.logging.Logger;43public class Docker {...

Full Screen

Full Screen

Source:ResourceHandlerTest.java Github

copy

Full Screen

...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

...20import okhttp3.MediaType;21import okhttp3.Request;22import okhttp3.RequestBody;23import okhttp3.Response;24import org.openqa.selenium.remote.http.Contents;25import org.openqa.selenium.remote.http.HttpRequest;26import org.openqa.selenium.remote.http.HttpResponse;27import java.io.IOException;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 @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:CreateContainer.java Github

copy

Full Screen

...22import org.openqa.selenium.docker.DockerProtocol;23import org.openqa.selenium.internal.Require;24import org.openqa.selenium.json.Json;25import org.openqa.selenium.json.JsonException;26import org.openqa.selenium.remote.http.Contents;27import org.openqa.selenium.remote.http.HttpHandler;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import java.util.Collection;31import java.util.Map;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 }67 return new Container(protocol, id);68 } catch (JsonException | NullPointerException e) {69 throw new DockerException("Unable to create container from " + info);70 }...

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:Container.java Github

copy

Full Screen

...17package org.openqa.selenium.docker;18import static org.openqa.selenium.remote.http.HttpMethod.DELETE;19import static org.openqa.selenium.remote.http.HttpMethod.POST;20import org.openqa.selenium.WebDriverException;21import org.openqa.selenium.remote.http.Contents;22import org.openqa.selenium.remote.http.HttpRequest;23import org.openqa.selenium.remote.http.HttpResponse;24import java.net.HttpURLConnection;25import java.time.Duration;26import java.util.Objects;27import java.util.function.Function;28import java.util.logging.Logger;29public class Container {30 public static final Logger LOG = Logger.getLogger(Container.class.getName());31 private final Function<HttpRequest, HttpResponse> client;32 private final ContainerId id;33 public Container(Function<HttpRequest, HttpResponse> client, ContainerId id) {34 LOG.info("Created container " + id);35 this.client = Objects.requireNonNull(client);36 this.id = Objects.requireNonNull(id);37 }38 public ContainerId getId() {39 return id;40 }41 public void start() {42 LOG.info("Starting " + getId());43 HttpResponse res = client.apply(44 new HttpRequest(POST, String.format("/containers/%s/start", id)));45 if (res.getStatus() != HttpURLConnection.HTTP_OK) {46 throw new WebDriverException("Unable to start container: " + Contents.string(res));47 }48 }49 public void stop(Duration timeout) {50 Objects.requireNonNull(timeout);51 LOG.info("Stopping " + getId());52 String seconds = String.valueOf(timeout.toMillis() / 1000);53 HttpRequest request = new HttpRequest(POST, String.format("/containers/%s/stop", id));54 request.addQueryParameter("t", seconds);55 HttpResponse res = client.apply(request);56 if (res.getStatus() != HttpURLConnection.HTTP_OK) {57 throw new WebDriverException("Unable to stop container: " + Contents.string(res));58 }59 }60 public void delete() {61 LOG.info("Removing " + getId());62 HttpRequest request = new HttpRequest(DELETE, "/containers/" + id);63 HttpResponse res = client.apply(request);64 if (res.getStatus() != HttpURLConnection.HTTP_OK) {65 LOG.warning("Unable to delete container");66 }67 }68}...

Full Screen

Full Screen

Source:NewNodeSession.java Github

copy

Full Screen

...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));...

Full Screen

Full Screen

Contents

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.http.Contents;2import org.openqa.selenium.remote.http.HttpRequest;3public class HttpTest {4 public static void main(String[] args) {5 request.setContent(Contents.utf8String("Hello World!"));6 System.out.println(request.getContent());7 }8}

Full Screen

Full Screen

Contents

Using AI Code Generation

copy

Full Screen

1Contents contents = new Contents();2contents.put("text", "Hello World");3Content content = new Content();4content.put("text", "Hello World");5Content content = new Content();6content.put("text", "Hello World");7Contents contents = new Contents();8contents.put("text", "Hello World");9Content content = new Content();10content.put("text", "Hello World");11Contents contents = new Contents();12contents.put("text", "Hello World");13Content content = new Content();14content.put("text", "Hello World");15Contents contents = new Contents();16contents.put("text", "Hello World");17Content content = new Content();18content.put("text", "Hello World");19Contents contents = new Contents();20contents.put("text", "Hello World");21Content content = new Content();22content.put("text", "Hello World");23Contents contents = new Contents();24contents.put("text", "Hello World");25Content content = new Content();26content.put("text", "Hello World");27Contents contents = new Contents();28contents.put("text", "Hello World");29Content content = new Content();30content.put("text", "Hello World");31Contents contents = new Contents();32contents.put("text", "Hello World");33Content content = new Content();34content.put("text", "Hello World");

Full Screen

Full Screen

Contents

Using AI Code Generation

copy

Full Screen

1Contents contents = driver.execute(DriverCommand.EXECUTE_SCRIPT, ImmutableMap.of(2"script", "return document.documentElement.outerHTML", "args", new Object[] {}));3String body = contents.asString();4HttpClient client = HttpClientBuilder.create().build();5HttpGet request = new HttpGet(url);6HttpResponse response = client.execute(request);7HttpEntity entity = response.getEntity();8String body = EntityUtils.toString(entity);9HttpClient client = HttpClientBuilder.create().build();10HttpGet request = new HttpGet(url);11HttpResponse response = client.execute(request);12HttpEntity entity = response.getEntity();13String body = EntityUtils.toString(entity);14HttpClient client = HttpClientBuilder.create().build();15HttpGet request = new HttpGet(url);16HttpResponse response = client.execute(request);17HttpEntity entity = response.getEntity();18String body = EntityUtils.toString(entity);19HttpClient client = HttpClientBuilder.create().build();20HttpGet request = new HttpGet(url);21HttpResponse response = client.execute(request);22HttpEntity entity = response.getEntity();23String body = EntityUtils.toString(entity);24HttpClient client = HttpClientBuilder.create().build();25HttpGet request = new HttpGet(url);26HttpResponse response = client.execute(request);27HttpEntity entity = response.getEntity();28String body = EntityUtils.toString(entity);29HttpClient client = HttpClientBuilder.create().build();30HttpGet request = new HttpGet(url);31HttpResponse response = client.execute(request);32HttpEntity entity = response.getEntity();33String body = EntityUtils.toString(entity);

Full Screen

Full Screen

Contents

Using AI Code Generation

copy

Full Screen

1Contents contents = response.getContents();2JsonInput jsonInput = new JsonInput();3JsonOutput jsonOutput = new JsonOutput();4JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();5JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();6JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();7JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();8JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();9JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();10JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();11JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();12JsonTypeCoercer jsonTypeCoercer = new JsonTypeCoercer();

Full Screen

Full Screen
copy
1// GET2HttpResponse response = HttpRequest3 .create(new URI("http://www.stackoverflow.com"))4 .headers("Foo", "foovalue", "Bar", "barvalue")5 .GET()6 .response();7
Full Screen
copy
1HttpURLConnection.setFollowRedirects(true); // Defaults to true23String url = "https://name_of_the_url";4URL request_url = new URL(url);5HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();6http_conn.setConnectTimeout(100000);7http_conn.setReadTimeout(100000);8http_conn.setInstanceFollowRedirects(true);9System.out.println(String.valueOf(http_conn.getResponseCode()));10
Full Screen
copy
1package org.boon.utils;23import java.io.IOException;4import java.io.InputStream;5import java.net.HttpURLConnection;6import java.net.URL;7import java.net.URLConnection;8import java.util.Map;910import static org.boon.utils.IO.read;1112public class HTTP {13
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.

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful