org.openqa.selenium.json.JsonException Java Examples

The following examples show how to use org.openqa.selenium.json.JsonException. 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: RelativeLocator.java    From selenium with Apache License 2.0 6 votes vote down vote up
private static Object asAtomLocatorParameter(Object object) {
  if (object instanceof WebElement) {
    return object;
  }

  if (!(object instanceof By)) {
    throw new IllegalArgumentException("Expected locator to be either an element or a By: " + object);
  }

  assertLocatorCanBeSerialized(object);

  Map<String, Object> raw = JSON.toType(JSON.toJson(object), MAP_TYPE);

  if (!(raw.get("using") instanceof String)) {
    throw new JsonException("Expected JSON encoded form of locator to have a 'using' field. " + raw);
  }
  if (!raw.containsKey("value")) {
    throw new JsonException("Expected JSON encoded form of locator to have a 'value' field: " + raw);
  }

  return ImmutableMap.of((String) raw.get("using"), raw.get("value"));
}
 
Example #2
Source File: NodeStatus.java    From selenium with Apache License 2.0 6 votes vote down vote up
public static NodeStatus fromJson(Map<String, Object> raw) {
  List<Active> sessions = ((Collection<?>) raw.get("sessions")).stream()
      .map(item -> {
        @SuppressWarnings("unchecked")
        Map<String, Object> converted = (Map<String, Object>) item;
        return converted;
      })
      .map(Active::fromJson)
      .collect(toImmutableList());

  try {
    return new NodeStatus(
        UUID.fromString((String) raw.get("id")),
        new URI((String) raw.get("uri")),
        ((Number) raw.get("maxSessions")).intValue(),
        readCapacityNamed(raw, "stereotypes"),
        sessions,
        ((String) raw.get("registrationSecret")));
  } catch (URISyntaxException e) {
    throw new JsonException(e);
  }
}
 
Example #3
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 #4
Source File: SessionId.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static SessionId fromJson(Object raw) {
  if (raw instanceof String) {
    return new SessionId(String.valueOf(raw));
  }

  if (raw instanceof Map) {
    Map<?, ?> map = (Map<?, ?>) raw;
    if (map.get("value") instanceof String) {
      return new SessionId(String.valueOf(map.get("value")));
    }
  }

  throw new JsonException("Unable to coerce session id from " + raw);
}
 
Example #5
Source File: CreateContainer.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Container apply(ContainerInfo info) {
  HttpResponse res = DockerMessages.throwIfNecessary(
    client.execute(
      new HttpRequest(POST, "/v1.40/containers/create")
        .addHeader("Content-Type", JSON_UTF_8)
        .setContent(asJson(info))),
    "Unable to create container: ",
    info);

  try {
    Map<String, Object> rawContainer = JSON.toType(Contents.string(res), MAP_TYPE);

    if (!(rawContainer.get("Id") instanceof String)) {
      throw new DockerException("Unable to read container id: " + rawContainer);
    }
    ContainerId id = new ContainerId((String) rawContainer.get("Id"));

    if (rawContainer.get("Warnings") instanceof Collection) {
      String allWarnings = ((Collection<?>) rawContainer.get("Warnings")).stream()
        .map(String::valueOf)
        .collect(Collectors.joining("\n", " * ", ""));

      LOG.info(String.format("Warnings while creating %s from %s: %s", id, info, allWarnings));
    }

    return new Container(protocol, id);
  } catch (JsonException | NullPointerException e) {
    throw new DockerException("Unable to create container from " + info);
  }
}
 
Example #6
Source File: VersionCommand.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Optional<DockerProtocol> getDockerProtocol() {
  try {
    HttpResponse res = handler.execute(new HttpRequest(GET, "/version"));

    if (!res.isSuccessful()) {
      return Optional.empty();
    }

    Map<String, Object> raw = JSON.toType(Contents.string(res), MAP_TYPE);

    Version maxVersion = new Version((String) raw.get("ApiVersion"));
    Version minVersion = new Version((String) raw.get("MinAPIVersion"));

    return SUPPORTED_VERSIONS.entrySet().stream()
      .filter(entry -> {
        Version version = entry.getKey();
        if (version.equalTo(maxVersion) || version.equalTo(minVersion)) {
          return true;
        }
        return version.isLessThan(maxVersion) && version.isGreaterThan(minVersion);
      })
      .map(Map.Entry::getValue)
      .map(func -> func.apply(handler))
      .findFirst();
  } catch (ClassCastException | JsonException | NullPointerException | UncheckedIOException e) {
    return Optional.empty();
  }
}
 
Example #7
Source File: JsonConfig.java    From selenium with Apache License 2.0 5 votes vote down vote up
JsonConfig(Reader reader) {
  try {
    delegate = new MapConfig(JSON.toType(Require.nonNull("JSON source", reader), MAP_TYPE));
  } catch (JsonException e) {
    throw new ConfigException("Unable to parse input", e);
  }
}
 
Example #8
Source File: DataUtils.java    From Selenium-Foundation with Apache License 2.0 3 votes vote down vote up
/**
 * Transform the specified JSON string into the specified type.
 * <p>
 * <b>NOTE</b>: For this method to work correctly, the specified type must conform to the
 * <a href=https://stackoverflow.com/a/3295517>JavaBeans</a> specification. For a simple example, see the
 * {@link com.nordstrom.automation.selenium.listeners.PlatformInterceptor.PlatformIdentity PlatformIdentity}
 * class.
 * 
 * @param <T> desired object type
 * @param json JSON object string
 * @param type target object type
 * @return new instance of the specified type
 */
public static <T> T fromString(final String json, final Type type) {
    try {
        return new Json().toType(json, type);
    } catch (JsonException e) {
        LOGGER.debug("Failed to deserialize JSON object string: " + json, e);
        return null;
    }
}