org.openqa.selenium.json.JsonInput Java Examples

The following examples show how to use org.openqa.selenium.json.JsonInput. 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: TeeReaderTest.java    From selenium with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDuplicateStreams() {
  String expected = "{\"key\": \"value\"}";
  Reader source = new StringReader(expected);

  StringWriter writer = new StringWriter();

  Reader tee = new TeeReader(source, writer);

  try (JsonInput reader = new Json().newInput(tee)) {

    reader.beginObject();
    assertEquals("key", reader.nextName());
    reader.skipValue();
    reader.endObject();

    assertEquals(expected, writer.toString());
  }
}
 
Example #2
Source File: NewSessionPayload.java    From selenium with Apache License 2.0 6 votes vote down vote up
private Collection<Map<String, Object>> getFirstMatches() throws IOException {
  CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
  try (Reader reader = charSource.openBufferedStream();
       JsonInput input = json.newInput(reader)) {
    input.beginObject();
    while (input.hasNext()) {
      String name = input.nextName();
      if ("capabilities".equals(name)) {
        input.beginObject();
        while (input.hasNext()) {
          name = input.nextName();
          if ("firstMatch".equals(name)) {
            return input.read(LIST_OF_MAPS_TYPE);
          } else {
            input.skipValue();
          }
        }
        input.endObject();
      } else {
        input.skipValue();
      }
    }
  }
  return null;
}
 
Example #3
Source File: NewSessionPayload.java    From selenium with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getAlwaysMatch() throws IOException {
  CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
  try (Reader reader = charSource.openBufferedStream();
       JsonInput input = json.newInput(reader)) {
    input.beginObject();
    while (input.hasNext()) {
      String name = input.nextName();
      if ("capabilities".equals(name)) {
        input.beginObject();
        while (input.hasNext()) {
          name = input.nextName();
          if ("alwaysMatch".equals(name)) {
            return input.read(MAP_TYPE);
          } else {
            input.skipValue();
          }
        }
        input.endObject();
      } else {
        input.skipValue();
      }
    }
  }
  return null;
}
 
Example #4
Source File: NewSessionPayload.java    From selenium with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getOss() throws IOException {
  CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
  try (Reader reader = charSource.openBufferedStream();
       JsonInput input = json.newInput(reader)) {
    input.beginObject();
    while (input.hasNext()) {
      String name = input.nextName();
      if ("desiredCapabilities".equals(name)) {
        return input.read(MAP_TYPE);
      } else {
        input.skipValue();
      }
    }
  }
  return null;
}
 
Example #5
Source File: NewSessionPayload.java    From selenium with Apache License 2.0 6 votes vote down vote up
private void writeMetaData(JsonOutput out) throws IOException {
  CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
  try (Reader reader = charSource.openBufferedStream();
       JsonInput input = json.newInput(reader)) {
    input.beginObject();
    while (input.hasNext()) {
      String name = input.nextName();
      switch (name) {
        case "capabilities":
        case "desiredCapabilities":
        case "requiredCapabilities":
          input.skipValue();
          break;

        default:
          out.name(name);
          out.write(input.read(Object.class));
          break;
      }
    }
  }
}
 
Example #6
Source File: SeleniumConfig.java    From Selenium-Foundation with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Path createNodeConfig(String capabilities, URL hubUrl) throws IOException {
    String nodeConfigPath = getNodeConfigPath().toString();
    String configPathBase = nodeConfigPath.substring(0, nodeConfigPath.length() - 5);
    String hashCode = String.format("%08X", Objects.hash(capabilities, hubUrl));
    Path filePath = Paths.get(configPathBase + "-" + hashCode + ".json");
    if (filePath.toFile().createNewFile()) {
        JsonInput input = new Json().newInput(new StringReader(JSON_HEAD + capabilities + JSON_TAIL));
        List<MutableCapabilities> capabilitiesList = GridNodeConfiguration.loadFromJSON(input).capabilities;
        GridNodeConfiguration nodeConfig = GridNodeConfiguration.loadFromJSON(nodeConfigPath);
        nodeConfig.capabilities = capabilitiesList;
        nodeConfig.hub = hubUrl.toString();
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(filePath.toFile()))) {
            out.write(new Json().toJson(nodeConfig).getBytes(StandardCharsets.UTF_8));
        }
    }
    return filePath;
}
 
Example #7
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 6 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(name);

  String propertyName = decapitalize(name);
  classDecl.addField(getJavaType(), propertyName).setPrivate(true).setFinal(true);

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  constructor.addParameter(getJavaType(), propertyName);
  constructor.getBody().addStatement(String.format(
      "this.%s = java.util.Objects.requireNonNull(%s, \"Missing value for %s\");",
      propertyName, propertyName, name
  ));

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(name);
  fromJson.addParameter(JsonInput.class, "input");
  fromJson.getBody().get().addStatement(String.format("return %s;", getMapper()));

  MethodDeclaration toString = classDecl.addMethod("toString").setPublic(true);
  toString.setType(String.class);
  toString.getBody().get().addStatement(String.format("return %s.toString();", propertyName));

  return classDecl;
}
 
Example #8
Source File: CreateSessionResponse.java    From selenium with Apache License 2.0 6 votes vote down vote up
private static CreateSessionResponse fromJson(JsonInput input) {
  Session session = null;
  byte[] downstreamResponse = null;

  input.beginObject();
  while (input.hasNext()) {
    switch (input.nextName()) {
      case "downstreamEncodedResponse":
        downstreamResponse = Base64.getDecoder().decode(input.nextString());
        break;

      case "session":
        session = input.read(Session.class);
        break;

      default:
        input.skipValue();
        break;
    }
  }
  input.endObject();

  return new CreateSessionResponse(session, downstreamResponse);
}
 
Example #9
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 6 votes vote down vote up
public void dumpTo(Path target) {
  CompilationUnit unit = new CompilationUnit();
  unit.setPackageDeclaration("org.openqa.selenium.devtools." + domain.name.toLowerCase() + ".model");
  unit.addImport(Beta.class);
  unit.addImport(JsonInput.class);
  unit.addType(toTypeDeclaration());

  Path typeFile = target.resolve(capitalize(name) + ".java");
  ensureFileDoesNotExists(typeFile);

  try {
    Files.write(typeFile, unit.toString().getBytes());
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example #10
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 6 votes vote down vote up
public void dumpTo(Path target) {
  if (type instanceof ObjectType) {
    CompilationUnit unit = new CompilationUnit();
    unit.setPackageDeclaration(getNamespace());
    unit.addImport(Beta.class);
    unit.addImport(JsonInput.class);
    unit.addType(toTypeDeclaration());

    Path eventFile = target.resolve(capitalize(name) + ".java");
    ensureFileDoesNotExists(eventFile);

    try {
      Files.write(eventFile, unit.toString().getBytes());
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
}
 
Example #11
Source File: DistributorStatus.java    From selenium with Apache License 2.0 6 votes vote down vote up
private static DistributorStatus fromJson(JsonInput input) {
  Set<NodeSummary> nodes = null;

  input.beginObject();
  while (input.hasNext()) {
    switch (input.nextName()) {
      case "nodes":
        nodes = input.read(SUMMARIES_TYPES);
        break;

      default:
        input.skipValue();
    }
  }
  input.endObject();

  return new DistributorStatus(nodes);
}
 
Example #12
Source File: ConverterFunctions.java    From selenium with Apache License 2.0 6 votes vote down vote up
public static <X> Function<JsonInput, X> map(final String keyName, Type typeOfX) {
  Require.nonNull("Key name", keyName);
  Require.nonNull("Type to convert to", typeOfX);

  return input -> {
    X value = null;

    input.beginObject();
    while (input.hasNext()) {
      String name = input.nextName();
      if (keyName.equals(name)) {
        value = input.read(typeOfX);
      } else {
        input.skipValue();
      }
    }
    input.endObject();

    return value;
  };
}
 
Example #13
Source File: NewAppiumSessionPayload.java    From java-client with Apache License 2.0 6 votes vote down vote up
private @Nullable Collection<Map<String, Object>> getFirstMatch() throws IOException {
    CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
    try (Reader reader = charSource.openBufferedStream();
         JsonInput input = json.newInput(reader)) {
        input.beginObject();
        while (input.hasNext()) {
            String name = input.nextName();
            if (CAPABILITIES.equals(name)) {
                input.beginObject();
                while (input.hasNext()) {
                    name = input.nextName();
                    if (FIRST_MATCH.equals(name)) {
                        return input.read(LIST_OF_MAPS_TYPE);
                    }
                    input.skipValue();
                }
                input.endObject();
            } else {
                input.skipValue();
            }
        }
    }
    return null;
}
 
Example #14
Source File: NewAppiumSessionPayload.java    From java-client with Apache License 2.0 6 votes vote down vote up
private @Nullable Map<String, Object> getAlwaysMatch() throws IOException {
    CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
    try (Reader reader = charSource.openBufferedStream();
         JsonInput input = json.newInput(reader)) {
        input.beginObject();
        while (input.hasNext()) {
            String name = input.nextName();
            if (CAPABILITIES.equals(name)) {
                input.beginObject();
                while (input.hasNext()) {
                    name = input.nextName();
                    if (ALWAYS_MATCH.equals(name)) {
                        return input.read(MAP_TYPE);
                    }
                    input.skipValue();
                }
                input.endObject();
            } else {
                input.skipValue();
            }
        }
    }
    return null;
}
 
Example #15
Source File: NewAppiumSessionPayload.java    From java-client with Apache License 2.0 6 votes vote down vote up
private void writeMetaData(JsonOutput out) throws IOException {
    CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
    try (Reader reader = charSource.openBufferedStream();
         JsonInput input = json.newInput(reader)) {
        input.beginObject();
        while (input.hasNext()) {
            String name = input.nextName();
            switch (name) {
                case CAPABILITIES:
                case DESIRED_CAPABILITIES:
                case REQUIRED_CAPABILITIES:
                    input.skipValue();
                    break;

                default:
                    out.name(name);
                    out.write(input.read(Object.class));
                    break;
            }
        }
    }
}
 
Example #16
Source File: DistributorStatus.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Map<Capabilities, Integer> readCapabilityCounts(JsonInput input) {
  Map<Capabilities, Integer> toReturn = new HashMap<>();

  input.beginArray();
  while (input.hasNext()) {
    Capabilities caps = null;
    int count = 0;
    input.beginObject();
    while (input.hasNext()) {
      switch (input.nextName()) {
        case "capabilities":
          caps = input.read(Capabilities.class);
          break;

        case "count":
          count = input.nextNumber().intValue();
          break;

        default:
          input.skipValue();
          break;
      }
    }
    input.endObject();

    toReturn.put(caps, count);
  }
  input.endArray();

  return toReturn;
}
 
Example #17
Source File: CreateSessionRequest.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static CreateSessionRequest fromJson(JsonInput input) {
  Set<Dialect> downstreamDialects = null;
  Capabilities capabilities = null;
  Map<String, Object> metadata = null;

  input.beginObject();
  while (input.hasNext()) {
    switch (input.nextName()) {
      case "capabilities":
        capabilities = input.read(Capabilities.class);
        break;

      case "downstreamDialects":
        downstreamDialects = input.read(new TypeToken<Set<Dialect>>(){}.getType());
        break;

      case "metadata":
        metadata = input.read(MAP_TYPE);
        break;

      default:
        input.skipValue();
    }
  }
  input.endObject();

  return new CreateSessionRequest(downstreamDialects, capabilities, metadata);
}
 
Example #18
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 #19
Source File: RemoteNode.java    From selenium with Apache License 2.0 5 votes vote down vote up
@Override
public NodeStatus getStatus() {
  HttpRequest req = new HttpRequest(GET, "/status");
  HttpTracing.inject(tracer, tracer.getCurrentContext(), req);

  HttpResponse res = client.execute(req);

  try (Reader reader = reader(res);
       JsonInput in = JSON.newInput(reader)) {
    in.beginObject();

    // Skip everything until we find "value"
    while (in.hasNext()) {
      if ("value".equals(in.nextName())) {
        in.beginObject();

        while (in.hasNext()) {
          if ("node".equals(in.nextName())) {
            return in.read(NodeStatus.class);
          } else {
            in.skipValue();
          }
        }

        in.endObject();
      } else {
        in.skipValue();
      }
    }
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }

  throw new IllegalStateException("Unable to read status");
}
 
Example #20
Source File: Command.java    From selenium with Apache License 2.0 5 votes vote down vote up
private Command(String method, Map<String, Object> params, Function<JsonInput, X> mapper, boolean sendsResponse) {
  this.method = Require.nonNull("Method name", method);
  this.params = ImmutableMap.copyOf(Require.nonNull("Command parameters", params));
  this.mapper = Require.nonNull("Mapper for result", mapper);

  this.sendsResponse = sendsResponse;
}
 
Example #21
Source File: ImageSummary.java    From selenium with Apache License 2.0 5 votes vote down vote up
static ImageSummary fromJson(JsonInput input) {
  input.beginObject();

  ImageId id = null;
  List<String> repoTags = new ArrayList<>();

  while (input.hasNext()) {
    switch (input.nextName()) {
      case "Id":
        id = new ImageId(input.nextString());
        break;

      case "RepoTags":
        // This is a required field, but can be null. *sigh*
        List<String> tags = input.read(LIST_OF_STRING);
        if (tags != null) {
          repoTags = tags;
        }
        break;

      default:
        input.skipValue();
        break;
    }
  }

  input.endObject();

  return new ImageSummary(id, repoTags);
}
 
Example #22
Source File: FileExtension.java    From selenium with Apache License 2.0 5 votes vote down vote up
private String readIdFromManifestJson(File root) {
  final String MANIFEST_JSON_FILE = "manifest.json";
  File manifestJsonFile = new File(root, MANIFEST_JSON_FILE);
  try (Reader reader = new FileReader(manifestJsonFile);
       JsonInput json = new Json().newInput(reader)) {
    String addOnId = null;

    Map<String, Object> manifestObject = json.read(MAP_TYPE);
    if (manifestObject.get("applications") instanceof Map) {
      Map<?, ?> applicationObj = (Map<?, ?>) manifestObject.get("applications");
      if (applicationObj.get("gecko") instanceof Map) {
        Map<?, ?> geckoObj = (Map<?, ?>) applicationObj.get("gecko");
        if (geckoObj.get("id") instanceof String) {
          addOnId = ((String) geckoObj.get("id")).trim();
        }
      }
    }

    if (addOnId == null || addOnId.isEmpty()) {
      addOnId = ((String) manifestObject.get("name")).replaceAll(" ", "") +
        "@" + manifestObject.get("version");
    }

    return addOnId;
  } catch (FileNotFoundException e1) {
    throw new WebDriverException("Unable to file manifest.json in xpi file");
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example #23
Source File: Command.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Command fromJson(JsonInput input) {
  input.beginObject();

  SessionId sessionId = null;
  String name = null;
  Map<String, Object> parameters = null;

  while (input.hasNext()) {
    switch (input.nextName()) {
      case "name":
        name = input.nextString();
        break;

      case "parameters":
        parameters = input.read(MAP_TYPE);
        break;

      case "sessionId":
        sessionId = input.read(SessionId.class);
        break;

      default:
        input.skipValue();
        break;
    }
  }

  input.endObject();

  return new Command(sessionId, name, parameters);
}
 
Example #24
Source File: NewAppiumSessionPayload.java    From java-client with Apache License 2.0 5 votes vote down vote up
private @Nullable Map<String, Object> getOss() throws IOException {
    CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8);
    try (Reader reader = charSource.openBufferedStream();
         JsonInput input = json.newInput(reader)) {
        input.beginObject();
        while (input.hasNext()) {
            String name = input.nextName();
            if (DESIRED_CAPABILITIES.equals(name)) {
                return input.read(MAP_TYPE);
            }
            input.skipValue();
        }
    }
    return null;
}
 
Example #25
Source File: DistributorStatus.java    From selenium with Apache License 2.0 4 votes vote down vote up
private static NodeSummary fromJson(JsonInput input) {
  UUID nodeId = null;
  URI uri = null;
  boolean up = false;
  int maxSessionCount = 0;
  Map<Capabilities, Integer> stereotypes = new HashMap<>();
  Map<Capabilities, Integer> used = new HashMap<>();

  input.beginObject();
  while (input.hasNext()) {
    switch (input.nextName()) {
      case "maxSessionCount":
        maxSessionCount = input.nextNumber().intValue();
        break;

      case "nodeId":
        nodeId = input.read(UUID.class);
        break;

      case "stereotypes":
        stereotypes = readCapabilityCounts(input);
        break;

      case "up":
        up = input.nextBoolean();
        break;

      case "uri":
        uri = input.read(URI.class);
        break;

      case "usedStereotypes":
        used = readCapabilityCounts(input);
        break;

      default:
        input.skipValue();
        break;
    }
  }

  input.endObject();

  return new NodeSummary(nodeId, uri, up, maxSessionCount, stereotypes, used);
}
 
Example #26
Source File: Command.java    From selenium with Apache License 2.0 4 votes vote down vote up
public Command(String method, Map<String, Object> params, Function<JsonInput, X> mapper) {
  this(method, params, mapper, true);
}
 
Example #27
Source File: Command.java    From selenium with Apache License 2.0 4 votes vote down vote up
Function<JsonInput, X> getMapper() {
  return mapper;
}
 
Example #28
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 4 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(capitalize(name));

  properties.stream().filter(property -> property.type instanceof EnumType).forEach(
      property -> classDecl.addMember(((EnumType) property.type).toTypeDeclaration()));

  properties.forEach(property -> classDecl.addField(
      property.getJavaType(), property.getFieldName()).setPrivate(true).setFinal(true));

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  properties.forEach(
      property -> constructor.addParameter(property.getJavaType(), property.getFieldName()));
  properties.forEach(property -> {
    if (property.optional) {
      constructor.getBody().addStatement(String.format(
          "this.%s = %s;", property.getFieldName(), property.getFieldName()));
    } else {
      constructor.getBody().addStatement(String.format(
          "this.%s = java.util.Objects.requireNonNull(%s, \"%s is required\");",
          property.getFieldName(), property.getFieldName(), property.name));
    }
  });

  properties.forEach(property -> {
    MethodDeclaration getter = classDecl.addMethod("get" + capitalize(property.name)).setPublic(true);
    getter.setType(property.getJavaType());
    if (property.description != null) {
      getter.setJavadocComment(property.description);
    }
    if (property.experimental) {
      getter.addAnnotation(Beta.class);
    }
    if (property.deprecated) {
      getter.addAnnotation(Deprecated.class);
    }
    getter.getBody().get().addStatement(String.format("return %s;", property.getFieldName()));
  });

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(capitalize(name));
  fromJson.addParameter(JsonInput.class, "input");
  BlockStmt body = fromJson.getBody().get();
  if (properties.size() > 0) {
    properties.forEach(property -> {
      if (property.optional) {
        body.addStatement(String.format("%s %s = java.util.Optional.empty();", property.getJavaType(), property.getFieldName()));
      } else {
        body.addStatement(String.format("%s %s = null;", property.getJavaType(), property.getFieldName()));
      }
    });

    body.addStatement("input.beginObject();");
    body.addStatement(
        "while (input.hasNext()) {"
        + "switch (input.nextName()) {"
        + properties.stream().map(property -> {
          String mapper = String.format(
            property.optional ? "java.util.Optional.ofNullable(%s)" : "%s",
            property.type.getMapper());

          return String.format(
            "case \"%s\":"
              + "  %s = %s;"
              + "  break;",
            property.name, property.getFieldName(), mapper);
        })
            .collect(joining("\n"))
        + "  default:\n"
        + "    input.skipValue();\n"
        + "    break;"
        + "}}");
    body.addStatement("input.endObject();");
    body.addStatement(String.format(
        "return new %s(%s);", capitalize(name),
        properties.stream().map(VariableSpec::getFieldName)
            .collect(joining(", "))));
  } else {
    body.addStatement(String.format("return new %s();", capitalize(name)));
  }

  return classDecl;
}
 
Example #29
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 4 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  EnumDeclaration enumDecl = new EnumDeclaration().setName(capitalize(name)).setPublic(true);

  values.forEach(val ->
    enumDecl.addEnumConstant(toJavaConstant(val)).addArgument(String.format("\"%s\"", val))
  );

  enumDecl.addField(String.class, "value").setPrivate(true);

  enumDecl.addConstructor()
      .addParameter(String.class, "value")
      .getBody().addStatement("this.value = value;");

  enumDecl.addMethod("fromString").setPublic(true).setStatic(true)
      .addParameter(String.class, "s")
      .setType(name)
      .getBody().get()
      .addStatement(String.format("return java.util.Arrays.stream(%s.values())\n"
                                  + ".filter(rs -> rs.value.equalsIgnoreCase(s))\n"
                                  + ".findFirst()\n"
                                  + ".orElseThrow(() -> new org.openqa.selenium.devtools.DevToolsException(\n"
                                  + "\"Given value \" + s + \" is not found within %s \"));",
                                  name, name));

  enumDecl.addMethod("toString").setPublic(true)
    .setType(String.class)
    .getBody().get()
      .addStatement("return value;");

  enumDecl.addMethod("toJson").setPublic(true)
      .setType(String.class)
      .getBody().get()
      .addStatement("return value;");

  enumDecl.addMethod("fromJson").setPrivate(true).setStatic(true)
      .setType(name)
      .addParameter(JsonInput.class, "input")
      .getBody().get()
      .addStatement("return fromString(input.nextString());");

  return enumDecl;
}
 
Example #30
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 4 votes vote down vote up
public TypeDeclaration<?> toTypeDeclaration() {
  ClassOrInterfaceDeclaration classDecl = new ClassOrInterfaceDeclaration().setName(name);

  if (type.equals("object")) {
    classDecl.addExtendedType("com.google.common.collect.ForwardingMap<String, Object>");
  }

  String propertyName = decapitalize(name);
  classDecl.addField(getJavaType(), propertyName).setPrivate(true).setFinal(true);

  ConstructorDeclaration constructor = classDecl.addConstructor().setPublic(true);
  constructor.addParameter(getJavaType(), propertyName);
  constructor.getBody().addStatement(String.format(
      "this.%s = java.util.Objects.requireNonNull(%s, \"Missing value for %s\");",
      propertyName, propertyName, name
  ));

  if (type.equals("object")) {
    MethodDeclaration delegate = classDecl.addMethod("delegate").setProtected(true);
    delegate.setType("java.util.Map<String, Object>");
    delegate.getBody().get().addStatement(String.format("return %s;", propertyName));
  }

  MethodDeclaration fromJson = classDecl.addMethod("fromJson").setPrivate(true).setStatic(true);
  fromJson.setType(name);
  fromJson.addParameter(JsonInput.class, "input");
  fromJson.getBody().get().addStatement(
      String.format("return new %s(%s);", name, getMapper()));

  MethodDeclaration toJson = classDecl.addMethod("toJson").setPublic(true);
  if (type.equals("object")) {
    toJson.setType("java.util.Map<String, Object>");
    toJson.getBody().get().addStatement(String.format("return %s;", propertyName));
  } else {
    toJson.setType(String.class);
    toJson.getBody().get().addStatement(String.format("return %s.toString();", propertyName));
  }

  MethodDeclaration toString = classDecl.addMethod("toString").setPublic(true);
  toString.setType(String.class);
  toString.getBody().get().addStatement(String.format("return %s.toString();", propertyName));

  return classDecl;
}