org.openqa.selenium.remote.http.HttpRequest Java Examples
The following examples show how to use
org.openqa.selenium.remote.http.HttpRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalNode.java From selenium with Apache License 2.0 | 6 votes |
@Override public HttpResponse executeWebDriverCommand(HttpRequest req) { // True enough to be good enough SessionId id = getSessionId(req.getUri()).map(SessionId::new) .orElseThrow(() -> new NoSuchSessionException("Cannot find session: " + req)); SessionSlot slot = currentSessions.getIfPresent(id); if (slot == null) { throw new NoSuchSessionException("Cannot find session with id: " + id); } HttpResponse toReturn = slot.execute(req); if (req.getMethod() == DELETE && req.getUri().equals("/session/" + id)) { stop(id); } return toReturn; }
Example #2
Source File: AddToSessionMap.java From selenium with Apache License 2.0 | 6 votes |
@Override public HttpResponse execute(HttpRequest req) { try (Span span = newSpanAsChildOf(tracer, req, "sessions.add_session")) { HTTP_REQUEST.accept(span, req); Session session = json.toType(string(req), Session.class); Objects.requireNonNull(session, "Session to add must be set"); SESSION_ID.accept(span, session.getId()); CAPABILITIES.accept(span, session.getCapabilities()); span.setAttribute("session.uri", session.getUri().toString()); sessions.add(session); return new HttpResponse().setContent(asJson(ImmutableMap.of("value", true))); } }
Example #3
Source File: ProxyCdpIntoGrid.java From selenium with Apache License 2.0 | 6 votes |
@Override public Optional<Consumer<Message>> apply(String uri, Consumer<Message> downstream) { Objects.requireNonNull(uri); Objects.requireNonNull(downstream); Optional<SessionId> sessionId = HttpSessionId.getSessionId(uri).map(SessionId::new); if (!sessionId.isPresent()) { return Optional.empty(); } try { Session session = sessions.get(sessionId.get()); HttpClient client = clientFactory.createClient(ClientConfig.defaultConfig().baseUri(session.getUri())); WebSocket upstream = client.openSocket(new HttpRequest(GET, uri), new ForwardingListener(downstream)); return Optional.of(upstream::send); } catch (NoSuchSessionException e) { LOG.info("Attempt to connect to non-existant session: " + uri); return Optional.empty(); } }
Example #4
Source File: ListImages.java From selenium with Apache License 2.0 | 6 votes |
public Set<Image> apply(Reference reference) { Require.nonNull("Reference to search for", reference); String familiarName = reference.getFamiliarName(); Map<String, Object> filters = ImmutableMap.of("reference", ImmutableMap.of(familiarName, true)); // https://docs.docker.com/engine/api/v1.40/#operation/ImageList HttpRequest req = new HttpRequest(GET, "/v1.40/images/json") .addHeader("Content-Length", "0") .addHeader("Content-Type", JSON_UTF_8) .addQueryParameter("filters", JSON.toJson(filters)); HttpResponse response = DockerMessages.throwIfNecessary( client.execute(req), "Unable to list images for %s", reference); Set<ImageSummary> images = JSON.toType(string(response), SET_OF_IMAGE_SUMMARIES); return images.stream() .map(org.openqa.selenium.docker.Image::new) .collect(toImmutableSet()); }
Example #5
Source File: ResourceHandler.java From selenium with Apache License 2.0 | 6 votes |
private HttpResponse readDirectory(HttpRequest req, Resource resource) { if (!req.getUri().endsWith("/")) { String dest = UrlPath.relativeToContext(req, req.getUri() + "/"); return new HttpResponse() .setStatus(HTTP_MOVED_TEMP) .addHeader("Location", dest); } String links = resource.list().stream() .map(res -> String.format("<li><a href=\"%s\">%s</a>", res.name(), res.name())) .sorted() .collect(Collectors.joining("\n", "<ul>\n", "</ul>\n")); String html = String.format( "<html><title>Listing of %s</title><body><h1>%s</h1>%s", resource.name(), resource.name(), links); return new HttpResponse() .addHeader("Content-Type", HTML_UTF_8.toString()) .setContent(utf8String(html)); }
Example #6
Source File: NoSessionHandler.java From selenium with Apache License 2.0 | 6 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { // We're not using ImmutableMap for the outer map because it disallows null values. Map<String, Object> responseMap = new HashMap<>(); responseMap.put("sessionId", sessionId.toString()); responseMap.put("status", NO_SUCH_SESSION); responseMap.put("value", ImmutableMap.of( "error", "invalid session id", "message", String.format("No active session with ID %s", sessionId), "stacktrace", "")); responseMap = Collections.unmodifiableMap(responseMap); byte[] payload = json.toJson(responseMap).getBytes(UTF_8); return new HttpResponse().setStatus(HTTP_NOT_FOUND) .setHeader("Content-Type", JSON_UTF_8.toString()) .setContent(bytes(payload)); }
Example #7
Source File: HttpHandlerServletTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldReturnValueFromHandlerIfUrlMatches() throws IOException { String cheerfulGreeting = "Hello, world!"; HttpHandlerServlet servlet = new HttpHandlerServlet( Route.matching(req -> true) .to(() -> req -> new HttpResponse().setContent(utf8String(cheerfulGreeting)))); HttpServletRequest request = requestConverter.apply(new HttpRequest(GET, "/hello-world")); FakeHttpServletResponse response = new FakeHttpServletResponse(); servlet.service(request, response); assertThat(response.getStatus()).isEqualTo(HTTP_OK); assertThat(response.getBody()).isEqualTo(cheerfulGreeting); }
Example #8
Source File: EndToEndTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldAllowPassthroughForJWPMode() { HttpRequest request = new HttpRequest(POST, "/session"); request.setContent(asJson( ImmutableMap.of( "desiredCapabilities", ImmutableMap.of( "browserName", "cheese")))); HttpClient client = clientFactory.createClient(server.getUrl()); HttpResponse response = client.execute(request); assertEquals(200, response.getStatus()); Map<String, Object> topLevel = json.toType(string(response), MAP_TYPE); // There should be a numeric status field assertEquals(topLevel.toString(), 0L, topLevel.get("status")); // The session id assertTrue(string(request), topLevel.containsKey("sessionId")); // And the value should be the capabilities. Map<?, ?> value = (Map<?, ?>) topLevel.get("value"); assertEquals(string(request), "cheese", value.get("browserName")); }
Example #9
Source File: WebSocketServingTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldStillBeAbleToServeHttpTraffic() { server = new NettyServer( defaultOptions(), req -> new HttpResponse().setContent(utf8String("Brie!")), (uri, sink) -> { if ("/foo".equals(uri)) { return Optional.of(msg -> sink.accept(new TextMessage("Peas!"))); } return Optional.empty(); }).start(); HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl()); HttpResponse res = client.execute(new HttpRequest(GET, "/cheese")); assertThat(Contents.string(res)).isEqualTo("Brie!"); }
Example #10
Source File: PageHandler.java From selenium with Apache License 2.0 | 6 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { int lastIndex = req.getUri().lastIndexOf('/'); String pageNumber = (lastIndex == -1 ? "Unknown" : req.getUri().substring(lastIndex + 1)); String body = String.format("<html><head><title>Page%s</title></head>" + "<body>Page number <span id=\"pageNumber\">%s</span>" + "<p><a href=\"../xhtmlTest.html\" target=\"_top\">top</a>" + "</body></html>", pageNumber, pageNumber); return new HttpResponse() .setHeader("Content-Type", "text/html") .setContent(utf8String(body)); }
Example #11
Source File: GetAllSessions.java From selenium with Apache License 2.0 | 6 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { List<Map<String, Object>> value = new ArrayList<>(); allSessions.getAllSessions().forEach(s -> value.add( ImmutableMap.of("id", s.getId().toString(), "capabilities", s.getCapabilities()))); Map<String, Object> payloadObj = ImmutableMap.of( "status", SUCCESS, "value", value); // Write out a minimal W3C status response. byte[] payload = json.toJson(payloadObj).getBytes(UTF_8); return new HttpResponse().setStatus(HTTP_OK) .setHeader("Content-Type", JSON_UTF_8.toString()) .setContent(bytes(payload)); }
Example #12
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void ignoresNullSessionIdInSessionBody() { Map<String, Object> map = new HashMap<>(); map.put("sessionId", null); map.put("fruit", "apple"); map.put("color", "red"); map.put("size", "large"); String data = new Json().toJson(map); HttpRequest request = new HttpRequest(POST, "/fruit/apple/size/large"); request.setContent(utf8String(data)); codec.defineCommand("pick", POST, "/fruit/:fruit/size/:size"); Command decoded = codec.decode(request); assertThat(decoded.getSessionId()).isNull(); assertThat(decoded.getParameters()).isEqualTo((Map<String, String>) ImmutableMap.of( "fruit", "apple", "size", "large", "color", "red")); }
Example #13
Source File: HttpClientTestBase.java From selenium with Apache License 2.0 | 6 votes |
private HttpResponse executeWithinServer(HttpRequest request, HttpServlet servlet) throws Exception { Server server = new Server(PortProber.findFreePort()); ServletContextHandler handler = new ServletContextHandler(); handler.setContextPath(""); ServletHolder holder = new ServletHolder(servlet); handler.addServlet(holder, "/*"); server.setHandler(handler); server.start(); try { HttpClient client = createFactory().createClient(fromUri(server.getURI())); return client.execute(request); } finally { server.stop(); } }
Example #14
Source File: HttpClientTestBase.java From selenium with Apache License 2.0 | 6 votes |
private HttpResponse getQueryParameterResponse(HttpRequest request) throws Exception { return executeWithinServer( request, new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try (Writer writer = resp.getWriter()) { JsonOutput json = new Json().newOutput(writer); json.beginObject(); req.getParameterMap() .forEach((key, value) -> { json.name(key); json.beginArray(); Stream.of(value).forEach(json::write); json.endArray(); }); json.endObject(); } } }); }
Example #15
Source File: JettyServerTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void exceptionsThrownByHandlersAreConvertedToAProperPayload() { Server<?> server = new JettyServer( emptyOptions, req -> { throw new UnableToSetCookieException("Yowza"); }); server.start(); URL url = server.getUrl(); HttpClient client = HttpClient.Factory.createDefault().createClient(url); HttpResponse response = client.execute(new HttpRequest(GET, "/status")); assertThat(response.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); Throwable thrown = null; try { thrown = ErrorCodec.createDefault().decode(new Json().toType(string(response), MAP_TYPE)); } catch (IllegalArgumentException ignored) { fail("Apparently the command succeeded" + string(response)); } assertThat(thrown).isInstanceOf(UnableToSetCookieException.class); assertThat(thrown.getMessage()).startsWith("Yowza"); }
Example #16
Source File: EndToEndTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldAllowPassthroughForW3CMode() { HttpRequest request = new HttpRequest(POST, "/session"); request.setContent(asJson( ImmutableMap.of( "capabilities", ImmutableMap.of( "alwaysMatch", ImmutableMap.of("browserName", "cheese"))))); HttpClient client = clientFactory.createClient(server.getUrl()); HttpResponse response = client.execute(request); assertEquals(200, response.getStatus()); Map<String, Object> topLevel = json.toType(string(response), MAP_TYPE); // There should not be a numeric status field assertFalse(string(request), topLevel.containsKey("status")); // And the value should have all the good stuff in it: the session id and the capabilities Map<?, ?> value = (Map<?, ?>) topLevel.get("value"); assertThat(value.get("sessionId")).isInstanceOf(String.class); Map<?, ?> caps = (Map<?, ?>) value.get("capabilities"); assertEquals("cheese", caps.get("browserName")); }
Example #17
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void decodingUsesUtf8IfNoEncodingSpecified() { codec.defineCommand("num", POST, "/one"); byte[] data = "{\"char\":\"水\"}".getBytes(UTF_8); HttpRequest request = new HttpRequest(POST, "/one"); request.setHeader(CONTENT_TYPE, JSON_UTF_8.withoutParameters().toString()); request.setHeader(CONTENT_LENGTH, String.valueOf(data.length)); request.setContent(bytes(data)); Command command = codec.decode(request); assertThat((String) command.getParameters().get("char")).isEqualTo("水"); }
Example #18
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void treatsEmptyPathAsRoot_recognizedCommand() { codec.defineCommand("num", POST, "/"); byte[] data = "{\"char\":\"水\"}".getBytes(UTF_8); HttpRequest request = new HttpRequest(POST, ""); request.setHeader(CONTENT_TYPE, JSON_UTF_8.withoutParameters().toString()); request.setHeader(CONTENT_LENGTH, String.valueOf(data.length)); request.setContent(bytes(data)); Command command = codec.decode(request); assertThat(command.getName()).isEqualTo("num"); }
Example #19
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void canExtractSessionIdFromPathParameters() { HttpRequest request = new HttpRequest(GET, "/foo/bar/baz"); codec.defineCommand("foo", GET, "/foo/:sessionId/baz"); Command decoded = codec.decode(request); assertThat(decoded.getSessionId()).isEqualTo(new SessionId("bar")); }
Example #20
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void canDecodeCommandWithNoParameters() { HttpRequest request = new HttpRequest(GET, "/foo/bar/baz"); codec.defineCommand("foo", GET, "/foo/bar/baz"); Command decoded = codec.decode(request); assertThat(decoded.getName()).isEqualTo("foo"); assertThat(decoded.getSessionId()).isNull(); assertThat(decoded.getParameters()).isEmpty(); }
Example #21
Source File: RemoteNode.java From selenium with Apache License 2.0 | 5 votes |
@Override public NodeStatus getStatus() { HttpRequest req = new HttpRequest(GET, "/status"); HttpTracing.inject(tracer, tracer.getCurrentContext(), req); HttpResponse res = client.execute(req); try (Reader reader = reader(res); JsonInput in = JSON.newInput(reader)) { in.beginObject(); // Skip everything until we find "value" while (in.hasNext()) { if ("value".equals(in.nextName())) { in.beginObject(); while (in.hasNext()) { if ("node".equals(in.nextName())) { return in.read(NodeStatus.class); } else { in.skipValue(); } } in.endObject(); } else { in.skipValue(); } } } catch (IOException e) { throw new UncheckedIOException(e); } throw new IllegalStateException("Unable to read status"); }
Example #22
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void preventsCachingGetRequests() { codec.defineCommand("foo", GET, "/foo"); HttpRequest request = codec.encode(new Command(null, "foo")); assertThat(request.getMethod()).isEqualTo(GET); assertThat(request.getHeader(CACHE_CONTROL)).isEqualTo("no-cache"); }
Example #23
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void encodingAPostWithUrlParameters() { codec.defineCommand("foo", POST, "/foo/:bar/baz"); Command command = new Command(null, "foo", ImmutableMap.of("bar", "apples123")); String encoding = "{\n \"bar\": \"apples123\"\n}"; HttpRequest request = codec.encode(command); assertThat(request.getMethod()).isEqualTo(POST); assertThat(request.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString()); assertThat(request.getHeader(CONTENT_LENGTH)).isEqualTo(String.valueOf(encoding.length())); assertThat(request.getUri()).isEqualTo("/foo/apples123/baz"); assertThat(string(request)).isEqualTo(encoding); }
Example #24
Source File: NodeTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void canReturnStatus() { node.newSession(createSessionRequest(caps)) .map(CreateSessionResponse::getSession) .orElseThrow(() -> new AssertionError("Cannot create session")); HttpRequest req = new HttpRequest(GET, "/status"); HttpResponse res = node.execute(req); assertThat(res.getStatus()).isEqualTo(200); Map<String, Object> status = new Json().toType(string(res), MAP_TYPE); assertThat(status).containsOnlyKeys("value"); assertThat(status).extracting("value").asInstanceOf(MAP) .containsEntry("ready", true) .containsEntry("message", "Ready") .containsKey("node"); assertThat(status).extracting("value.node").asInstanceOf(MAP) .containsKey("id") .containsEntry("uri", "http://localhost:1234") .containsEntry("maxSessions", (long) 2) .containsKey("stereotypes") .containsKey("sessions"); assertThat(status).extracting("value.node.stereotypes").asInstanceOf(LIST) .hasSize(1) .element(0).asInstanceOf(MAP) .containsEntry("capabilities", Collections.singletonMap("browserName", "cheese")) .containsEntry("count", (long) 3); assertThat(status).extracting("value.node.sessions").asInstanceOf(LIST) .hasSize(1) .element(0).asInstanceOf(MAP) .containsEntry("currentCapabilities", Collections.singletonMap("browserName", "cheese")) .containsEntry("stereotype", Collections.singletonMap("browserName", "cheese")) .containsKey("sessionId"); }
Example #25
Source File: ErrorHandler.java From selenium with Apache License 2.0 | 5 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { return new HttpResponse() .setHeader("Cache-Control", "none") .setHeader("Content-Type", JSON_UTF_8.toString()) .setStatus(errors.getHttpStatusCode(throwable)) .setContent(asJson(errors.encode(throwable))); }
Example #26
Source File: RemoteDistributor.java From selenium with Apache License 2.0 | 5 votes |
@Override public RemoteDistributor add(Node node) { HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/node"); HttpTracing.inject(tracer, tracer.getCurrentContext(), request); request.setContent(asJson(node.getStatus())); HttpResponse response = client.execute(request); Values.get(response, Void.class); LOG.info(String.format("Added node %s.", node.getId())); return this; }
Example #27
Source File: RemoveFromSession.java From selenium with Apache License 2.0 | 5 votes |
@Override public HttpResponse execute(HttpRequest req) { try (Span span = newSpanAsChildOf(tracer, req, "sessions.remove_session")) { HTTP_REQUEST.accept(span, req); SESSION_ID.accept(span, id); sessions.remove(id); return new HttpResponse(); } }
Example #28
Source File: ExceptionHandler.java From selenium with Apache License 2.0 | 5 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { int code = ERRORS.toStatusCode(exception); String status = ERRORS.toState(code); Map<String, Object> toSerialise = new HashMap<>(); // W3C Map<String, Object> value = new HashMap<>(); value.put("message", exception.getMessage()); value.put("stacktrace", Throwables.getStackTraceAsString(exception)); value.put("error", status); // JSON Wire Protocol toSerialise.put("status", code); value.put( "stackTrace", Stream.of(exception.getStackTrace()) .map(ste -> { HashMap<String, Object> line = new HashMap<>(); line.put("fileName", ste.getFileName()); line.put("lineNumber", ste.getLineNumber()); line.put("className", ste.getClassName()); line.put("methodName", ste.getMethodName()); return line; }) .collect(ImmutableList.toImmutableList())); toSerialise.put("value", value); byte[] bytes = toJson.toJson(toSerialise).getBytes(UTF_8); return new HttpResponse() .setStatus(HTTP_INTERNAL_ERROR) .setHeader("Content-Type", JSON_UTF_8.toString()) .setContent(bytes(bytes)); }
Example #29
Source File: ProtocolConverter.java From selenium with Apache License 2.0 | 5 votes |
private CommandCodec<HttpRequest> getCommandCodec(Dialect dialect) { switch (dialect) { case OSS: return new JsonHttpCommandCodec(); case W3C: return new W3CHttpCommandCodec(); default: throw new IllegalStateException("Unknown dialect: " + dialect); } }
Example #30
Source File: ReverseProxyHandlerTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void shouldForwardRequestsToEndPoint() { HttpHandler handler = new ReverseProxyHandler(tracer, factory.createClient(server.url)); HttpRequest req = new HttpRequest(HttpMethod.GET, "/ok"); req.addHeader("X-Cheese", "Cake"); handler.execute(req); // HTTP headers are case insensitive. This is how the HttpUrlConnection likes to encode things assertEquals("Cake", server.lastRequest.getHeader("x-cheese")); }