org.openqa.selenium.json.Json Java Examples
The following examples show how to use
org.openqa.selenium.json.Json.
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: NodeStatusTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void ensureRoundTripWorks() throws URISyntaxException { ImmutableCapabilities stereotype = new ImmutableCapabilities("cheese", "brie"); NodeStatus status = new NodeStatus( UUID.randomUUID(), new URI("http://localhost:23456"), 100, ImmutableMap.of(stereotype, 1), ImmutableSet.of(new NodeStatus.Active(stereotype, new SessionId(UUID.randomUUID()), new ImmutableCapabilities("peas", "sausages"))), "cheese"); Json json = new Json(); String source = json.toJson(status); System.out.println(source); Object seen = json.toType(source, NodeStatus.class); assertThat(seen).isEqualTo(status); }
Example #2
Source File: TeeReaderTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldDuplicateStreams() { String expected = "{\"key\": \"value\"}"; Reader source = new StringReader(expected); StringWriter writer = new StringWriter(); Reader tee = new TeeReader(source, writer); try (JsonInput reader = new Json().newInput(tee)) { reader.beginObject(); assertEquals("key", reader.nextName()); reader.skipValue(); reader.endObject(); assertEquals(expected, writer.toString()); } }
Example #3
Source File: Router.java From selenium with Apache License 2.0 | 6 votes |
public Router( Tracer tracer, HttpClient.Factory clientFactory, SessionMap sessions, Distributor distributor) { Require.nonNull("Tracer to use", tracer); Require.nonNull("HTTP client factory", clientFactory); this.sessions = Require.nonNull("Session map", sessions); this.distributor = Require.nonNull("Distributor", distributor); routes = combine( get("/status") .to(() -> new GridStatusHandler(new Json(), tracer, clientFactory, distributor)), sessions.with(new SpanDecorator(tracer, req -> "session_map")), distributor.with(new SpanDecorator(tracer, req -> "distributor")), matching(req -> req.getUri().startsWith("/session/")) .to(() -> new HandleSession(tracer, clientFactory, sessions))); }
Example #4
Source File: SeleniumConfig.java From Selenium-Foundation with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public Path createNodeConfig(String capabilities, URL hubUrl) throws IOException { String nodeConfigPath = getNodeConfigPath().toString(); String configPathBase = nodeConfigPath.substring(0, nodeConfigPath.length() - 5); String hashCode = String.format("%08X", Objects.hash(capabilities, hubUrl)); Path filePath = Paths.get(configPathBase + "-" + hashCode + ".json"); if (filePath.toFile().createNewFile()) { JsonInput input = new Json().newInput(new StringReader(JSON_HEAD + capabilities + JSON_TAIL)); List<MutableCapabilities> capabilitiesList = GridNodeConfiguration.loadFromJSON(input).capabilities; GridNodeConfiguration nodeConfig = GridNodeConfiguration.loadFromJSON(nodeConfigPath); nodeConfig.capabilities = capabilitiesList; nodeConfig.hub = hubUrl.toString(); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(filePath.toFile()))) { out.write(new Json().toJson(nodeConfig).getBytes(StandardCharsets.UTF_8)); } } return filePath; }
Example #5
Source File: GetLogTypes.java From selenium with Apache License 2.0 | 6 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { // Try going upstream first. It's okay if this fails. HttpRequest upReq = new HttpRequest(GET, String.format("/session/%s/log/types", session.getId())); HttpResponse upRes = session.execute(upReq); ImmutableSet.Builder<String> types = ImmutableSet.builder(); types.add(LogType.SERVER); if (upRes.getStatus() == HTTP_OK) { Map<String, Object> upstream = json.toType(string(upRes), Json.MAP_TYPE); Object raw = upstream.get("value"); if (raw instanceof Collection) { ((Collection<?>) raw).stream().map(String::valueOf).forEach(types::add); } } Response response = new Response(session.getId()); response.setValue(types.build()); response.setStatus(ErrorCodes.SUCCESS); HttpResponse resp = new HttpResponse(); session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response); return resp; }
Example #6
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 #7
Source File: NodeTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void canUploadAFile() throws IOException { Session session = node.newSession(createSessionRequest(caps)) .map(CreateSessionResponse::getSession) .orElseThrow(() -> new AssertionError("Cannot create session")); HttpRequest req = new HttpRequest(POST, String.format("/session/%s/file", session.getId())); String hello = "Hello, world!"; String zip = Zip.zip(createTmpFile(hello)); String payload = new Json().toJson(Collections.singletonMap("file", zip)); req.setContent(() -> new ByteArrayInputStream(payload.getBytes())); node.execute(req); File baseDir = getTemporaryFilesystemBaseDir(local.getTemporaryFilesystem(session.getId())); assertThat(baseDir.listFiles()).hasSize(1); File uploadDir = baseDir.listFiles()[0]; assertThat(uploadDir.listFiles()).hasSize(1); assertThat(new String(Files.readAllBytes(uploadDir.listFiles()[0].toPath()))).isEqualTo(hello); node.stop(session.getId()); assertThat(baseDir).doesNotExist(); }
Example #8
Source File: Preferences.java From selenium with Apache License 2.0 | 6 votes |
private void readDefaultPreferences(Reader defaultsReader) { try { String rawJson = CharStreams.toString(defaultsReader); Map<String, Object> map = new Json().toType(rawJson, MAP_TYPE); Map<String, Object> frozen = (Map<String, Object>) map.get("frozen"); frozen.forEach((key, value) -> { if (value instanceof Long) { value = ((Long) value).intValue(); } setPreference(key, value); immutablePrefs.put(key, value); }); Map<String, Object> mutable = (Map<String, Object>) map.get("mutable"); mutable.forEach(this::setPreference); } catch (IOException e) { throw new WebDriverException(e); } }
Example #9
Source File: PointerInputTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void encodesWrappedElementInMoveOrigin() { RemoteWebElement innerElement = new RemoteWebElement(); innerElement.setId("12345"); WebElement element = new WrappedWebElement(innerElement); PointerInput pointerInput = new PointerInput(Kind.MOUSE, null); Interaction move = pointerInput.createPointerMove( Duration.ofMillis(100), Origin.fromElement(element), 0, 0); Sequence sequence = new Sequence(move.getSource(), 0).addAction(move); String rawJson = new Json().toJson(sequence); ActionSequenceJson json = new Json().toType( rawJson, ActionSequenceJson.class, PropertySetting.BY_FIELD); assertThat(json.actions).hasSize(1); ActionJson firstAction = json.actions.get(0); assertThat(firstAction.origin).containsEntry(W3C.getEncodedElementKey(), "12345"); }
Example #10
Source File: CompiledAtomsNotLeakingTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void nestedFragmentsShouldNotLeakVariables() { ContextFactory.getGlobal().call(context -> { // executeScript atom recursing on itself to execute "return 1+2". // Should result in {status:0,value:{status:0,value:3}} // Global scope should not be modified. String nestedScript = String.format("(%s).call(null, %s, ['return 1+2;'], true)", fragment, fragment); String jsonResult = (String) eval(context, nestedScript, RESOURCE_PATH); Map<String, Object> result = new Json().toType(jsonResult, Json.MAP_TYPE); assertThat(result.get("status")).isInstanceOf(Long.class).as(jsonResult).isEqualTo(0L); assertThat(result.get("value")).isInstanceOf(Map.class); assertThat(result.get("value")) .asInstanceOf(MAP) .hasSize(2) .containsEntry("status", 0L) .containsEntry("value", 3L); assertThat(eval(context, "_")).isEqualTo(1234); return null; }); }
Example #11
Source File: Distributor.java From selenium with Apache License 2.0 | 6 votes |
protected Distributor(Tracer tracer, HttpClient.Factory httpClientFactory) { this.tracer = Require.nonNull("Tracer", tracer); Require.nonNull("HTTP client factory", httpClientFactory); Json json = new Json(); routes = Route.combine( post("/session").to(() -> req -> { CreateSessionResponse sessionResponse = newSession(req); return new HttpResponse().setContent(bytes(sessionResponse.getDownstreamEncodedResponse())); }), post("/se/grid/distributor/session") .to(() -> new CreateSession(this)), post("/se/grid/distributor/node") .to(() -> new AddNode(tracer, this, json, httpClientFactory)), delete("/se/grid/distributor/node/{nodeId}") .to(params -> new RemoveNode(this, UUID.fromString(params.get("nodeId")))), get("/se/grid/distributor/status") .to(() -> new GetDistributorStatus(this)) .with(new SpanDecorator(tracer, req -> "distributor.status"))); }
Example #12
Source File: JreAppServer.java From selenium with Apache License 2.0 | 6 votes |
@Override public String create(Page page) { try { byte[] data = new Json() .toJson(ImmutableMap.of("content", page.toString())) .getBytes(UTF_8); HttpClient client = HttpClient.Factory.createDefault().createClient(new URL(whereIs("/"))); HttpRequest request = new HttpRequest(HttpMethod.POST, "/common/createPage"); request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString()); request.setContent(bytes(data)); HttpResponse response = client.execute(request); return string(response); } catch (IOException ex) { throw new RuntimeException(ex); } }
Example #13
Source File: CreatePageServlet.java From selenium with Apache License 2.0 | 6 votes |
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String content = request.getReader().lines().collect(Collectors.joining()); Map<String, String> json = new Json().toType(content, Json.MAP_TYPE); Path tempPageDir = Paths.get(getServletContext().getInitParameter("tempPageDir")); Path target = Files.createTempFile(tempPageDir, "page", ".html"); try (Writer out = new FileWriter(target.toFile())) { out.write(json.get("content")); } response.setContentType("text/plain"); response.getWriter().write(String.format( "http://%s:%s%s/%s", getServletContext().getInitParameter("hostname"), getServletContext().getInitParameter("port"), getServletContext().getInitParameter("path"), target.getFileName())); response.setStatus(HttpServletResponse.SC_OK); }
Example #14
Source File: NewSessionPayloadTest.java From selenium with Apache License 2.0 | 6 votes |
private List<Capabilities> create(Map<String, ?> source) { List<Capabilities> presumablyFromMemory; List<Capabilities> fromDisk; try (NewSessionPayload payload = NewSessionPayload.create(source)) { presumablyFromMemory = payload.stream().collect(toList()); } String json = new Json().toJson(source); try (NewSessionPayload payload = NewSessionPayload.create(new StringReader(json))) { fromDisk = payload.stream().collect(toList()); } assertEquals(presumablyFromMemory, fromDisk); return presumablyFromMemory; }
Example #15
Source File: JsonWireProtocolResponseTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldProperlyPopulateAnError() { WebDriverException exception = new SessionNotCreatedException("me no likey"); Json json = new Json(); Map<String, Object> payload = ImmutableMap.of( "value", json.toType(json.toJson(exception), Json.MAP_TYPE), "status", ErrorCodes.SESSION_NOT_CREATED); InitialHandshakeResponse initialResponse = new InitialHandshakeResponse( 0, 500, payload); assertThatExceptionOfType(SessionNotCreatedException.class) .isThrownBy(() -> new JsonWireProtocolResponse().getResponseFunction().apply(initialResponse)) .withMessageContaining("me no likey"); }
Example #16
Source File: NewSessionPayloadTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldIndicateDownstreamW3cDialect() { Map<String, Map<String, Map<String, String>>> caps = singletonMap( "capabilities", singletonMap( "alwaysMatch", singletonMap( "browserName", "cheese"))); try (NewSessionPayload payload = NewSessionPayload.create(caps)) { assertEquals(singleton(Dialect.W3C), payload.getDownstreamDialects()); } String json = new Json().toJson(caps); try (NewSessionPayload payload = NewSessionPayload.create(new StringReader(json))) { assertEquals(singleton(Dialect.W3C), payload.getDownstreamDialects()); } }
Example #17
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 #18
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 #19
Source File: UploadFileTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldWriteABase64EncodedZippedFileToDiskAndKeepName() throws Exception { ActiveSession session = mock(ActiveSession.class); when(session.getId()).thenReturn(new SessionId("1234567")); when(session.getFileSystem()).thenReturn(tempFs); when(session.getDownstreamDialect()).thenReturn(Dialect.OSS); File tempFile = touch(null, "foo"); String encoded = Zip.zip(tempFile); UploadFile uploadFile = new UploadFile(new Json(), session); Map<String, Object> args = ImmutableMap.of("file", encoded); HttpRequest request = new HttpRequest(HttpMethod.POST, "/session/%d/se/file"); request.setContent(asJson(args)); HttpResponse response = uploadFile.execute(request); Response res = new Json().toType(string(response), Response.class); String path = (String) res.getValue(); assertTrue(new File(path).exists()); assertTrue(path.endsWith(tempFile.getName())); }
Example #20
Source File: JsonHttpResponseCodecTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void convertsResponses_success() { Response response = new Response(); response.setStatus(ErrorCodes.SUCCESS); response.setValue(ImmutableMap.of("color", "red")); HttpResponse converted = codec.encode(HttpResponse::new, response); assertThat(converted.getStatus()).isEqualTo(HTTP_OK); assertThat(converted.getHeader(CONTENT_TYPE)).isEqualTo(JSON_UTF_8.toString()); Response rebuilt = new Json().toType(string(converted), Response.class); assertThat(rebuilt.getStatus()).isEqualTo(response.getStatus()); assertThat(rebuilt.getState()).isEqualTo(new ErrorCodes().toState(response.getStatus())); assertThat(rebuilt.getSessionId()).isEqualTo(response.getSessionId()); assertThat(rebuilt.getValue()).isEqualTo(response.getValue()); }
Example #21
Source File: NewSessionPayloadTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void forwardsMetaDataAssociatedWithARequest() throws IOException { try (NewSessionPayload payload = NewSessionPayload.create( ImmutableMap.of( "desiredCapabilities", EMPTY_MAP, "cloud:user", "bob", "cloud:key", "there is no cake"))) { StringBuilder toParse = new StringBuilder(); payload.writeTo(toParse); Map<String, Object> seen = new Json().toType(toParse.toString(), MAP_TYPE); assertEquals("bob", seen.get("cloud:user")); assertEquals("there is no cake", seen.get("cloud:key")); } }
Example #22
Source File: ExceptionHandlerTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void shouldSetErrorCodeForJsonWireProtocol() { Exception e = new NoSuchSessionException("This does not exist"); HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session")); assertEquals(HTTP_INTERNAL_ERROR, response.getStatus()); Map<String, Object> err = new Json().toType(string(response), MAP_TYPE); assertEquals(ErrorCodes.NO_SUCH_SESSION, ((Number) err.get("status")).intValue()); }
Example #23
Source File: NewSessionPayloadTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void shouldDefaultToAssumingADownstreamOssDialect() { Map<String, Object> caps = EMPTY_MAP; try (NewSessionPayload payload = NewSessionPayload.create(caps)) { assertEquals(singleton(Dialect.OSS), payload.getDownstreamDialects()); } String json = new Json().toJson(caps); try (NewSessionPayload payload = NewSessionPayload.create(new StringReader(json))) { assertEquals(singleton(Dialect.OSS), payload.getDownstreamDialects()); } }
Example #24
Source File: SessionMap.java From selenium with Apache License 2.0 | 5 votes |
public SessionMap(Tracer tracer) { this.tracer = Require.nonNull("Tracer", tracer); Json json = new Json(); routes = combine( Route.get("/se/grid/session/{sessionId}/uri") .to(params -> new GetSessionUri(this, sessionIdFrom(params))), post("/se/grid/session") .to(() -> new AddToSessionMap(tracer, json, this)), Route.get("/se/grid/session/{sessionId}") .to(params -> new GetFromSessionMap(tracer, this, sessionIdFrom(params))), delete("/se/grid/session/{sessionId}") .to(params -> new RemoveFromSession(tracer, this, sessionIdFrom(params)))); }
Example #25
Source File: UploadFile.java From selenium with Apache License 2.0 | 5 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { Map<String, Object> args = json.toType(string(req), Json.MAP_TYPE); String file = (String) args.get("file"); File tempDir = session.getFileSystem().createTempDir("upload", "file"); try { Zip.unzip(file, tempDir); } catch (IOException e) { throw new UncheckedIOException(e); } // Select the first file File[] allFiles = tempDir.listFiles(); Response response = new Response(session.getId()); if (allFiles == null || allFiles.length != 1) { response.setStatus(ErrorCodes.UNHANDLED_ERROR); response.setValue(new WebDriverException( "Expected there to be only 1 file. There were: " + (allFiles == null ? 0 : allFiles.length))); } else { response.setStatus(ErrorCodes.SUCCESS); response.setValue(allFiles[0].getAbsolutePath()); } HttpResponse resp = new HttpResponse(); session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response); return resp; }
Example #26
Source File: NewSessionPayloadTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void shouldIndicateDownstreamOssDialect() { Map<String, Map<String, String>> caps = singletonMap( "desiredCapabilities", singletonMap( "browserName", "cheese")); try (NewSessionPayload payload = NewSessionPayload.create(caps)) { assertEquals(singleton(Dialect.OSS), payload.getDownstreamDialects()); } String json = new Json().toJson(caps); try (NewSessionPayload payload = NewSessionPayload.create(new StringReader(json))) { assertEquals(singleton(Dialect.OSS), payload.getDownstreamDialects()); } }
Example #27
Source File: GetLogsOfType.java From selenium with Apache License 2.0 | 5 votes |
@Override public HttpResponse execute(HttpRequest req) throws UncheckedIOException { String originalPayload = string(req); Map<String, Object> args = json.toType(originalPayload, Json.MAP_TYPE); String type = (String) args.get("type"); if (!LogType.SERVER.equals(type)) { HttpRequest upReq = new HttpRequest(POST, String.format("/session/%s/log", session.getId())); upReq.setContent(utf8String(originalPayload)); return session.execute(upReq); } LogEntries entries = null; try { entries = LoggingManager.perSessionLogHandler().getSessionLog(session.getId()); } catch (IOException e) { throw new UncheckedIOException(e); } Response response = new Response(session.getId()); response.setStatus(ErrorCodes.SUCCESS); response.setValue(entries); HttpResponse resp = new HttpResponse(); session.getDownstreamDialect().getResponseCodec().encode(() -> resp, response); return resp; }
Example #28
Source File: JsonHttpCommandCodecTest.java From selenium with Apache License 2.0 | 5 votes |
@Test public void extractsAllParameters() { String data = new Json().toJson(ImmutableMap.of("sessionId", "sessionX", "fruit", "apple", "color", "red", "size", "large")); 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()).isEqualTo(new SessionId("sessionX")); assertThat(decoded.getParameters()).isEqualTo((Map<String, String>) ImmutableMap.of( "fruit", "apple", "size", "large", "color", "red")); }
Example #29
Source File: Edition095_Android_Datamatcher.java From appiumpro with Apache License 2.0 | 5 votes |
@Test public void testFindHiddenListItemWithDatamatcher() { wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AccessibilityId("Views"))).click(); WebElement list = wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.className("android.widget.ListView"))); String selector = new Json().toJson(ImmutableMap.of( "name", "hasEntry", "args", ImmutableList.of("title", "Layouts") )); list.findElement(MobileBy.androidDataMatcher(selector)).click(); wait.until(ExpectedConditions.presenceOfElementLocated(MobileBy.AccessibilityId("Baseline"))); }
Example #30
Source File: GraphqlHandlerTest.java From selenium with Apache License 2.0 | 5 votes |
private Map<String, Object> executeQuery(HttpHandler handler, String query) { HttpResponse res = handler.execute( new HttpRequest(GET, "/graphql") .setContent(Contents.utf8String(query))); return new Json().toType(Contents.string(res), MAP_TYPE); }