Java Code Examples for org.openqa.selenium.remote.http.HttpRequest#setContent()

The following examples show how to use org.openqa.selenium.remote.http.HttpRequest#setContent() . 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: JreAppServer.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: EndToEndTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: JreMessages.java    From selenium with Apache License 2.0 6 votes vote down vote up
static HttpRequest asRequest(HttpExchange exchange) {
  HttpRequest request = new HttpRequest(
    HttpMethod.valueOf(exchange.getRequestMethod()),
    exchange.getRequestURI().getPath());

  String query = exchange.getRequestURI().getQuery();
  if (query != null) {
    Arrays.stream(query.split("&"))
      .map(q -> {
        int i = q.indexOf("=");
        if (i == -1) {
          return new AbstractMap.SimpleImmutableEntry<>(q, "");
        }
        return new AbstractMap.SimpleImmutableEntry<>(q.substring(0, i), q.substring(i + 1));
      })
      .forEach(entry -> request.addQueryParameter(entry.getKey(), entry.getValue()));
  }

  exchange.getRequestHeaders().forEach((name, values) -> values.forEach(value -> request.addHeader(name, value)));

  request.setContent(memoize(exchange::getRequestBody));

  return request;
}
 
Example 4
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: UploadFileTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void treatsNullPathAsRoot_recognizedCommand() {
  codec.defineCommand("num", POST, "/");

  byte[] data = "{\"char\":\"水\"}".getBytes(UTF_8);
  HttpRequest request = new HttpRequest(POST, null);
  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 7
Source File: DistributorTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private HttpRequest createRequest(NewSessionPayload payload) {
  StringBuilder builder = new StringBuilder();
  try {
    payload.writeTo(builder);
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }

  HttpRequest request = new HttpRequest(POST, "/se/grid/distributor/session");
  request.setContent(utf8String(builder.toString()));

  return request;
}
 
Example 8
Source File: GetLogsOfType.java    From selenium with Apache License 2.0 5 votes vote down vote up
@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 9
Source File: RemoteNode.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<CreateSessionResponse> newSession(CreateSessionRequest sessionRequest) {
  Require.nonNull("Capabilities for session", sessionRequest);

  HttpRequest req = new HttpRequest(POST, "/se/grid/node/session");
  HttpTracing.inject(tracer, tracer.getCurrentContext(), req);
  req.setContent(asJson(sessionRequest));

  HttpResponse res = client.execute(req);

  return Optional.ofNullable(Values.get(res, CreateSessionResponse.class));
}
 
Example 10
Source File: RemoteSessionMap.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public boolean add(Session session) {
  Require.nonNull("Session", session);

  HttpRequest request = new HttpRequest(POST, "/se/grid/session");
  request.setContent(asJson(session));

  return makeRequest(request, Boolean.class);
}
 
Example 11
Source File: UploadFileTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowAnExceptionIfMoreThanOneFileIsSent() 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 baseDir = Files.createTempDir();
  touch(baseDir, "example");
  touch(baseDir, "unwanted");
  String encoded = Zip.zip(baseDir);

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

  try {
    new ErrorHandler(false).throwIfResponseFailed(
        new Json().toType(string(response), Response.class),
        100);
    fail("Should not get this far");
  } catch (WebDriverException ignored) {
    // Expected
  }
}
 
Example 12
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void treatsNullPathAsRoot_unrecognizedCommand() {
  codec.defineCommand("num", GET, "/");

  byte[] data = "{\"char\":\"水\"}".getBytes(UTF_8);
  HttpRequest request = new HttpRequest(POST, null);
  request.setHeader(CONTENT_TYPE, JSON_UTF_8.withoutParameters().toString());
  request.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
  request.setContent(bytes(data));

  assertThatExceptionOfType(UnsupportedCommandException.class)
      .isThrownBy(() -> codec.decode(request));
}
 
Example 13
Source File: CreateSessionTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAcceptAW3CPayload() throws URISyntaxException {
  String payload = json.toJson(ImmutableMap.of(
      "capabilities", ImmutableMap.of(
          "alwaysMatch", ImmutableMap.of("cheese", "brie"))));

  HttpRequest request = new HttpRequest(POST, "/session");
  request.setContent(utf8String(payload));

  URI uri = new URI("http://example.com");

  Node node = LocalNode.builder(
    DefaultTestTracer.createTracer(),
      new GuavaEventBus(),
      uri,
      uri,
      null)
      .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))
      .build();

  CreateSessionResponse sessionResponse = node.newSession(
      new CreateSessionRequest(
          ImmutableSet.of(W3C),
          stereotype,
          ImmutableMap.of()))
      .orElseThrow(() -> new AssertionError("Unable to create session"));

  Map<String, Object> all = json.toType(
      new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),
      MAP_TYPE);

  // Ensure that there's no status field (as this is used by the protocol handshake to determine
  // whether the session is using the JWP or the W3C dialect.
  assertThat(all.containsKey("status")).isFalse();

  // Now check the fields required by the spec
  Map<?, ?> value = (Map<?, ?>) all.get("value");
  assertThat(value.get("sessionId")).isInstanceOf(String.class);
  assertThat(value.get("capabilities")).isInstanceOf(Map.class);
}
 
Example 14
Source File: ProtocolHandshake.java    From selenium with Apache License 2.0 5 votes vote down vote up
private Optional<Result> createSession(HttpClient client, InputStream newSessionBlob, long size) {
  // Create the http request and send it
  HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");

  HttpResponse response;
  long start = System.currentTimeMillis();

  request.setHeader(CONTENT_LENGTH, String.valueOf(size));
  request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
  request.setContent(() -> newSessionBlob);

  response = client.execute(request);
  long time = System.currentTimeMillis() - start;

  // Ignore the content type. It may not have been set. Strictly speaking we're not following the
  // W3C spec properly. Oh well.
  Map<?, ?> blob;
  try {
    blob = new Json().toType(string(response), Map.class);
  } catch (JsonException e) {
    throw new WebDriverException(
        "Unable to parse remote response: " + string(response), e);
  }

  InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(
      time,
      response.getStatus(),
      blob);

  return Stream.of(
      new W3CHandshakeResponse().getResponseFunction(),
      new JsonWireProtocolResponse().getResponseFunction())
      .map(func -> func.apply(initialResponse))
      .filter(Objects::nonNull)
      .findFirst();
}
 
Example 15
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: JsonHttpCommandCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeRequestWithUtf16Encoding() {
  codec.defineCommand("num", POST, "/one");

  byte[] data = "{\"char\":\"水\"}".getBytes(UTF_16);
  HttpRequest request = new HttpRequest(POST, "/one");
  request.setHeader(CONTENT_TYPE, JSON_UTF_8.withCharset(UTF_16).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 vote down vote up
@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 19
Source File: CreateSessionTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void ifOnlyJWPPayloadSentResponseShouldBeJWPOnlyIfJWPConfigured()
    throws URISyntaxException {
  String payload = json.toJson(ImmutableMap.of(
      "desiredCapabilities", ImmutableMap.of("cheese", "brie")));

  HttpRequest request = new HttpRequest(POST, "/session");
  request.setContent(utf8String(payload));

  URI uri = new URI("http://example.com");

  Node node = LocalNode.builder(
    DefaultTestTracer.createTracer(),
      new GuavaEventBus(),
      uri,
      uri,
      null)
      .add(stereotype, new TestSessionFactory((id, caps) -> new Session(id, uri, caps)))
      .build();

  CreateSessionResponse sessionResponse = node.newSession(
      new CreateSessionRequest(
          ImmutableSet.of(OSS),
          stereotype,
          ImmutableMap.of()))
      .orElseThrow(() -> new AssertionError("Unable to create session"));

  Map<String, Object> all = json.toType(
      new String(sessionResponse.getDownstreamEncodedResponse(), UTF_8),
      MAP_TYPE);

  // The status field is used by local ends to determine whether or not the session is a JWP one.
  assertThat(all.get("status")).matches(obj -> ((Number) obj).intValue() == ErrorCodes.SUCCESS);

  // The session id is a top level field
  assertThat(all.get("sessionId")).isInstanceOf(String.class);

  // And the value should contain the capabilities.
  assertThat(all.get("value")).isInstanceOf(Map.class);
}
 
Example 20
Source File: AbstractHttpCommandCodec.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequest encode(Command command) {
  String name = aliases.getOrDefault(command.getName(), command.getName());
  CommandSpec spec = nameToSpec.get(name);
  if (spec == null) {
    throw new UnsupportedCommandException(command.getName());
  }
  Map<String, ?> parameters = amendParameters(command.getName(), command.getParameters());
  String uri = buildUri(name, command.getSessionId(), parameters, spec);

  HttpRequest request = new HttpRequest(spec.method, uri);

  if (HttpMethod.POST == spec.method) {

    String content = json.toJson(parameters);
    byte[] data = content.getBytes(UTF_8);

    request.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
    request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
    request.setContent(bytes(data));
  }

  if (HttpMethod.GET == spec.method) {
    request.setHeader(CACHE_CONTROL, "no-cache");
  }

  return request;
}