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

The following examples show how to use com.github.javaparser.ast.body.MethodDeclaration#addAnnotation() . 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: 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 2
Source File: KieModuleModelMethod.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String toGetKieModuleModelMethod() {
    MethodDeclaration methodDeclaration = new MethodDeclaration(nodeList(publicModifier()), new ClassOrInterfaceType(null, kieModuleModelCanonicalName), "getKieModuleModel");
    methodDeclaration.setBody(stmt);
    methodDeclaration.addAnnotation( "Override" );
    return methodDeclaration.toString();
}
 
Example 3
Source File: DMNRestResourceGenerator.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(this.getClass().getResourceAsStream("/class-templates/DMNRestResourceTemplate.java"));
    clazz.setPackageDeclaration(this.packageName);

    ClassOrInterfaceDeclaration template = clazz
            .findFirst(ClassOrInterfaceDeclaration.class)
            .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!"));

    template.setName(resourceClazzName);

    template.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);
    template.findAll(MethodDeclaration.class).forEach(this::interpolateMethods);

    interpolateInputType(template);

    if (useInjection()) {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(fd -> annotator.withInjection(fd));
    } else {
        template.findAll(FieldDeclaration.class,
                         CodegenUtils::isApplicationField).forEach(this::initializeApplicationField);
    }

    MethodDeclaration dmnMethod = template.findAll(MethodDeclaration.class, x -> x.getName().toString().equals("dmn")).get(0);
    for (DecisionService ds : dmnModel.getDefinitions().getDecisionService()) {
        if (ds.getAdditionalAttributes().keySet().stream().anyMatch(qn -> qn.getLocalPart().equals("dynamicDecisionService"))) {
            continue;
        }

        MethodDeclaration clonedMethod = dmnMethod.clone();
        String name = CodegenStringUtil.escapeIdentifier("decisionService_" + ds.getName());
        clonedMethod.setName(name);
        MethodCallExpr evaluateCall = clonedMethod.findFirst(MethodCallExpr.class, x -> x.getNameAsString().equals("evaluateAll")).orElseThrow(() -> new RuntimeException("Template was modified!"));
        evaluateCall.setName(new SimpleName("evaluateDecisionService"));
        evaluateCall.addArgument(new StringLiteralExpr(ds.getName()));
        clonedMethod.addAnnotation(new SingleMemberAnnotationExpr(new Name("javax.ws.rs.Path"), new StringLiteralExpr("/" + ds.getName())));
        ReturnStmt returnStmt = clonedMethod.findFirst(ReturnStmt.class).orElseThrow(() -> new RuntimeException("Template was modified!"));
        if (ds.getOutputDecision().size() == 1) {
            MethodCallExpr rewrittenReturnExpr = returnStmt.findFirst(MethodCallExpr.class,
                                                                      mce -> mce.getNameAsString().equals("extractContextIfSucceded"))
                                                           .orElseThrow(() -> new RuntimeException("Template was modified!"));
            rewrittenReturnExpr.setName("extractSingletonDSIfSucceded");
        }

        if (useMonitoring) {
            addMonitoringToMethod(clonedMethod, ds.getName());
        }

        template.addMember(clonedMethod);
    }

    if (useMonitoring) {
        addMonitoringImports(clazz);
        ClassOrInterfaceDeclaration exceptionClazz = clazz.findFirst(ClassOrInterfaceDeclaration.class, x -> "DMNEvaluationErrorExceptionMapper".equals(x.getNameAsString()))
                .orElseThrow(() -> new NoSuchElementException("Could not find DMNEvaluationErrorExceptionMapper, template has changed."));
        addExceptionMetricsLogging(exceptionClazz, nameURL);
        addMonitoringToMethod(dmnMethod, nameURL);
    }

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 4
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;
}