org.openqa.selenium.remote.ErrorCodes Java Examples

The following examples show how to use org.openqa.selenium.remote.ErrorCodes. 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: WebDriverServletTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void doesNotRedirectForNewSessionsRequestedViaCrossDomainRpc()
    throws IOException, ServletException {
  Map<String, Object> json = ImmutableMap.of(
      "method", "POST",
      "path", "/session",
      "data", ImmutableMap.of(
          "desiredCapabilities", ImmutableMap.of(
              CapabilityType.BROWSER_NAME, BrowserType.FIREFOX,
              CapabilityType.VERSION, true)));
  FakeHttpServletResponse response = sendCommand("POST", "/xdrpc", json);

  assertEquals(HttpServletResponse.SC_OK, response.getStatus());
  assertEquals("application/json; charset=utf-8",
               response.getHeader("content-type"));

  Map<String, Object> jsonResponse = this.json.toType(response.getBody(), MAP_TYPE);
  assertEquals(ErrorCodes.SUCCESS, ((Number) jsonResponse.get("status")).intValue());
  assertNotNull(jsonResponse.get("sessionId"));

  Map<?, ?> value = (Map<?, ?>) jsonResponse.get("value");
  // values: browsername, version, remote session id.
  assertEquals(value.toString(), 3, value.entrySet().size());
  assertEquals(BrowserType.FIREFOX, value.get(CapabilityType.BROWSER_NAME));
  assertTrue((Boolean) value.get(CapabilityType.VERSION));
}
 
Example #3
Source File: WebDriverServletTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void handlesWellFormedAndSuccessfulCrossDomainRpcs()
    throws IOException, ServletException {
  final SessionId sessionId = createSession();

  WebDriver driver = testSessions.get(sessionId).getWrappedDriver();

  Map<String, Object> json = ImmutableMap.of(
      "method", "POST",
      "path", String.format("/session/%s/url", sessionId),
      "data", ImmutableMap.of("url", "http://www.google.com"));
  FakeHttpServletResponse response = sendCommand("POST", "/xdrpc", json);

  verify(driver).get("http://www.google.com");
  assertEquals(HttpServletResponse.SC_OK, response.getStatus());
  assertEquals("application/json; charset=utf-8",
               response.getHeader("content-type"));

  Map<String, Object> jsonResponse = this.json.toType(response.getBody(), MAP_TYPE);
  assertEquals(ErrorCodes.SUCCESS, ((Number) jsonResponse.get("status")).intValue());
  assertEquals(sessionId.toString(), jsonResponse.get("sessionId"));
  assertNull(jsonResponse.get("value"));
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: ExceptionHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUnwrapAnExecutionException() {
  Exception noSession = new SessionNotCreatedException("This does not exist");
  Exception e = new ExecutionException(noSession);
  HttpResponse response = new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"));

  Map<String, Object> err = new Json().toType(string(response), MAP_TYPE);
  Map<?, ?> value = (Map<?, ?>) err.get("value");

  assertEquals(ErrorCodes.SESSION_NOT_CREATED, ((Number) err.get("status")).intValue());
  assertEquals("session not created", value.get("error"));
}
 
Example #11
Source File: ExceptionHandlerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: WebDriverServletTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void handlesInvalidCommandsToRootOfDriverService()
    throws IOException, ServletException {
  // Command path will be null in servlet API when request is to the context root (e.g. /wd/hub).
  FakeHttpServletResponse response = sendCommand("POST", null, ImmutableMap.of());

  // An Unknown Command has an HTTP status code of 404. Fact.
  assertEquals(404, response.getStatus());

  Map<String, Object> jsonResponse = json.toType(response.getBody(), MAP_TYPE);
  assertEquals(ErrorCodes.UNKNOWN_COMMAND, ((Number) jsonResponse.get("status")).intValue());

  Map<?, ?> value = (Map<?, ?>) jsonResponse.get("value");
  assertThat(value.get("message")).isInstanceOf(String.class);
}
 
Example #13
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecognizeNumericStatus() {
  Response response = new Json().toType(
      "{\"status\":0,\"value\":\"cheese\"}",
      Response.class);

  assertThat(response.getStatus().intValue()).isEqualTo(0);
  assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0));
  String value = (String) response.getValue();
  assertThat(value).isEqualTo("cheese");
}
 
Example #14
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 #15
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecognizeStringStatus() {
  Response response = new Json().toType(
      "{\"status\":\"success\",\"value\":\"cheese\"}",
      Response.class);

  assertThat(response.getStatus().intValue()).isEqualTo(0);
  assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0));
  String value = (String) response.getValue();
  assertThat(value).isEqualTo("cheese");
}
 
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: 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 #18
Source File: ResultConfig.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Throwable getRootExceptionCause(Throwable originalException) {
  Throwable toReturn = originalException;
  if (originalException instanceof UndeclaredThrowableException) {
    // An exception was thrown within an invocation handler. Not smart.
    // Extract the original exception
    toReturn = originalException.getCause().getCause();
  }

  // When catching an exception here, it is most likely wrapped by
  // several other exceptions. Peel the layers and use the original
  // exception as the one to return to the client. That is the most
  // likely to contain informative data about the error.
  // This is a safety measure to make sure this loop is never endless
  List<Throwable> chain = new ArrayList<>(10);
  for (Throwable current = toReturn; current != null && chain.size() < 10; current =
      current.getCause()) {
    chain.add(current);
  }

  if (chain.isEmpty()) {
    return null;
  }

  // If the root cause came from another server implementing the wire protocol, there might
  // not have been enough information to fully reconstitute its error, in which case we'll
  // want to return the last 2 causes - with the outer error providing context to the
  // true root cause. These case are identified by the root cause not being mappable to a
  // standard WebDriver error code, but its wrapper is mappable.
  //
  // Of course, if we only have one item in our chain, go ahead and return.
  ErrorCodes ec = new ErrorCodes();
  Iterator<Throwable> reversedChain = Lists.reverse(chain).iterator();
  Throwable rootCause = reversedChain.next();
  if (!reversedChain.hasNext() || ec.isMappableError(rootCause)) {
    return rootCause;
  }
  Throwable nextCause = reversedChain.next();
  return ec.isMappableError(nextCause) ? nextCause : rootCause;
}
 
Example #19
Source File: JsonTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConvertInvalidSelectorError() {
  Response response = new Json().toType(
      "{\"state\":\"invalid selector\",\"message\":\"invalid xpath selector\"}",
      Response.class);
  assertThat(response.getStatus().intValue()).isEqualTo(32);
  assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(32));
}
 
Example #20
Source File: CapabilityResponseEncoder.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> encodeJsonWireProtocol(
    SessionId id,
    Capabilities capabilities,
    Map<String, Object> metadata) {
  return ImmutableMap.<String, Object>builder()
      .putAll(metadata)
      .put("status", ErrorCodes.SUCCESS)
      .put("sessionId", id)
      .put("value", capabilities)
      .build();

}
 
Example #21
Source File: W3CHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void noErrorNoCry() {
  Map<String, Object> data = new HashMap<>();
  data.put("value", "cheese");

  HttpResponse response = createValidResponse(HTTP_OK, data);

  Response decoded = new W3CHttpResponseCodec().decode(response);

  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.SUCCESS);
  assertThat(decoded.getState()).isEqualTo("success");
  assertThat(decoded.getValue()).isEqualTo("cheese");
}
 
Example #22
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 #23
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 #24
Source File: JsonHttpResponseCodecTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Test
public void decodeNonJsonResponse_5xx() {
  HttpResponse response = new HttpResponse();
  response.setStatus(HTTP_INTERNAL_ERROR);
  response.setContent(utf8String("{\"foobar\"}"));

  Response decoded = codec.decode(response);
  assertThat(decoded.getStatus().intValue()).isEqualTo(ErrorCodes.UNHANDLED_ERROR);
  assertThat(decoded.getValue()).isEqualTo("{\"foobar\"}");
}
 
Example #25
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 #26
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 #27
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;
}