Java Code Examples for com.github.javaparser.ast.CompilationUnit#toString()

The following examples show how to use com.github.javaparser.ast.CompilationUnit#toString() . 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: JavaSourceUtils.java    From dolphin with Apache License 2.0 6 votes vote down vote up
public static String mergeContent(CompilationUnit one, CompilationUnit two) throws Exception {

        // 包声明不同,返回null
        if (!one.getPackage().equals(two.getPackage())) return null;

        CompilationUnit cu = new CompilationUnit();

        // add package declaration to the compilation unit
        PackageDeclaration pd = new PackageDeclaration();
        pd.setName(one.getPackage().getName());
        cu.setPackage(pd);

        // check and merge file comment;
        Comment fileComment = mergeSelective(one.getComment(), two.getComment());
        cu.setComment(fileComment);

        // check and merge imports
        List<ImportDeclaration> ids = mergeListNoDuplicate(one.getImports(), two.getImports());
        cu.setImports(ids);

        // check and merge Types
        List<TypeDeclaration> types = mergeTypes(one.getTypes(), two.getTypes());
        cu.setTypes(types);

        return cu.toString();
    }
 
Example 2
Source File: CDIDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public String objectMapperInjectorSource(String packageName) {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/rules/KogitoQuarkusObjectMapper.java"));
    clazz.setPackageDeclaration( packageName );
    return clazz.toString();
}
 
Example 3
Source File: SpringDependencyInjectionAnnotator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public String objectMapperInjectorSource(String packageName) {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/rules/KogitoSpringObjectMapper.java"));
    clazz.setPackageDeclaration( packageName );
    return clazz.toString();
}
 
Example 4
Source File: MessageProducerGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageProducerTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get();
    template.setName(resourceClazzName);        
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).forEach(md -> md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType())));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct"));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("marshall")).forEach(md -> {
        md.getParameters().stream().filter(p -> p.getNameAsString().equals(EVENT_DATA_VAR)).forEach(p -> p.setType(trigger.getDataType()));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
    });
    
    if (useInjection()) {
        annotator.withApplicationComponent(template);
        
        FieldDeclaration emitterField = template.findFirst(FieldDeclaration.class).filter(fd -> fd.getVariable(0).getNameAsString().equals("emitter")).get();
        annotator.withInjection(emitterField);
        annotator.withOutgoingMessage(emitterField, trigger.getName());
        emitterField.getVariable(0).setType(annotator.emitterType("String"));
        
        MethodDeclaration produceMethod = template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("produce")).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find produce methos in MessageProducerTemplate"));
        BlockStmt body = new BlockStmt();
        MethodCallExpr sendMethodCall = new MethodCallExpr(new NameExpr("emitter"), "send");
        annotator.withMessageProducer(sendMethodCall, trigger.getName(), new MethodCallExpr(new ThisExpr(), "marshall").addArgument(new NameExpr("pi")).addArgument(new NameExpr(EVENT_DATA_VAR)));
        body.addStatement(sendMethodCall);
        produceMethod.setBody(body);

        template.findAll(FieldDeclaration.class,
                fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents"));
        
    } 
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 5
Source File: MessageDataEventGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public String generate() {
    CompilationUnit clazz = parse(
            this.getClass().getResourceAsStream("/class-templates/MessageDataEventTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).orElseThrow(() -> new IllegalStateException("Cannot find the class in MessageDataEventTemplate"));
    template.setName(resourceClazzName);  
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, trigger.getDataType()));
    template.findAll(ConstructorDeclaration.class).stream().forEach(cd -> cd.setName(resourceClazzName));

    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 6
Source File: QueryEndpointGenerator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public String generate() {
    CompilationUnit cu = parse(
            this.getClass().getResourceAsStream("/class-templates/rules/RestQueryTemplate.java"));
    cu.setPackageDeclaration(query.getNamespace());

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

    cu.findAll(StringLiteralExpr.class).forEach(this::interpolateStrings);

    FieldDeclaration ruleUnitDeclaration = clazz
            .getFieldByName("ruleUnit")
            .orElseThrow(() -> new NoSuchElementException("ClassOrInterfaceDeclaration doesn't contain a field named ruleUnit!"));
    setUnitGeneric(ruleUnitDeclaration.getElementType());
    if (annotator != null) {
        annotator.withInjection(ruleUnitDeclaration);
    }

    String returnType = getReturnType(clazz);
    generateConstructors(clazz);
    generateQueryMethods(cu, clazz, returnType);
    clazz.getMembers().sort(new BodyDeclarationComparator());
    return cu.toString();
}
 
Example 7
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 8
Source File: CompilationUnitMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
/**
 * Util method to make source merge more convenient
 *
 * @param first  merge params, specifically for the existing source
 * @param second merge params, specifically for the new source
 * @return merged result
 * @throws ParseException cannot parse the input params
 */
public static String merge(String first, String second) throws ParseException {
  JavaParser.setDoNotAssignCommentsPreceedingEmptyLines(false);

  CompilationUnit cu1 = JavaParser.parse(new StringReader(first), true);
  CompilationUnit cu2 = JavaParser.parse(new StringReader(second), true);
  AbstractMerger<CompilationUnit> merger = AbstractMerger.getMerger(CompilationUnit.class);
  CompilationUnit result = merger.merge(cu1, cu2);
  return result.toString();
}
 
Example 9
Source File: MyShellCallback.java    From mapper-generator-javafx with Apache License 2.0 4 votes vote down vote up
/**
 * merge java bean
 *
 * @param newCompilationUnit      新的
 * @param existingCompilationUnit 旧的
 * @return merge 后的
 */
private String mergerFile(CompilationUnit newCompilationUnit, CompilationUnit existingCompilationUnit) {

    Optional<PackageDeclaration> newPackageDeclaration = newCompilationUnit.getPackageDeclaration();
    newPackageDeclaration.ifPresent(existingCompilationUnit::setPackageDeclaration);

    //合并imports
    NodeList<ImportDeclaration> oldImports = existingCompilationUnit.getImports();
    NodeList<ImportDeclaration> newImports = newCompilationUnit.getImports();
    oldImports.addAll(newImports);
    Set<ImportDeclaration> importSet = new HashSet<>(oldImports);

    existingCompilationUnit.setImports(new NodeList<>(importSet));

    //处理类 comment
    TypeDeclaration<?> newType = newCompilationUnit.getTypes().get(0);
    TypeDeclaration<?> existType = existingCompilationUnit.getTypes().get(0);
    newType.getComment().ifPresent(existType::setComment);

    List<FieldDeclaration> existFields = existType.getFields();
    List<FieldDeclaration> newFields = newType.getFields();

    //合并fields
    int size = newFields.size();
    for (int i = 0; i < size; i++) {
        FieldDeclaration existField = newFields.get(0);
        VariableDeclarator existVar = existField.getVariables().get(0);
        for (FieldDeclaration newField : existFields) {
            VariableDeclarator newVar = newField.getVariables().get(0);
            // 名称相同
            if (newVar.getName().equals(existVar.getName())) {
                // 名称相同 且 类型相同
                if (newVar.getTypeAsString().equals(existVar.getTypeAsString())) {
                    newType.getComment().ifPresent(existType::setComment);
                } else {

                }
            }
        }

        //合并methods
    }

    return existingCompilationUnit.toString();
}
 
Example 10
Source File: MessageConsumerGenerator.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/MessageConsumerTemplate.java"));
    clazz.setPackageDeclaration(process.getPackageName());
    clazz.addImport(modelfqcn);

    ClassOrInterfaceDeclaration template = clazz.findFirst(ClassOrInterfaceDeclaration.class).get();
    template.setName(resourceClazzName);        
    
    template.findAll(ClassOrInterfaceType.class).forEach(cls -> interpolateTypes(cls, dataClazzName));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("configure")).forEach(md -> md.addAnnotation("javax.annotation.PostConstruct"));
    template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("consume")).forEach(md -> { 
        interpolateArguments(md, "String");
        md.findAll(StringLiteralExpr.class).forEach(str -> str.setString(str.asString().replace("$Trigger$", trigger.getName())));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataEventType$", messageDataEventClassName)));
        md.findAll(ClassOrInterfaceType.class).forEach(t -> t.setName(t.getNameAsString().replace("$DataType$", trigger.getDataType())));
    });
    template.findAll(MethodCallExpr.class).forEach(this::interpolateStrings);
    
    if (useInjection()) {
        annotator.withApplicationComponent(template);
        
        template.findAll(FieldDeclaration.class,
                         fd -> isProcessField(fd)).forEach(fd -> annotator.withNamedInjection(fd, processId));
        template.findAll(FieldDeclaration.class,
                         fd -> isApplicationField(fd)).forEach(fd -> annotator.withInjection(fd));

        template.findAll(FieldDeclaration.class,
                fd -> fd.getVariable(0).getNameAsString().equals("useCloudEvents")).forEach(fd -> annotator.withConfigInjection(fd, "kogito.messaging.as-cloudevents"));
        
        template.findAll(MethodDeclaration.class).stream().filter(md -> md.getNameAsString().equals("consume")).forEach(md -> annotator.withIncomingMessage(md, trigger.getName()));
    } else {
        template.findAll(FieldDeclaration.class,
                         fd -> isProcessField(fd)).forEach(fd -> initializeProcessField(fd, template));
        
        template.findAll(FieldDeclaration.class,
                         fd -> isApplicationField(fd)).forEach(fd -> initializeApplicationField(fd, template));
    }
    template.getMembers().sort(new BodyDeclarationComparator());
    return clazz.toString();
}
 
Example 11
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 12
Source File: ModelMetaData.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generate() {
    CompilationUnit modelClass = compilationUnit();
    return modelClass.toString();
}
 
Example 13
Source File: UserTaskModelMetaData.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generateInput() {
    CompilationUnit modelClass = compilationUnitInput();
    return modelClass.toString();
}
 
Example 14
Source File: UserTaskModelMetaData.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
public String generateOutput() {
    CompilationUnit modelClass = compilationUnitOutput();
    return modelClass.toString();
}