Search in sources :

Example 1 with ClassOrInterfaceDeclaration

use of org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration in project drools by kiegroup.

the class POJOGenerator method toClassDeclaration.

/**
 * @param packageDescr
 */
public static ClassOrInterfaceDeclaration toClassDeclaration(TypeDeclarationDescr typeDeclaration, PackageDescr packageDescr) {
    EnumSet<Modifier> classModifiers = EnumSet.of(Modifier.PUBLIC);
    String generatedClassName = typeDeclaration.getTypeName();
    ClassOrInterfaceDeclaration generatedClass = new ClassOrInterfaceDeclaration(classModifiers, false, generatedClassName);
    generatedClass.addImplementedType(GeneratedFact.class.getName());
    // Ref: {@link org.drools.core.factmodel.DefaultBeanClassBuilder} by default always receive is Serializable.
    generatedClass.addImplementedType(Serializable.class.getName());
    boolean hasSuper = typeDeclaration.getSuperTypeName() != null;
    if (hasSuper) {
        generatedClass.addExtendedType(typeDeclaration.getSuperTypeName());
    }
    List<AnnotationDescr> softAnnotations = new ArrayList<>();
    for (AnnotationDescr ann : typeDeclaration.getAnnotations()) {
        final String annFqn = Optional.ofNullable(ann.getFullyQualifiedName()).orElse(Optional.ofNullable(predefinedClassLevelAnnotation.get(ann.getName())).map(Class::getCanonicalName).orElse(null));
        if (annFqn != null) {
            NormalAnnotationExpr annExpr = generatedClass.addAndGetAnnotation(annFqn);
            ann.getValueMap().forEach((k, v) -> annExpr.addPair(k, getAnnotationValue(annFqn, k, v.toString())));
        } else {
            softAnnotations.add(ann);
        }
    }
    if (softAnnotations.size() > 0) {
        String softAnnDictionary = softAnnotations.stream().map(a -> "<dt>" + a.getName() + "</dt><dd>" + a.getValuesAsString() + "</dd>").collect(Collectors.joining());
        JavadocComment generatedClassJavadoc = new JavadocComment("<dl>" + softAnnDictionary + "</dl>");
        generatedClass.setJavadocComment(generatedClassJavadoc);
    }
    // No-args ctor
    generatedClass.addConstructor(Modifier.PUBLIC);
    List<Statement> equalsFieldStatement = new ArrayList<>();
    List<Statement> hashCodeFieldStatement = new ArrayList<>();
    List<String> toStringFieldStatement = new ArrayList<>();
    List<TypeFieldDescr> keyFields = new ArrayList<>();
    Collection<TypeFieldDescr> inheritedFields = findInheritedDeclaredFields(typeDeclaration, packageDescr);
    Collection<TypeFieldDescr> typeFields = typeDeclaration.getFields().values();
    if (!inheritedFields.isEmpty() || !typeDeclaration.getFields().isEmpty()) {
        ConstructorDeclaration fullArgumentsCtor = generatedClass.addConstructor(Modifier.PUBLIC);
        NodeList<Statement> ctorFieldStatement = NodeList.nodeList();
        MethodCallExpr superCall = new MethodCallExpr(null, "super");
        for (TypeFieldDescr typeFieldDescr : inheritedFields) {
            String fieldName = typeFieldDescr.getFieldName();
            addCtorArg(fullArgumentsCtor, typeFieldDescr.getPattern().getObjectType(), fieldName);
            superCall.addArgument(fieldName);
            if (typeFieldDescr.getAnnotation("key") != null) {
                keyFields.add(typeFieldDescr);
            }
        }
        ctorFieldStatement.add(new ExpressionStmt(superCall));
        int position = inheritedFields.size();
        for (TypeFieldDescr typeFieldDescr : typeFields) {
            String fieldName = typeFieldDescr.getFieldName();
            Type returnType = addCtorArg(fullArgumentsCtor, typeFieldDescr.getPattern().getObjectType(), fieldName);
            FieldDeclaration field = generatedClass.addField(returnType, fieldName, Modifier.PRIVATE);
            field.createSetter();
            field.addAndGetAnnotation(Position.class.getName()).addPair("value", "" + position++);
            MethodDeclaration getter = field.createGetter();
            equalsFieldStatement.add(generateEqualsForField(getter, fieldName));
            hashCodeFieldStatement.addAll(generateHashCodeForField(getter, fieldName));
            ctorFieldStatement.add(replaceFieldName(parseStatement("this.__fieldName = __fieldName;"), fieldName));
            toStringFieldStatement.add(format("+ {0}+{1}", quote(fieldName + "="), fieldName));
            if (typeFieldDescr.getAnnotation("key") != null) {
                keyFields.add(typeFieldDescr);
            }
        }
        fullArgumentsCtor.setBody(new BlockStmt(ctorFieldStatement));
        if (!keyFields.isEmpty() && keyFields.size() != inheritedFields.size() + typeFields.size()) {
            ConstructorDeclaration keyArgumentsCtor = generatedClass.addConstructor(Modifier.PUBLIC);
            NodeList<Statement> ctorKeyFieldStatement = NodeList.nodeList();
            MethodCallExpr keySuperCall = new MethodCallExpr(null, "super");
            ctorKeyFieldStatement.add(new ExpressionStmt(keySuperCall));
            for (TypeFieldDescr typeFieldDescr : keyFields) {
                String fieldName = typeFieldDescr.getFieldName();
                addCtorArg(keyArgumentsCtor, typeFieldDescr.getPattern().getObjectType(), fieldName);
                if (typeDeclaration.getFields().get(fieldName) != null) {
                    ctorKeyFieldStatement.add(replaceFieldName(parseStatement("this.__fieldName = __fieldName;"), fieldName));
                } else {
                    keySuperCall.addArgument(fieldName);
                }
            }
            keyArgumentsCtor.setBody(new BlockStmt(ctorKeyFieldStatement));
        }
        if (hasSuper) {
            generatedClass.addMember(generateEqualsMethod(generatedClassName, equalsFieldStatement));
            generatedClass.addMember(generateHashCodeMethod(hashCodeFieldStatement));
        }
    }
    generatedClass.addMember(generateToStringMethod(generatedClassName, toStringFieldStatement));
    return generatedClass;
}
Also used : JavaParser.parseStatement(org.drools.javaparser.JavaParser.parseStatement) ClassOrInterfaceType(org.drools.javaparser.ast.type.ClassOrInterfaceType) Primitive(org.drools.javaparser.ast.type.PrimitiveType.Primitive) JavaParser(org.drools.javaparser.JavaParser) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) HashMap(java.util.HashMap) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) NodeList.nodeList(org.drools.javaparser.ast.NodeList.nodeList) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) ArrayList(java.util.ArrayList) JavadocComment(org.drools.javaparser.ast.comments.JavadocComment) JavaParserCompiler.compileAll(org.drools.modelcompiler.builder.JavaParserCompiler.compileAll) FieldDeclaration(org.drools.javaparser.ast.body.FieldDeclaration) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr) MessageFormat.format(java.text.MessageFormat.format) Map(java.util.Map) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) FieldAccessExpr(org.drools.javaparser.ast.expr.FieldAccessExpr) ExpressionStmt(org.drools.javaparser.ast.stmt.ExpressionStmt) PrimitiveType(org.drools.javaparser.ast.type.PrimitiveType) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) Statement(org.drools.javaparser.ast.stmt.Statement) EnumSet(java.util.EnumSet) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) ConstructorDeclaration(org.drools.javaparser.ast.body.ConstructorDeclaration) PackageModel(org.drools.modelcompiler.builder.PackageModel) TypeResolver(org.kie.soup.project.datamodel.commons.types.TypeResolver) Collection(java.util.Collection) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) TypeDeclarationDescr(org.drools.compiler.lang.descr.TypeDeclarationDescr) NormalAnnotationExpr(org.drools.javaparser.ast.expr.NormalAnnotationExpr) GeneratedFact(org.drools.core.factmodel.GeneratedFact) Collectors(java.util.stream.Collectors) NameExpr(org.drools.javaparser.ast.expr.NameExpr) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) Serializable(java.io.Serializable) Type(org.drools.javaparser.ast.type.Type) List(java.util.List) NodeList(org.drools.javaparser.ast.NodeList) Position(org.kie.api.definition.type.Position) Optional(java.util.Optional) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) GeneratedClassWithPackage(org.drools.modelcompiler.builder.GeneratedClassWithPackage) Role(org.kie.api.definition.type.Role) Collections(java.util.Collections) Modifier(org.drools.javaparser.ast.Modifier) Serializable(java.io.Serializable) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) ArrayList(java.util.ArrayList) ExpressionStmt(org.drools.javaparser.ast.stmt.ExpressionStmt) FieldDeclaration(org.drools.javaparser.ast.body.FieldDeclaration) JavadocComment(org.drools.javaparser.ast.comments.JavadocComment) ConstructorDeclaration(org.drools.javaparser.ast.body.ConstructorDeclaration) NormalAnnotationExpr(org.drools.javaparser.ast.expr.NormalAnnotationExpr) Modifier(org.drools.javaparser.ast.Modifier) JavaParser.parseStatement(org.drools.javaparser.JavaParser.parseStatement) Statement(org.drools.javaparser.ast.stmt.Statement) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) AnnotationDescr(org.drools.compiler.lang.descr.AnnotationDescr) ClassOrInterfaceType(org.drools.javaparser.ast.type.ClassOrInterfaceType) PrimitiveType(org.drools.javaparser.ast.type.PrimitiveType) Type(org.drools.javaparser.ast.type.Type) TypeFieldDescr(org.drools.compiler.lang.descr.TypeFieldDescr) GeneratedFact(org.drools.core.factmodel.GeneratedFact) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 2 with ClassOrInterfaceDeclaration

use of org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration in project drools by kiegroup.

the class AccumulateVisitor method visitAccInlineCustomCode.

/**
 * By design this legacy accumulate (with inline custome code) visitor supports only with 1-and-only binding in the accumulate code/expressions.
 */
protected void visitAccInlineCustomCode(RuleContext context2, AccumulateDescr descr, MethodCallExpr accumulateDSL, PatternDescr basePattern, PatternDescr inputDescr) {
    context.pushExprPointer(accumulateDSL::addArgument);
    final MethodCallExpr functionDSL = new MethodCallExpr(null, "accFunction");
    String code = null;
    try {
        code = new String(IoUtils.readBytesFromInputStream(this.getClass().getResourceAsStream("/AccumulateInlineFunction.java")));
    } catch (IOException e1) {
        e1.printStackTrace();
        throw new RuntimeException("Unable to locate template.");
    }
    String targetClassName = StringUtil.toId(context2.getRuleDescr().getName()) + "Accumulate" + descr.getLine();
    code = code.replaceAll("AccumulateInlineFunction", targetClassName);
    CompilationUnit templateCU = JavaParser.parse(code);
    ClassOrInterfaceDeclaration templateClass = templateCU.getClassByName(targetClassName).orElseThrow(() -> new RuntimeException("Template did not contain expected type definition."));
    ClassOrInterfaceDeclaration templateContextClass = templateClass.getMembers().stream().filter(m -> m instanceof ClassOrInterfaceDeclaration && ((ClassOrInterfaceDeclaration) m).getNameAsString().equals("ContextData")).map(ClassOrInterfaceDeclaration.class::cast).findFirst().orElseThrow(() -> new RuntimeException("Template did not contain expected type definition."));
    List<String> contextFieldNames = new ArrayList<>();
    MethodDeclaration initMethod = templateClass.getMethodsByName("init").get(0);
    BlockStmt initBlock = JavaParser.parseBlock("{" + descr.getInitCode() + "}");
    for (Statement stmt : initBlock.getStatements()) {
        if (stmt instanceof ExpressionStmt && ((ExpressionStmt) stmt).getExpression() instanceof VariableDeclarationExpr) {
            VariableDeclarationExpr vdExpr = (VariableDeclarationExpr) ((ExpressionStmt) stmt).getExpression();
            for (VariableDeclarator vd : vdExpr.getVariables()) {
                contextFieldNames.add(vd.getNameAsString());
                templateContextClass.addField(vd.getType(), vd.getNameAsString(), Modifier.PUBLIC);
                if (vd.getInitializer().isPresent()) {
                    Expression initializer = vd.getInitializer().get();
                    Expression target = new FieldAccessExpr(new NameExpr("data"), vd.getNameAsString());
                    Statement initStmt = new ExpressionStmt(new AssignExpr(target, initializer, AssignExpr.Operator.ASSIGN));
                    initMethod.getBody().get().addStatement(initStmt);
                }
            }
        } else {
            // add as-is.
            initMethod.getBody().get().addStatement(stmt);
        }
    }
    Type singleAccumulateType = JavaParser.parseType("java.lang.Object");
    MethodDeclaration accumulateMethod = templateClass.getMethodsByName("accumulate").get(0);
    BlockStmt actionBlock = JavaParser.parseBlock("{" + descr.getActionCode() + "}");
    Collection<String> allNamesInActionBlock = collectNamesInBlock(context2, actionBlock);
    if (allNamesInActionBlock.size() == 1) {
        String nameExpr = allNamesInActionBlock.iterator().next();
        accumulateMethod.getParameter(1).setName(nameExpr);
        singleAccumulateType = context2.getDeclarationById(nameExpr).get().getType();
    } else {
        new LegacyAccumulate(context, descr, basePattern).build();
        return;
    }
    writeAccumulateMethod(contextFieldNames, singleAccumulateType, accumulateMethod, actionBlock);
    // <result expression>: this is a semantic expression in the selected dialect that is executed after all source objects are iterated.
    MethodDeclaration resultMethod = templateClass.getMethodsByName("getResult").get(0);
    Type returnExpressionType = JavaParser.parseType("java.lang.Object");
    Expression returnExpression = JavaParser.parseExpression(descr.getResultCode());
    if (returnExpression instanceof NameExpr) {
        returnExpression = new EnclosedExpr(returnExpression);
    }
    rescopeNamesToNewScope(new NameExpr("data"), contextFieldNames, returnExpression);
    resultMethod.getBody().get().addStatement(new ReturnStmt(returnExpression));
    MethodDeclaration getResultTypeMethod = templateClass.getMethodsByName("getResultType").get(0);
    getResultTypeMethod.getBody().get().addStatement(new ReturnStmt(new ClassExpr(returnExpressionType)));
    if (descr.getReverseCode() != null) {
        MethodDeclaration supportsReverseMethod = templateClass.getMethodsByName("supportsReverse").get(0);
        supportsReverseMethod.getBody().get().addStatement(JavaParser.parseStatement("return true;"));
        MethodDeclaration reverseMethod = templateClass.getMethodsByName("reverse").get(0);
        BlockStmt reverseBlock = JavaParser.parseBlock("{" + descr.getReverseCode() + "}");
        Collection<String> allNamesInReverseBlock = collectNamesInBlock(context2, reverseBlock);
        if (allNamesInReverseBlock.size() == 1) {
            reverseMethod.getParameter(1).setName(allNamesInReverseBlock.iterator().next());
        } else {
            new LegacyAccumulate(context, descr, basePattern).build();
            return;
        }
        writeAccumulateMethod(contextFieldNames, singleAccumulateType, reverseMethod, reverseBlock);
    } else {
        MethodDeclaration supportsReverseMethod = templateClass.getMethodsByName("supportsReverse").get(0);
        supportsReverseMethod.getBody().get().addStatement(JavaParser.parseStatement("return false;"));
        MethodDeclaration reverseMethod = templateClass.getMethodsByName("reverse").get(0);
        reverseMethod.getBody().get().addStatement(JavaParser.parseStatement("throw new UnsupportedOperationException(\"This function does not support reverse.\");"));
    }
    // add resulting accumulator class into the package model
    this.packageModel.addGeneratedPOJO(templateClass);
    functionDSL.addArgument(new ClassExpr(JavaParser.parseType(targetClassName)));
    functionDSL.addArgument(new NameExpr(toVar(inputDescr.getIdentifier())));
    final String bindingId = basePattern.getIdentifier();
    final MethodCallExpr asDSL = new MethodCallExpr(functionDSL, "as");
    asDSL.addArgument(new NameExpr(toVar(bindingId)));
    accumulateDSL.addArgument(asDSL);
    context.popExprPointer();
}
Also used : Expression(org.drools.javaparser.ast.expr.Expression) ModelGeneratorVisitor(org.drools.modelcompiler.builder.generator.visitor.ModelGeneratorVisitor) DeclarationSpec(org.drools.modelcompiler.builder.generator.DeclarationSpec) DrlxParseUtil(org.drools.modelcompiler.builder.generator.DrlxParseUtil) JavaParser(org.drools.javaparser.JavaParser) BinaryExpr(org.drools.javaparser.ast.expr.BinaryExpr) DrlxParseUtil.toType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toType) AccumulateUtil(org.drools.compiler.rule.builder.util.AccumulateUtil) AccumulateFunction(org.kie.api.runtime.rule.AccumulateFunction) DrlxParseUtil.forceCastForName(org.drools.modelcompiler.builder.generator.DrlxParseUtil.forceCastForName) FieldAccessExpr(org.drools.javaparser.ast.expr.FieldAccessExpr) ExpressionStmt(org.drools.javaparser.ast.stmt.ExpressionStmt) DrlxParseUtil.toVar(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toVar) ConstraintParser(org.drools.modelcompiler.builder.generator.drlxparse.ConstraintParser) Statement(org.drools.javaparser.ast.stmt.Statement) PackageModel(org.drools.modelcompiler.builder.PackageModel) Parameter(org.drools.javaparser.ast.body.Parameter) Collection(java.util.Collection) ClassExpr(org.drools.javaparser.ast.expr.ClassExpr) NameExpr(org.drools.javaparser.ast.expr.NameExpr) VariableDeclarationExpr(org.drools.javaparser.ast.expr.VariableDeclarationExpr) UnknownType(org.drools.javaparser.ast.type.UnknownType) List(java.util.List) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) Optional(java.util.Optional) DrlxParseFail(org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseFail) DrlxParseResult(org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseResult) AbstractExpressionBuilder(org.drools.modelcompiler.builder.generator.expression.AbstractExpressionBuilder) DrlxParseSuccess(org.drools.modelcompiler.builder.generator.drlxparse.DrlxParseSuccess) DrlxParseUtil.rescopeNamesToNewScope(org.drools.modelcompiler.builder.generator.DrlxParseUtil.rescopeNamesToNewScope) ReturnStmt(org.drools.javaparser.ast.stmt.ReturnStmt) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) ArrayList(java.util.ArrayList) AssignExpr(org.drools.javaparser.ast.expr.AssignExpr) IoUtils(org.drools.core.util.IoUtils) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr) StringUtil(org.drools.modelcompiler.util.StringUtil) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) LambdaExpr(org.drools.javaparser.ast.expr.LambdaExpr) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) EnclosedExpr(org.drools.javaparser.ast.expr.EnclosedExpr) AccumulateDescr(org.drools.compiler.lang.descr.AccumulateDescr) VariableDeclarator(org.drools.javaparser.ast.body.VariableDeclarator) IOException(java.io.IOException) BaseDescr(org.drools.compiler.lang.descr.BaseDescr) CompilationUnit(org.drools.javaparser.ast.CompilationUnit) Type(org.drools.javaparser.ast.type.Type) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) RuleContext(org.drools.modelcompiler.builder.generator.RuleContext) Collectors.toList(java.util.stream.Collectors.toList) ParseResultVisitor(org.drools.modelcompiler.builder.generator.drlxparse.ParseResultVisitor) Modifier(org.drools.javaparser.ast.Modifier) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) ArrayList(java.util.ArrayList) NameExpr(org.drools.javaparser.ast.expr.NameExpr) ExpressionStmt(org.drools.javaparser.ast.stmt.ExpressionStmt) VariableDeclarator(org.drools.javaparser.ast.body.VariableDeclarator) AssignExpr(org.drools.javaparser.ast.expr.AssignExpr) FieldAccessExpr(org.drools.javaparser.ast.expr.FieldAccessExpr) CompilationUnit(org.drools.javaparser.ast.CompilationUnit) VariableDeclarationExpr(org.drools.javaparser.ast.expr.VariableDeclarationExpr) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) Statement(org.drools.javaparser.ast.stmt.Statement) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) IOException(java.io.IOException) DrlxParseUtil.toType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toType) UnknownType(org.drools.javaparser.ast.type.UnknownType) Type(org.drools.javaparser.ast.type.Type) Expression(org.drools.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) ClassExpr(org.drools.javaparser.ast.expr.ClassExpr) EnclosedExpr(org.drools.javaparser.ast.expr.EnclosedExpr) ReturnStmt(org.drools.javaparser.ast.stmt.ReturnStmt) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 3 with ClassOrInterfaceDeclaration

use of org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration in project drools by kiegroup.

the class DrlxCompiler method compileSingleSource.

public static CompiledUnit compileSingleSource(Reader source) {
    CompilationUnit compilationUnit = JavaParser.parse(source);
    ClassOrInterfaceDeclaration unitClass = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
    String pkg = compilationUnit.getPackageDeclaration().map(PackageDeclaration::getNameAsString).orElse("defaultpkg");
    String unit = unitClass.getNameAsString();
    KieServices ks = KieServices.get();
    ReleaseId releaseId = ks.newReleaseId(pkg, unit, "1.0");
    KieFileSystem kfs = createKieFileSystem(ks, releaseId);
    String unitPath = pkg.replace(".", "/") + "/" + unit;
    String javaPath = "src/main/java/" + unitPath + ".java";
    String drlPath = "src/main/resources/" + unitPath + ".drl";
    kfs.write(drlPath, toDrl(compilationUnit)).write(javaPath, toJava(compilationUnit));
    KieContainer kieContainer = createKieContainer(ks, kfs, releaseId);
    return new CompiledUnit(kieContainer, pkg + "." + unit);
}
Also used : CompilationUnit(org.drools.javaparser.ast.CompilationUnit) KieFileSystem(org.kie.api.builder.KieFileSystem) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) KieServices(org.kie.api.KieServices) ReleaseId(org.kie.api.builder.ReleaseId) KieContainer(org.kie.api.runtime.KieContainer)

Example 4 with ClassOrInterfaceDeclaration

use of org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration in project drools by kiegroup.

the class JavaParserCompiler method writeModel.

private static String[] writeModel(List<GeneratedClassWithPackage> classes, MemoryFileSystem srcMfs) {
    List<String> sources = new ArrayList<>();
    for (GeneratedClassWithPackage generatedPojo : classes) {
        final String pkgName = generatedPojo.getPackageName();
        final String folderName = pkgName.replace('.', '/');
        final ClassOrInterfaceDeclaration generatedClass = generatedPojo.getGeneratedClass();
        final String varsSourceName = String.format("src/main/java/%s/%s.java", folderName, generatedClass.getName());
        srcMfs.write(varsSourceName, toPojoSource(pkgName, generatedPojo.getImports(), generatedClass).getBytes());
        sources.add(varsSourceName);
    }
    return sources.toArray(new String[sources.size()]);
}
Also used : ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) ArrayList(java.util.ArrayList)

Example 5 with ClassOrInterfaceDeclaration

use of org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration in project drools by kiegroup.

the class ModelWriter method writeModel.

public Result writeModel(MemoryFileSystem srcMfs, Collection<PackageModel> packageModels) {
    List<String> sourceFiles = new ArrayList<>();
    List<String> modelFiles = new ArrayList<>();
    PrettyPrinter prettyPrinter = getPrettyPrinter();
    for (PackageModel pkgModel : packageModels) {
        String pkgName = pkgModel.getName();
        String folderName = pkgName.replace('.', '/');
        for (ClassOrInterfaceDeclaration generatedPojo : pkgModel.getGeneratedPOJOsSource()) {
            final String source = JavaParserCompiler.toPojoSource(pkgModel.getName(), pkgModel.getImports(), generatedPojo);
            pkgModel.logRule(source);
            String pojoSourceName = "src/main/java/" + folderName + "/" + generatedPojo.getName() + ".java";
            srcMfs.write(pojoSourceName, source.getBytes());
            sourceFiles.add(pojoSourceName);
        }
        for (GeneratedClassWithPackage generatedPojo : pkgModel.getGeneratedAccumulateClasses()) {
            final String source = JavaParserCompiler.toPojoSource(pkgModel.getName(), generatedPojo.getImports(), generatedPojo.getGeneratedClass());
            pkgModel.logRule(source);
            String pojoSourceName = "src/main/java/" + folderName + "/" + generatedPojo.getGeneratedClass().getName() + ".java";
            srcMfs.write(pojoSourceName, source.getBytes());
            sourceFiles.add(pojoSourceName);
        }
        RuleSourceResult rulesSourceResult = pkgModel.getRulesSource();
        // main rules file:
        String rulesFileName = pkgModel.getRulesFileName();
        String rulesSourceName = "src/main/java/" + folderName + "/" + rulesFileName + ".java";
        String rulesSource = prettyPrinter.print(rulesSourceResult.getMainRuleClass());
        pkgModel.logRule(rulesSource);
        byte[] rulesBytes = rulesSource.getBytes();
        srcMfs.write(rulesSourceName, rulesBytes);
        modelFiles.add(pkgName + "." + rulesFileName);
        sourceFiles.add(rulesSourceName);
        // manage additional classes, please notice to not add to modelFiles.
        for (CompilationUnit cu : rulesSourceResult.getSplitted()) {
            String addFileName = cu.findFirst(ClassOrInterfaceDeclaration.class).get().getNameAsString();
            String addSourceName = "src/main/java/" + folderName + "/" + addFileName + ".java";
            String addSource = prettyPrinter.print(cu);
            pkgModel.logRule(addSource);
            byte[] addBytes = addSource.getBytes();
            srcMfs.write(addSourceName, addBytes);
            sourceFiles.add(addSourceName);
        }
    }
    return new Result(sourceFiles, modelFiles);
}
Also used : CompilationUnit(org.drools.javaparser.ast.CompilationUnit) PrettyPrinter(org.drools.javaparser.printer.PrettyPrinter) JavaParserCompiler.getPrettyPrinter(org.drools.modelcompiler.builder.JavaParserCompiler.getPrettyPrinter) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) ArrayList(java.util.ArrayList) RuleSourceResult(org.drools.modelcompiler.builder.PackageModel.RuleSourceResult) RuleSourceResult(org.drools.modelcompiler.builder.PackageModel.RuleSourceResult)

Aggregations

ClassOrInterfaceDeclaration (org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration)8 CompilationUnit (org.drools.javaparser.ast.CompilationUnit)6 ArrayList (java.util.ArrayList)4 MethodDeclaration (org.drools.javaparser.ast.body.MethodDeclaration)3 MethodCallExpr (org.drools.javaparser.ast.expr.MethodCallExpr)3 NameExpr (org.drools.javaparser.ast.expr.NameExpr)3 BlockStmt (org.drools.javaparser.ast.stmt.BlockStmt)3 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 JavaParser (org.drools.javaparser.JavaParser)2 Modifier (org.drools.javaparser.ast.Modifier)2 FieldDeclaration (org.drools.javaparser.ast.body.FieldDeclaration)2 JavadocComment (org.drools.javaparser.ast.comments.JavadocComment)2 Expression (org.drools.javaparser.ast.expr.Expression)2 FieldAccessExpr (org.drools.javaparser.ast.expr.FieldAccessExpr)2 ExpressionStmt (org.drools.javaparser.ast.stmt.ExpressionStmt)2 Statement (org.drools.javaparser.ast.stmt.Statement)2