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

The following examples show how to use org.openqa.selenium.remote.http.HttpResponse#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: AbstractHttpResponseCodec.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes the given response as a HTTP response message. This method is guaranteed not to throw.
 *
 * @param response The response to encode.
 * @return The encoded response.
 */
@Override
public HttpResponse encode(Supplier<HttpResponse> factory, Response response) {
  int status = response.getStatus() == ErrorCodes.SUCCESS
               ? HTTP_OK
               : HTTP_INTERNAL_ERROR;

  byte[] data = json.toJson(getValueToEncode(response)).getBytes(UTF_8);

  HttpResponse httpResponse = factory.get();
  httpResponse.setStatus(status);
  httpResponse.setHeader(CACHE_CONTROL, "no-cache");
  httpResponse.setHeader(EXPIRES, "Thu, 01 Jan 1970 00:00:00 GMT");
  httpResponse.setHeader(CONTENT_LENGTH, String.valueOf(data.length));
  httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());
  httpResponse.setContent(bytes(data));

  return httpResponse;
}
 
Example 2
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldIncludeJsonWireProtocolCapabilities() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> json = getRequestPayloadAsMap(client);

  assertThat(json.get("desiredCapabilities")).isEqualTo(EMPTY_MAP);
}
 
Example 3
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldIncludeSpecCompliantW3CCapabilities() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> json = getRequestPayloadAsMap(client);

  List<Map<String, Object>> caps = mergeW3C(json);

  assertThat(caps).isNotEmpty();
}
 
Example 4
Source File: WrapExceptions.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public HttpHandler apply(HttpHandler next) {
  return req -> {
    try {
      return next.execute(req);
    } catch (Throwable cause) {
      HttpResponse res = new HttpResponse();
      res.setStatus(errors.getHttpStatusCode(cause));

      res.addHeader("Content-Type", JSON_UTF_8.toString());
      res.addHeader("Cache-Control", "none");

      res.setContent(asJson(errors.encode(cause)));

      return res;
    }
  };
}
 
Example 5
Source File: ReactorMessages.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static HttpResponse toSeleniumResponse(Response response) {
  HttpResponse toReturn = new HttpResponse();

  toReturn.setStatus(response.getStatusCode());

  toReturn.setContent(! response.hasResponseBody()
                      ? empty()
                      : memoize(response::getResponseBodyAsStream));

  response.getHeaders().names().forEach(
      name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));

  return toReturn;
}
 
Example 6
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeJsonResponseWithTrailingNullBytes() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String("{\"status\":0,\"value\":\"foo\"}\0\0"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS);
  assertThat(decoded.getValue()).isEqualTo("foo");
}
 
Example 7
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeUtf16EncodedResponse() {
  HttpResponse httpResponse = new HttpResponse();
  httpResponse.setStatus(200);
  httpResponse.setHeader(CONTENT_TYPE, JSON_UTF_8.withCharset(UTF_16).toString());
  httpResponse.setContent(string("{\"status\":0,\"value\":\"水\"}", UTF_16));

  Response response = codec.decode(httpResponse);
  assertThat(response.getValue()).isEqualTo("水");
}
 
Example 8
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeJsonResponseMissingContentType() {
  Response response = new Response();
  response.setStatus(ErrorCodes.SUCCESS);
  response.setValue(ImmutableMap.of("color", "red"));

  HttpResponse httpResponse = new HttpResponse();
  httpResponse.setStatus(HTTP_OK);
  httpResponse.setContent(asJson(response));

  Response decoded = codec.decode(httpResponse);
  assertThat(decoded.getStatus()).isEqualTo(response.getStatus());
  assertThat(decoded.getSessionId()).isEqualTo(response.getSessionId());
  assertThat(decoded.getValue()).isEqualTo(response.getValue());
}
 
Example 9
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeNonJsonResponse_4xx() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_BAD_REQUEST);
  response.setContent(utf8String("{\"foobar\"}"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNKNOWN_COMMAND);
  assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
}
 
Example 10
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private HttpResponse createValidResponse(int statusCode, Map<String, ?> data) {
  byte[] contents = new Json().toJson(data).getBytes(UTF_8);

  HttpResponse response = new HttpResponse();
  response.setStatus(statusCode);
  response.addHeader("Content-Type", "application/json; charset=utf-8");
  response.addHeader("Cache-Control", "no-cache");
  response.addHeader("Content-Length", String.valueOf(contents.length));
  response.setContent(bytes(contents));

  return response;
}
 
Example 11
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotIncludeMappingOfANYPlatform() throws IOException {
  Capabilities caps = new ImmutableCapabilities(
      "platform", "ANY",
      "platformName", "ANY",
      "browserName", "cake");

  Map<String, Object> params = singletonMap("desiredCapabilities", caps);
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);

  mergeW3C(handshakeRequest)
      .forEach(capabilities -> {
        assertThat(capabilities.get("browserName")).isEqualTo("cake");
        assertThat(capabilities.get("platformName")).isNull();
        assertThat(capabilities.get("platform")).isNull();
      });
}
 
Example 12
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotCreateFirstMatchForNonW3CCaps() throws IOException {
  Capabilities caps = new ImmutableCapabilities(
      "cheese", EMPTY_MAP,
      "moz:firefoxOptions", EMPTY_MAP,
      "browserName", "firefox");

  Map<String, Object> params = singletonMap("desiredCapabilities", caps);
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);

  List<Map<String, Object>> w3c = mergeW3C(handshakeRequest);

  assertThat(w3c).hasSize(1);
  // firstMatch should not contain an object for Chrome-specific capabilities. Because
  // "chromeOptions" is not a W3C capability name, it is stripped from any firstMatch objects.
  // The resulting empty object should be omitted from firstMatch; if it is present, then the
  // Firefox-specific capabilities might be ignored.
  assertThat(w3c.get(0))
      .containsKey("moz:firefoxOptions")
      .containsEntry("browserName", "firefox");
}
 
Example 13
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotIncludeNonProtocolExtensionKeys() throws IOException {
  Capabilities caps = new ImmutableCapabilities(
      "se:option", "cheese",
      "option", "I like sausages",
      "browserName", "amazing cake browser");

  Map<String, Object> params = singletonMap("desiredCapabilities", caps);
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  new ProtocolHandshake().createSession(client, command);

  Map<String, Object> handshakeRequest = getRequestPayloadAsMap(client);

  Object rawCaps = handshakeRequest.get("capabilities");
  assertThat(rawCaps).isInstanceOf(Map.class);

  Map<?, ?> capabilities = (Map<?, ?>) rawCaps;

  assertThat(capabilities.get("alwaysMatch")).isNull();
  List<Map<?, ?>> first = (List<Map<?, ?>>) capabilities.get("firstMatch");

  // We don't care where they are, but we want to see "se:option" and not "option"
  Set<String> keys = first.stream()
      .map(Map::keySet)
      .flatMap(Collection::stream)
      .map(String::valueOf).collect(Collectors.toSet());
  assertThat(keys)
      .contains("browserName", "se:option")
      .doesNotContain("options");
}
 
Example 14
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldParseWireProtocolNewSessionResponse() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"sessionId\": \"23456789\", \"status\": 0, \"value\": {}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);
  assertThat(result.getDialect()).isEqualTo(Dialect.OSS);
}
 
Example 15
Source File: ProtocolHandshakeTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldParseW3CNewSessionResponse() throws IOException {
  Map<String, Object> params = singletonMap("desiredCapabilities", new ImmutableCapabilities());
  Command command = new Command(null, DriverCommand.NEW_SESSION, params);

  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_OK);
  response.setContent(utf8String(
      "{\"value\": {\"sessionId\": \"23456789\", \"capabilities\": {}}}"));
  RecordingHttpClient client = new RecordingHttpClient(response);

  ProtocolHandshake.Result result = new ProtocolHandshake().createSession(client, command);
  assertThat(result.getDialect()).isEqualTo(Dialect.W3C);
}
 
Example 16
Source File: NettyMessages.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static HttpResponse toSeleniumResponse(Response response) {
  HttpResponse toReturn = new HttpResponse();

  toReturn.setStatus(response.getStatusCode());

  toReturn.setContent(! response.hasResponseBody()
                      ? empty()
                      : memoize(response::getResponseBodyAsStream));

  response.getHeaders().names().forEach(
      name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));

  return toReturn;
}
 
Example 17
Source File: ProtocolConverterTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldAliasAComplexCommand() throws IOException {
  SessionId sessionId = new SessionId("1234567");

  // Downstream is JSON, upstream is W3C. This way we can force "isDisplayed" to become JS
  // execution.
  HttpHandler handler = new ProtocolConverter(
      tracer,
      HttpClient.Factory.createDefault().createClient(new URL("http://example.com/wd/hub")),
      OSS,
      W3C) {
    @Override
    protected HttpResponse makeRequest(HttpRequest request) {
      assertEquals(String.format("/session/%s/execute/sync", sessionId), request.getUri());
      Map<String, Object> params = json.toType(string(request), MAP_TYPE);

      assertEquals(
          ImmutableList.of(
              ImmutableMap.of(W3C.getEncodedElementKey(), "4567890")),
          params.get("args"));

      HttpResponse response = new HttpResponse();

      response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());
      response.setHeader("Cache-Control", "none");

      Map<String, Object> obj = ImmutableMap.of(
          "sessionId", sessionId.toString(),
          "status", 0,
          "value", true);
      String payload = json.toJson(obj);
      response.setContent(utf8String(payload));

      return response;
    }
  };

  Command command = new Command(
      sessionId,
      DriverCommand.IS_ELEMENT_DISPLAYED,
      ImmutableMap.of("id", "4567890"));

  HttpRequest w3cRequest = new JsonHttpCommandCodec().encode(command);

  HttpResponse resp = handler.execute(w3cRequest);

  assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));
  assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());

  Map<String, Object> parsed = json.toType(string(resp), MAP_TYPE);
  assertNull(parsed.get("sessionId"));
  assertTrue(parsed.containsKey("value"));
  assertEquals(true, parsed.get("value"));
}
 
Example 18
Source File: ProtocolConverterTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldRoundTripASimpleCommand() throws IOException {
  SessionId sessionId = new SessionId("1234567");

  HttpHandler handler = new ProtocolConverter(
      tracer,
      HttpClient.Factory.createDefault().createClient(new URL("http://example.com/wd/hub")),
      W3C,
      OSS) {
    @Override
    protected HttpResponse makeRequest(HttpRequest request) {
      HttpResponse response = new HttpResponse();

      response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());
      response.setHeader("Cache-Control", "none");

      Map<String, Object> obj = new HashMap<>();
      obj.put("sessionId", sessionId.toString());
      obj.put("status", 0);
      obj.put("value", null);
      String payload = json.toJson(obj);
      response.setContent(utf8String(payload));

      return response;
    }
  };

  Command command = new Command(
      sessionId,
      DriverCommand.GET,
      ImmutableMap.of("url", "http://example.com/cheese"));

  HttpRequest w3cRequest = new W3CHttpCommandCodec().encode(command);

  HttpResponse resp = handler.execute(w3cRequest);

  assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));
  assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());

  Map<String, Object> parsed = json.toType(string(resp), MAP_TYPE);
  assertNull(parsed.toString(), parsed.get("sessionId"));
  assertTrue(parsed.toString(), parsed.containsKey("value"));
  assertNull(parsed.toString(), parsed.get("value"));
}
 
Example 19
Source File: UploadHandler.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest req) throws UncheckedIOException {
  HttpResponse res = new HttpResponse();
  res.setHeader("Content-Type", "text/html");
  res.setStatus(HTTP_OK);

  StringBuilder content = new StringBuilder();

  // I mean. Seriously. *sigh*
  try {
    String decoded = URLDecoder.decode(
        string(req),
        Charset.defaultCharset().displayName());

    String[] splits = decoded.split("\r\n");

    // First line is the boundary marker
    String boundary = splits[0];
    List<Map<String, Object>> allParts = new ArrayList<>();
    Map<String, Object> values = new HashMap<>();
    boolean inHeaders = true;
    for (int i = 1; i < splits.length; i++) {
      if ("".equals(splits[i])) {
        inHeaders = false;
        continue;
      }

      if (splits[i].startsWith(boundary)) {
        inHeaders = true;
        allParts.add(values);
        continue;
      }

      if (inHeaders && splits[i].toLowerCase().startsWith("content-disposition:")) {
        for (String keyValue : Splitter.on(';').trimResults().omitEmptyStrings().split(splits[i])) {
          Matcher matcher = Pattern.compile("(\\S+)\\s*=.*\"(.*?)\".*").matcher(keyValue);
          if (matcher.find()) {
            values.put(matcher.group(1), matcher.group(2));
          }
        }
      } else if (!inHeaders) {
        String c = (String) values.getOrDefault("content", "");
        c += splits[i];
        values.put("content", c);
      }
    }

    Object value = allParts.stream()
        .filter(map -> "upload".equals(map.get("name")))
        .findFirst()
        .map(map -> map.get("content"))
        .orElseThrow(() -> new RuntimeException("Cannot find uploaded data"));

    content.append(value);
  } catch (UnsupportedEncodingException e) {
    throw new UncheckedIOException(e);
  }

  // Slow down the upload so we can verify WebDriver waits.
  try {
    Thread.sleep(2500);
  } catch (InterruptedException ignored) {
  }

  content.append("<script>window.top.window.onUploadDone();</script>");

  res.setContent(utf8String(content.toString()));

  return res;
}
 
Example 20
Source File: ProtocolConverterTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldConvertAnException() throws IOException {
  // Json upstream, w3c downstream
  SessionId sessionId = new SessionId("1234567");

  HttpHandler handler = new ProtocolConverter(
      tracer,
      HttpClient.Factory.createDefault().createClient(new URL("http://example.com/wd/hub")),
      W3C,
      OSS) {
    @Override
    protected HttpResponse makeRequest(HttpRequest request) {
      HttpResponse response = new HttpResponse();

      response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());
      response.setHeader("Cache-Control", "none");

     String payload = new Json().toJson(
         ImmutableMap.of(
             "sessionId", sessionId.toString(),
             "status", UNHANDLED_ERROR,
             "value", new WebDriverException("I love cheese and peas")));
      response.setContent(utf8String(payload));
      response.setStatus(HTTP_INTERNAL_ERROR);

      return response;
    }
  };

  Command command = new Command(
      sessionId,
      DriverCommand.GET,
      ImmutableMap.of("url", "http://example.com/cheese"));

  HttpRequest w3cRequest = new W3CHttpCommandCodec().encode(command);

  HttpResponse resp = handler.execute(w3cRequest);

  assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));
  assertEquals(HTTP_INTERNAL_ERROR, resp.getStatus());

  Map<String, Object> parsed = json.toType(string(resp), MAP_TYPE);
  assertNull(parsed.get("sessionId"));
  assertTrue(parsed.containsKey("value"));
  @SuppressWarnings("unchecked") Map<String, Object> value =
      (Map<String, Object>) parsed.get("value");
  System.out.println("value = " + value.keySet());
  assertEquals("unknown error", value.get("error"));
  assertTrue(((String) value.get("message")).startsWith("I love cheese and peas"));
}