Java Code Examples for org.openqa.selenium.remote.Response#setValue()

The following examples show how to use org.openqa.selenium.remote.Response#setValue() . 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: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAttemptToConvertAnExceptionIntoAnActualExceptionInstance() {
  Response response = new Response();
  response.setStatus(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);
  WebDriverException exception = new ScriptTimeoutException("I timed out");
  response.setValue(exception);

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

  Response decoded = codec.decode(httpResponse);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.ASYNC_SCRIPT_TIMEOUT);

  WebDriverException seenException = (WebDriverException) decoded.getValue();
  assertThat(seenException.getClass()).isEqualTo(exception.getClass());
  assertThat(seenException.getMessage().startsWith(exception.getMessage())).isTrue();
}
 
Example 2
Source File: GetLogTypes.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: Responses.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a response object for a failed command execution.
 *
 * @param sessionId ID of the session that executed the command.
 * @param reason the failure reason.
 * @param screenshot a base64 png screenshot to include with the failure.
 * @return the new response object.
 */
public static Response failure(
    SessionId sessionId, Throwable reason, Optional<String> screenshot) {
  Response response = new Response();
  response.setSessionId(sessionId != null ? sessionId.toString() : null);
  response.setStatus(ERROR_CODES.toStatusCode(reason));
  response.setState(ERROR_CODES.toState(response.getStatus()));

  if (reason != null) {
    Json json = new Json();
    String raw = json.toJson(reason);
    Map<String, Object> value = json.toType(raw, MAP_TYPE);
    screenshot.ifPresent(screen -> value.put("screen", screen));
    response.setValue(value);
  }
  return response;
}
 
Example 4
Source File: Status.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Response handle() {
  Response response = new Response();
  response.setStatus(ErrorCodes.SUCCESS);
  response.setState(ErrorCodes.SUCCESS_STRING);

  BuildInfo buildInfo = new BuildInfo();

  Object info = ImmutableMap.of(
      "ready", true,
      "message", "Server is running",
      "build", ImmutableMap.of(
          "version", buildInfo.getReleaseLabel(),
          "revision", buildInfo.getBuildRevision()),
      "os", ImmutableMap.of(
          "name", System.getProperty("os.name"),
          "arch", System.getProperty("os.arch"),
          "version", System.getProperty("os.version")),
      "java", ImmutableMap.of("version", System.getProperty("java.version")));

  response.setValue(info);
  return response;
}
 
Example 5
Source File: ActiveSessionCommandExecutor.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Response execute(Command command) throws IOException {
  if (DriverCommand.NEW_SESSION.equals(command.getName())) {
    if (active) {
      throw new WebDriverException("Cannot start session twice! " + session);
    }

    active = true;

    // We already have a running session.
    Response response = new Response(session.getId());
    response.setValue(session.getCapabilities());
    return response;
  }

  // The command is about to be sent to the session, which expects it to be
  // encoded as if it has come from the downstream end, not the upstream end.
  HttpRequest request = session.getDownstreamDialect().getCommandCodec().encode(command);

  HttpResponse httpResponse = session.execute(request);

  return session.getDownstreamDialect().getResponseCodec().decode(httpResponse);
}
 
Example 6
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void convertsResponses_failure() {
  Response response = new Response();
  response.setStatus(ErrorCodes.NO_SUCH_ELEMENT);
  response.setValue(ImmutableMap.of("color", "red"));

  HttpResponse converted = codec.encode(HttpResponse::new, response);
  assertThat(converted.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR);
  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 7
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: WebDriverWaitTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIncludeRemoteInfoForWrappedDriverTimeout() throws IOException {
  Capabilities caps = new MutableCapabilities();
  Response response = new Response(new SessionId("foo"));
  response.setValue(caps.asMap());
  CommandExecutor executor = mock(CommandExecutor.class);
  when(executor.execute(any(Command.class))).thenReturn(response);

  RemoteWebDriver driver = new RemoteWebDriver(executor, caps);
  WebDriver testDriver = mock(WebDriver.class, withSettings().extraInterfaces(WrapsDriver.class));
  when(((WrapsDriver) testDriver).getWrappedDriver()).thenReturn(driver);

  TickingClock clock = new TickingClock();
  WebDriverWait wait =
      new WebDriverWait(testDriver, Duration.ofSeconds(1), Duration.ofMillis(200), clock, clock);

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(d -> false))
      .withMessageContaining("Capabilities {javascriptEnabled: true, platform: ANY, platformName: ANY}")
      .withMessageContaining("Session ID: foo");
}
 
Example 9
Source File: JsonTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void canHandleValueBeingAnArray() {
  String[] value = {"Cheese", "Peas"};

  Response response = new Response();
  response.setSessionId("bar");
  response.setValue(value);
  response.setStatus(1512);

  String json = new Json().toJson(response);
  Response converted = new Json().toType(json, Response.class);

  assertThat(response.getSessionId()).isEqualTo("bar");
  assertThat(((List<?>) converted.getValue())).hasSize(2);
  assertThat(response.getStatus().intValue()).isEqualTo(1512);
}
 
Example 10
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void roundTrip() {
  Response response = new Response();
  response.setStatus(ErrorCodes.SUCCESS);
  response.setValue(ImmutableMap.of("color", "red"));

  HttpResponse httpResponse = codec.encode(HttpResponse::new, 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 11
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 12
Source File: Responses.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a response object for a successful command execution.
 *
 * @param sessionId ID of the session that executed the command.
 * @param value the command result value.
 * @return the new response object.
 */
public static Response success(SessionId sessionId, Object value) {
  Response response = new Response();
  response.setSessionId(sessionId != null ? sessionId.toString() : null);
  response.setValue(value);
  response.setStatus(ErrorCodes.SUCCESS);
  response.setState(ErrorCodes.SUCCESS_STRING);
  return response;
}
 
Example 13
Source File: Responses.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a response object for a failed command execution.
 *
 * @param sessionId ID of the session that executed the command.
 * @param reason the failure reason.
 * @return the new response object.
 */
public static Response failure(SessionId sessionId, Throwable reason) {
  Response response = new Response();
  response.setSessionId(sessionId != null ? sessionId.toString() : null);
  response.setValue(reason);
  response.setStatus(ERROR_CODES.toStatusCode(reason));
  response.setState(ERROR_CODES.toState(response.getStatus()));
  return response;
}
 
Example 14
Source File: JsonHttpResponseCodec.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
protected Response reconstructValue(Response response) {
  try {
    errorHandler.throwIfResponseFailed(response, 0);
  } catch (Exception e) {
    response.setValue(e);
  }

  response.setValue(elementConverter.apply(response.getValue()));

  return response;
}
 
Example 15
Source File: UploadFile.java    From selenium with Apache License 2.0 5 votes vote down vote up
@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 16
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 17
Source File: W3CHttpResponseCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
public Response decode(HttpResponse encodedResponse) {
  String content = string(encodedResponse).trim();
  log.fine(String.format(
    "Decoding response. Response code was: %d and content: %s",
    encodedResponse.getStatus(),
    content));
  String contentType = nullToEmpty(encodedResponse.getHeader(CONTENT_TYPE));

  Response response = new Response();

  // Are we dealing with an error?
  // {"error":"no such alert","message":"No tab modal was open when attempting to get the dialog text"}
  if (HTTP_OK != encodedResponse.getStatus()) {
    log.fine("Processing an error");
    if (HTTP_BAD_METHOD == encodedResponse.getStatus()) {
      response.setStatus(ErrorCodes.UNKNOWN_COMMAND);
      response.setValue(content);
    } else {
      Map<String, Object> obj = json.toType(content, MAP_TYPE);

      Object w3cWrappedValue = obj.get("value");
      if (w3cWrappedValue instanceof Map && ((Map<?, ?>) w3cWrappedValue).containsKey("error")) {
        //noinspection unchecked
        obj = (Map<String, Object>) w3cWrappedValue;
      }

      String message = "An unknown error has occurred";
      if (obj.get("message") instanceof String) {
        message = (String) obj.get("message");
      }

      String error = "unknown error";
      if (obj.get("error") instanceof String) {
        error = (String) obj.get("error");
      }

      response.setState(error);
      response.setStatus(errorCodes.toStatus(error, Optional.of(encodedResponse.getStatus())));

      // For now, we'll inelegantly special case unhandled alerts.
      if ("unexpected alert open".equals(error) &&
          HTTP_INTERNAL_ERROR == encodedResponse.getStatus()) {
        String text = "";
        Object data = obj.get("data");
        if (data != null) {
          Object rawText = ((Map<?, ?>) data).get("text");
          if (rawText instanceof String) {
            text = (String) rawText;
          }
        }
        response.setValue(new UnhandledAlertException(message, text));
      } else {
        response.setValue(createException(error, message));
      }
    }
    return response;
  }

  response.setState("success");
  response.setStatus(ErrorCodes.SUCCESS);
  if (!content.isEmpty()) {
    if (contentType.startsWith("application/json") || Strings.isNullOrEmpty("")) {
      Map<String, Object> parsed = json.toType(content, MAP_TYPE);
      if (parsed.containsKey("value")) {
        Object value = parsed.get("value");
        response.setValue(value);
      } else {
        // Assume that the body of the response was the response.
        response.setValue(json.toType(content, OBJECT_TYPE));
      }
    }
  }

  if (response.getValue() instanceof String) {
    // We normalise to \n because Java will translate this to \r\n
    // if this is suitable on our platform, and if we have \r\n, java will
    // turn this into \r\r\n, which would be Bad!
    response.setValue(((String) response.getValue()).replace("\r\n", "\n"));
  }

  return response;
}
 
Example 18
Source File: W3CHttpResponseCodec.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Override
protected Response reconstructValue(Response response) {
  response.setValue(elementConverter.apply(response.getValue()));
  return response;
}