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

The following examples show how to use org.openqa.selenium.remote.http.HttpResponse#getStatus() . 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: RemoteNode.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Override
public Result check() {
  HttpRequest req = new HttpRequest(GET, "/status");

  try {
    HttpResponse res = client.execute(req);

    if (res.getStatus() == 200) {
      return new Result(true, externalUri + " is ok");
    }
    return new Result(
        false,
        String.format(
            "An error occurred reading the status of %s: %s",
            externalUri,
            string(res)));
  } catch (RuntimeException e) {
    return new Result(
        false,
        "Unable to determine node status: " + e.getMessage());
  }
}
 
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: ChromiumDevToolsLocator.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static Optional<URI> getCdpEndPoint(
  HttpClient.Factory clientFactory,
  URI reportedUri) {
  Require.nonNull("HTTP client factory", clientFactory);
  Require.nonNull("DevTools URI", reportedUri);

  ClientConfig config = ClientConfig.defaultConfig().baseUri(reportedUri);
  HttpClient client = clientFactory.createClient(config);

  HttpResponse res = client.execute(new HttpRequest(GET, "/json/version"));
  if (res.getStatus() != HTTP_OK) {
    return Optional.empty();
  }

  Map<String, Object> versionData = JSON.toType(string(res), MAP_TYPE);
  Object raw = versionData.get("webSocketDebuggerUrl");

  if (!(raw instanceof String)) {
    return Optional.empty();
  }

  String debuggerUrl = (String) raw;
  try {
    return Optional.of(new URI(debuggerUrl));
  } catch (URISyntaxException e) {
    LOG.warning("Invalid URI for endpoint " + raw);
    return Optional.empty();
  }
}
 
Example 4
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 5
Source File: DeleteContainer.java    From selenium with Apache License 2.0 5 votes vote down vote up
public void apply(ContainerId id) {
  Require.nonNull("Container id", id);

  HttpResponse res = client.execute(
    new HttpRequest(DELETE, "/v1.40/containers/" + id)
      .addHeader("Content-Length", "0")
      .addHeader("Content-Type", "text/plain"));
  if (res.getStatus() != HTTP_OK) {
    LOG.warning("Unable to delete container " + id);
  }
}
 
Example 6
Source File: Values.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static <T> T get(HttpResponse response, Type typeOfT) {
  try (Reader reader = reader(response);
       JsonInput input = JSON.newInput(reader)) {

    // Alright then. We might be dealing with the object we expected, or we might have an
    // error. We shall assume that a non-200 http status code indicates that something is
    // wrong.
    if (response.getStatus() != 200) {
      throw ERRORS.decode(JSON.toType(string(response), MAP_TYPE));
    }

    if (Void.class.equals(typeOfT) && input.peek() == END) {
      return null;
    }

    input.beginObject();

    while (input.hasNext()) {
      if ("value".equals(input.nextName())) {
        return input.read(typeOfT);
      } else {
        input.skipValue();
      }
    }

    throw new IllegalStateException("Unable to locate value: " + string(response));
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example 7
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;
}