Java Code Examples for com.github.javaparser.ast.body.MethodDeclaration#setType()

The following examples show how to use com.github.javaparser.ast.body.MethodDeclaration#setType() . 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: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private String getReturnType(ClassOrInterfaceDeclaration clazz) {
    MethodDeclaration toResultMethod = clazz.getMethodsByName("toResult").get(0);
    String returnType;
    if (query.getBindings().size() == 1) {
        Map.Entry<String, Class<?>> binding = query.getBindings().entrySet().iterator().next();
        String name = binding.getKey();
        returnType = binding.getValue().getCanonicalName();

        Statement statement = toResultMethod
                .getBody()
                .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
                .getStatement(0);

        statement.findFirst(CastExpr.class).orElseThrow(() -> new NoSuchElementException("CastExpr not found in template.")).setType(returnType);
        statement.findFirst(StringLiteralExpr.class).orElseThrow(() -> new NoSuchElementException("StringLiteralExpr not found in template.")).setString(name);
    } else {
        returnType = "Result";
        generateResultClass(clazz, toResultMethod);
    }

    toResultMethod.setType(returnType);
    return returnType;
}
 
Example 2
Source File: MethodDeclarationMerger.java    From dolphin with Apache License 2.0 6 votes vote down vote up
@Override public MethodDeclaration doMerge(MethodDeclaration first, MethodDeclaration second) {

    MethodDeclaration md = new MethodDeclaration();
    md.setName(first.getName());
    md.setType(mergeSingle(first.getType(), second.getType()));
    md.setJavaDoc(mergeSingle(first.getJavaDoc(), second.getJavaDoc()));
    md.setModifiers(mergeModifiers(first.getModifiers(), second.getModifiers()));

    md.setDefault(first.isDefault() || second.isDefault());
    md.setArrayCount(Math.max(first.getArrayCount(), second.getArrayCount()));

    md.setAnnotations(mergeCollections(first.getAnnotations(), second.getAnnotations()));

    md.setThrows(mergeListNoDuplicate(first.getThrows(), second.getThrows(), false));
    md.setParameters(mergeCollectionsInOrder(first.getParameters(), second.getParameters()));
    md.setTypeParameters(mergeCollectionsInOrder(first.getTypeParameters(), second.getTypeParameters()));

    md.setBody(mergeSingle(first.getBody(), second.getBody()));

    return md;
  }
 
Example 3
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 6 votes vote down vote up
public BodyDeclaration<?> toMethodDeclaration() {
  MethodDeclaration methodDecl = new MethodDeclaration().setName(name).setPublic(true).setStatic(true);
  if (type == null) {
    methodDecl.setType("Event<Void>").getBody().get().addStatement(
        String.format("return new Event<>(\"%s.%s\");", domain.name, name));
  } else {
    methodDecl.setType(String.format("Event<%s>", getFullJavaType()));
    if (type instanceof VoidType) {
      methodDecl.getBody().get().addStatement(
          String.format("return new Event<>(\"%s.%s\", input -> null);", domain.name, name));
    } else if (type instanceof ObjectType) {
      methodDecl.getBody().get().addStatement(String.format(
          "return new Event<>(\"%s.%s\", input -> %s);",
          domain.name, name, type.getMapper()));
    } else {
      methodDecl.getBody().get().addStatement(String.format(
          "return new Event<>(\"%s.%s\", ConverterFunctions.map(\"%s\", %s));",
          domain.name, name, type.getName(), type.getTypeToken()));
    }
  }
  return methodDecl;
}
 
Example 4
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 5
Source File: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void generateQueryMethods(CompilationUnit cu, ClassOrInterfaceDeclaration clazz, String returnType) {
    boolean hasDI = annotator != null;
    MethodDeclaration queryMethod = clazz.getMethodsByName("executeQuery").get(0);
    queryMethod.getParameter(0).setType(ruleUnit.getCanonicalName() + (hasDI ? "" : "DTO"));
    setGeneric(queryMethod.getType(), returnType);

    Statement statement = queryMethod
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(0);
    statement.findAll(VariableDeclarator.class).forEach(decl -> setUnitGeneric(decl.getType()));
    statement.findAll( MethodCallExpr.class ).forEach( m -> m.addArgument( hasDI ? "unitDTO" : "unitDTO.get()" ) );

    Statement returnStatement = queryMethod
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(1);
    returnStatement.findAll(VariableDeclarator.class).forEach(decl -> setGeneric(decl.getType(), returnType));

    MethodDeclaration queryMethodSingle = clazz.getMethodsByName("executeQueryFirst").get(0);
    queryMethodSingle.getParameter(0).setType(ruleUnit.getCanonicalName() + (hasDI ? "" : "DTO"));
    queryMethodSingle.setType(toNonPrimitiveType(returnType));

    Statement statementSingle = queryMethodSingle
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(0);
    statementSingle.findAll(VariableDeclarator.class).forEach(decl -> setGeneric(decl.getType(), returnType));

    Statement returnMethodSingle = queryMethodSingle
            .getBody()
            .orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
            .getStatement(1);
    returnMethodSingle.findAll(VariableDeclarator.class).forEach(decl -> decl.setType(toNonPrimitiveType(returnType)));

    if (useMonitoring) {
        addMonitoringToResource(cu, new MethodDeclaration[]{queryMethod, queryMethodSingle}, endpointName);
    }
}
 
Example 6
Source File: RuleUnitDTOSourceClass.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public String generate() {
    CompilationUnit cu = new CompilationUnit();
    cu.setPackageDeclaration(packageName);

    ClassOrInterfaceDeclaration dtoClass = cu.addClass(targetCanonicalName, Modifier.Keyword.PUBLIC);
    dtoClass.addImplementedType(String.format("java.util.function.Supplier<%s>", ruleUnit.getSimpleName()));

    MethodDeclaration supplier = dtoClass.addMethod("get", Modifier.Keyword.PUBLIC);
    supplier.addAnnotation(Override.class);
    supplier.setType(ruleUnit.getSimpleName());
    BlockStmt supplierBlock = supplier.createBody();
    supplierBlock.addStatement(String.format("%s unit = new %s();", ruleUnit.getSimpleName(), ruleUnit.getSimpleName()));

    for (RuleUnitVariable unitVarDeclaration : ruleUnit.getUnitVarDeclarations()) {
        FieldProcessor fieldProcessor = new FieldProcessor(unitVarDeclaration, ruleUnitHelper );
        FieldDeclaration field = fieldProcessor.createField();
        supplierBlock.addStatement(fieldProcessor.fieldInitializer());
        dtoClass.addMember(field);
        field.createGetter();
        field.createSetter();
    }

    supplierBlock.addStatement("return unit;");

    return cu.toString();
}
 
Example 7
Source File: JavaInterfaceBuilderImpl.java    From chrome-devtools-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public void addMethod(
    String name, String description, List<MethodParam> methodParams, String returnType) {
  MethodDeclaration methodDeclaration = declaration.addMethod(name);
  methodDeclaration.setBody(null);

  if (StringUtils.isNotEmpty(description)) {
    methodDeclaration.setJavadocComment(
        JavadocUtils.createJavadocComment(description, INDENTATION_TAB));
  }

  if (StringUtils.isNotEmpty(returnType)) {
    methodDeclaration.setType(returnType);
  }

  if (CollectionUtils.isNotEmpty(methodParams)) {
    for (MethodParam methodParam : methodParams) {
      Parameter parameter =
          methodDeclaration.addAndGetParameter(methodParam.getType(), methodParam.getName());

      if (CollectionUtils.isNotEmpty(methodParam.getAnnotations())) {
        for (MethodParam.Annotation annotation : methodParam.getAnnotations()) {
          Optional<AnnotationExpr> currentAnnotation =
              parameter.getAnnotationByName(annotation.getName());
          if (!currentAnnotation.isPresent()) {
            if (StringUtils.isNotEmpty(annotation.getValue())) {
              parameter.addSingleMemberAnnotation(
                  annotation.getName(), new StringLiteralExpr(annotation.getValue()));
            } else {
              parameter.addMarkerAnnotation(annotation.getName());
            }

            if (!DEPRECATED_ANNOTATION.equals(annotation.getName())) {
              addImport(annotationsPackage, annotation.getName());
            }
          }
        }
      }
    }
  }
}
 
Example 8
Source File: CdpClientGenerator.java    From selenium with Apache License 2.0 4 votes vote down vote up
public MethodDeclaration toMethodDeclaration() {
  MethodDeclaration methodDecl = new MethodDeclaration().setName(name).setPublic(true).setStatic(true);
  if (description != null) {
    methodDecl.setJavadocComment(description);
  }
  if (experimental) {
    methodDecl.addAnnotation(Beta.class);
  }
  if (deprecated) {
    methodDecl.addAnnotation(Deprecated.class);
  }

  methodDecl.setType(String.format("Command<%s>", type.getJavaType()));

  parameters.forEach(param -> {
    if (param.optional) {
      methodDecl.addParameter(String.format("java.util.Optional<%s>", param.type.getJavaType()), param.name);
    } else {
      methodDecl.addParameter(param.type.getJavaType(), param.name);
    }
  });

  BlockStmt body = methodDecl.getBody().get();

  parameters.stream().filter(parameter -> !parameter.optional)
      .map(parameter -> parameter.name)
      .forEach(name -> body.addStatement(
          String.format("java.util.Objects.requireNonNull(%s, \"%s is required\");", name, name)));
  body.addStatement("ImmutableMap.Builder<String, Object> params = ImmutableMap.builder();");
  parameters.forEach(parameter -> {
    if (parameter.optional) {
      body.addStatement(String.format("%s.ifPresent(p -> params.put(\"%s\", p));", parameter.name, parameter.name));
    } else {
      body.addStatement(String.format("params.put(\"%s\", %s);", parameter.name, parameter.name));
    }
  });

  if (type instanceof VoidType) {
    body.addStatement(String.format(
        "return new Command<>(\"%s.%s\", params.build());", domain.name, name));
  } else if (type instanceof ObjectType) {
    body.addStatement(String.format(
        "return new Command<>(\"%s.%s\", params.build(), input -> %s);",
        domain.name, name, type.getMapper()));
  } else {
    body.addStatement(String.format(
        "return new Command<>(\"%s.%s\", params.build(), ConverterFunctions.map(\"%s\", %s));",
        domain.name, name, type.getName(), type.getTypeToken()));
  }

  return methodDecl;
}
 
Example 9
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;
}
 
Example 10
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;
}