Search in sources :

Example 1 with BlockStmt

use of org.drools.javaparser.ast.stmt.BlockStmt in project drools by kiegroup.

the class PackageModel method getRulesSource.

public RuleSourceResult getRulesSource() {
    CompilationUnit cu = new CompilationUnit();
    cu.setPackageDeclaration(name);
    manageImportForCompilationUnit(cu);
    ClassOrInterfaceDeclaration rulesClass = cu.addClass(rulesFileName);
    rulesClass.addImplementedType(Model.class);
    BodyDeclaration<?> dateFormatter = JavaParser.parseBodyDeclaration("public final static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DateUtils.getDateFormatMask());\n");
    rulesClass.addMember(dateFormatter);
    BodyDeclaration<?> getNameMethod = JavaParser.parseBodyDeclaration("    @Override\n" + "        public String getName() {\n" + "        return \"" + name + "\";\n" + "    }\n");
    rulesClass.addMember(getNameMethod);
    BodyDeclaration<?> getRulesMethod = JavaParser.parseBodyDeclaration("    @Override\n" + "    public List<Rule> getRules() {\n" + "        return rules;\n" + "    }\n");
    rulesClass.addMember(getRulesMethod);
    StringBuilder sb = new StringBuilder("\n");
    sb.append("With the following expression ID:\n");
    sb.append(exprIdGenerator.toString());
    sb.append("\n");
    JavadocComment exprIdComment = new JavadocComment(sb.toString());
    getRulesMethod.setComment(exprIdComment);
    BodyDeclaration<?> getGlobalsMethod = JavaParser.parseBodyDeclaration("    @Override\n" + "    public List<Global> getGlobals() {\n" + "        return globals;\n" + "    }\n");
    rulesClass.addMember(getGlobalsMethod);
    BodyDeclaration<?> getQueriesMethod = JavaParser.parseBodyDeclaration("    @Override\n" + "    public List<Query> getQueries() {\n" + "        return queries;\n" + "    }\n");
    rulesClass.addMember(getQueriesMethod);
    BodyDeclaration<?> getTypeMetaDataMethod = JavaParser.parseBodyDeclaration("    @Override\n" + "    public List<TypeMetaData> getTypeMetaDatas() {\n" + "        return typeMetaDatas;\n" + "    }\n");
    rulesClass.addMember(getTypeMetaDataMethod);
    for (Map.Entry<String, MethodCallExpr> windowReference : windowReferences.entrySet()) {
        FieldDeclaration f = rulesClass.addField(WINDOW_REFERENCE_TYPE, windowReference.getKey(), Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
        f.getVariables().get(0).setInitializer(windowReference.getValue());
    }
    for (Map.Entry<String, Class<?>> g : getGlobals().entrySet()) {
        addGlobalField(rulesClass, getName(), g.getKey(), g.getValue());
    }
    for (Map.Entry<String, QueryGenerator.QueryDefWithType> queryDef : queryDefWithType.entrySet()) {
        FieldDeclaration field = rulesClass.addField(queryDef.getValue().getQueryType(), queryDef.getKey(), Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
        field.getVariables().get(0).setInitializer(queryDef.getValue().getMethodCallExpr());
    }
    for (Map.Entry<String, MethodDeclaration> methodName : queryMethods.entrySet()) {
        FieldDeclaration field = rulesClass.addField(methodName.getValue().getType(), methodName.getKey(), Modifier.FINAL);
        field.getVariables().get(0).setInitializer(new MethodCallExpr(null, methodName.getKey()));
    }
    // instance initializer block.
    // add to `rules` list the result of invoking each method for rule
    InitializerDeclaration rulesListInitializer = new InitializerDeclaration();
    BlockStmt rulesListInitializerBody = new BlockStmt();
    rulesListInitializer.setBody(rulesListInitializerBody);
    queryMethods.values().forEach(rulesClass::addMember);
    buildArtifactsDeclaration(queryMethods.keySet(), rulesClass, rulesListInitializerBody, "Query", "queries", false);
    buildArtifactsDeclaration(windowReferences.keySet(), rulesClass, rulesListInitializerBody, "WindowReference", "windowReferences", false);
    buildArtifactsDeclaration(getGlobals().keySet(), rulesClass, rulesListInitializerBody, "Global", "globals", true);
    if (!typeMetaDataExpressions.isEmpty()) {
        BodyDeclaration<?> typeMetaDatasList = JavaParser.parseBodyDeclaration("List<TypeMetaData> typeMetaDatas = new ArrayList<>();");
        rulesClass.addMember(typeMetaDatasList);
        for (Expression expr : typeMetaDataExpressions) {
            addInitStatement(rulesListInitializerBody, expr, "typeMetaDatas");
        }
    } else {
        BodyDeclaration<?> typeMetaDatasList = JavaParser.parseBodyDeclaration("List<TypeMetaData> typeMetaDatas = Collections.emptyList();");
        rulesClass.addMember(typeMetaDatasList);
    }
    functions.forEach(rulesClass::addMember);
    RuleSourceResult results = new RuleSourceResult(cu);
    int ruleCount = ruleMethods.size();
    boolean requiresMultipleRulesLists = ruleCount >= RULES_DECLARATION_PER_CLASS - 1;
    MethodCallExpr rules = buildRulesField(rulesClass);
    if (requiresMultipleRulesLists) {
        addRulesList(rulesListInitializerBody, "rulesList");
    }
    // each method per Drlx parser result
    int count = -1;
    Map<Integer, ClassOrInterfaceDeclaration> splitted = new LinkedHashMap<>();
    for (Entry<String, MethodDeclaration> ruleMethodKV : ruleMethods.entrySet()) {
        ClassOrInterfaceDeclaration rulesMethodClass = splitted.computeIfAbsent(++count / RULES_PER_CLASS, i -> {
            CompilationUnit cuRulesMethod = new CompilationUnit();
            results.with(cuRulesMethod);
            cuRulesMethod.setPackageDeclaration(name);
            manageImportForCompilationUnit(cuRulesMethod);
            cuRulesMethod.addImport(JavaParser.parseImport("import static " + name + "." + rulesFileName + ".*;"));
            String currentRulesMethodClassName = rulesFileName + "RuleMethods" + i;
            return cuRulesMethod.addClass(currentRulesMethodClassName);
        });
        rulesMethodClass.addMember(ruleMethodKV.getValue());
        if (count % RULES_DECLARATION_PER_CLASS == RULES_DECLARATION_PER_CLASS - 1) {
            int index = count / RULES_DECLARATION_PER_CLASS;
            rules = buildRulesField(results, index);
            addRulesList(rulesListInitializerBody, rulesFileName + "Rules" + index + ".rulesList");
        }
        // manage in main class init block:
        rules.addArgument(new MethodCallExpr(new NameExpr(rulesMethodClass.getNameAsString()), ruleMethodKV.getKey()));
    }
    BodyDeclaration<?> rulesList = requiresMultipleRulesLists ? JavaParser.parseBodyDeclaration("List<Rule> rules = new ArrayList<>(" + ruleCount + ");") : JavaParser.parseBodyDeclaration("List<Rule> rules = rulesList;");
    rulesClass.addMember(rulesList);
    if (!rulesListInitializer.getBody().getStatements().isEmpty()) {
        rulesClass.addMember(rulesListInitializer);
    }
    return results;
}
Also used : ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) NameExpr(org.drools.javaparser.ast.expr.NameExpr) FieldDeclaration(org.drools.javaparser.ast.body.FieldDeclaration) LinkedHashMap(java.util.LinkedHashMap) JavadocComment(org.drools.javaparser.ast.comments.JavadocComment) CompilationUnit(org.drools.javaparser.ast.CompilationUnit) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) InitializerDeclaration(org.drools.javaparser.ast.body.InitializerDeclaration) Expression(org.drools.javaparser.ast.expr.Expression) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 2 with BlockStmt

use of org.drools.javaparser.ast.stmt.BlockStmt in project drools by kiegroup.

the class Consequence method createCall.

public MethodCallExpr createCall(RuleDescr ruleDescr, String consequenceString, BlockStmt ruleVariablesBlock, boolean isBreaking) {
    BlockStmt ruleConsequence = rewriteConsequence(consequenceString);
    if (ruleConsequence != null) {
        ruleConsequence.findAll(Expression.class).stream().filter(s -> isNameExprWithName(s, "kcontext")).forEach(n -> n.replace(new NameExpr("drools")));
    }
    Collection<String> usedDeclarationInRHS = extractUsedDeclarations(ruleConsequence, consequenceString);
    MethodCallExpr onCall = onCall(usedDeclarationInRHS);
    if (isBreaking) {
        onCall = new MethodCallExpr(onCall, BREAKING_CALL);
    }
    MethodCallExpr executeCall = null;
    if (context.getRuleDialect() == RuleContext.RuleDialect.JAVA) {
        executeCall = executeCall(ruleVariablesBlock, ruleConsequence, usedDeclarationInRHS, onCall);
    } else if (context.getRuleDialect() == RuleContext.RuleDialect.MVEL) {
        executeCall = executeScriptCall(ruleDescr, onCall);
    }
    return executeCall;
}
Also used : BitMask(org.drools.model.BitMask) ClassOrInterfaceType(org.drools.javaparser.ast.type.ClassOrInterfaceType) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) Expression(org.drools.javaparser.ast.expr.Expression) DrlxParseUtil.isNameExprWithName(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isNameExprWithName) DroolsImpl(org.drools.modelcompiler.consequence.DroolsImpl) JavaParser(org.drools.javaparser.JavaParser) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AssignExpr(org.drools.javaparser.ast.expr.AssignExpr) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr) BREAKING_CALL(org.drools.modelcompiler.builder.generator.visitor.NamedConsequenceVisitor.BREAKING_CALL) LambdaExpr(org.drools.javaparser.ast.expr.LambdaExpr) JavaParser.parseExpression(org.drools.javaparser.JavaParser.parseExpression) Statement(org.drools.javaparser.ast.stmt.Statement) Collectors.toSet(java.util.stream.Collectors.toSet) PackageModel(org.drools.modelcompiler.builder.PackageModel) ObjectCreationExpr(org.drools.javaparser.ast.expr.ObjectCreationExpr) DrlxParseUtil.hasScope(org.drools.modelcompiler.builder.generator.DrlxParseUtil.hasScope) Parameter(org.drools.javaparser.ast.body.Parameter) ClassUtils(org.drools.core.util.ClassUtils) Collection(java.util.Collection) DrlxParseUtil.parseBlock(org.drools.modelcompiler.builder.generator.DrlxParseUtil.parseBlock) Set(java.util.Set) EmptyStmt(org.drools.javaparser.ast.stmt.EmptyStmt) ClassExpr(org.drools.javaparser.ast.expr.ClassExpr) NameExpr(org.drools.javaparser.ast.expr.NameExpr) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) Objects(java.util.Objects) VariableDeclarationExpr(org.drools.javaparser.ast.expr.VariableDeclarationExpr) UnknownType(org.drools.javaparser.ast.type.UnknownType) DrlxParseUtil.findAllChildrenRecursive(org.drools.modelcompiler.builder.generator.DrlxParseUtil.findAllChildrenRecursive) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Modifier(org.drools.javaparser.ast.Modifier) SimpleName(org.drools.javaparser.ast.expr.SimpleName) StringUtils(org.drools.core.util.StringUtils) Expression(org.drools.javaparser.ast.expr.Expression) JavaParser.parseExpression(org.drools.javaparser.JavaParser.parseExpression) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) NameExpr(org.drools.javaparser.ast.expr.NameExpr) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 3 with BlockStmt

use of org.drools.javaparser.ast.stmt.BlockStmt in project drools by kiegroup.

the class Consequence method executeCall.

private MethodCallExpr executeCall(BlockStmt ruleVariablesBlock, BlockStmt ruleConsequence, Collection<String> verifiedDeclUsedInRHS, MethodCallExpr onCall) {
    boolean requireDrools = rewriteRHS(ruleVariablesBlock, ruleConsequence);
    MethodCallExpr executeCall = new MethodCallExpr(onCall, EXECUTE_CALL);
    LambdaExpr executeLambda = new LambdaExpr();
    executeCall.addArgument(executeLambda);
    executeLambda.setEnclosingParameters(true);
    if (requireDrools) {
        executeLambda.addParameter(new Parameter(new UnknownType(), "drools"));
    }
    verifiedDeclUsedInRHS.stream().map(x -> new Parameter(new UnknownType(), x)).forEach(executeLambda::addParameter);
    executeLambda.setBody(ruleConsequence);
    return executeCall;
}
Also used : UnknownType(org.drools.javaparser.ast.type.UnknownType) BitMask(org.drools.model.BitMask) ClassOrInterfaceType(org.drools.javaparser.ast.type.ClassOrInterfaceType) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) Expression(org.drools.javaparser.ast.expr.Expression) DrlxParseUtil.isNameExprWithName(org.drools.modelcompiler.builder.generator.DrlxParseUtil.isNameExprWithName) DroolsImpl(org.drools.modelcompiler.consequence.DroolsImpl) JavaParser(org.drools.javaparser.JavaParser) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AssignExpr(org.drools.javaparser.ast.expr.AssignExpr) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr) BREAKING_CALL(org.drools.modelcompiler.builder.generator.visitor.NamedConsequenceVisitor.BREAKING_CALL) LambdaExpr(org.drools.javaparser.ast.expr.LambdaExpr) JavaParser.parseExpression(org.drools.javaparser.JavaParser.parseExpression) Statement(org.drools.javaparser.ast.stmt.Statement) Collectors.toSet(java.util.stream.Collectors.toSet) PackageModel(org.drools.modelcompiler.builder.PackageModel) ObjectCreationExpr(org.drools.javaparser.ast.expr.ObjectCreationExpr) DrlxParseUtil.hasScope(org.drools.modelcompiler.builder.generator.DrlxParseUtil.hasScope) Parameter(org.drools.javaparser.ast.body.Parameter) ClassUtils(org.drools.core.util.ClassUtils) Collection(java.util.Collection) DrlxParseUtil.parseBlock(org.drools.modelcompiler.builder.generator.DrlxParseUtil.parseBlock) Set(java.util.Set) EmptyStmt(org.drools.javaparser.ast.stmt.EmptyStmt) ClassExpr(org.drools.javaparser.ast.expr.ClassExpr) NameExpr(org.drools.javaparser.ast.expr.NameExpr) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) Objects(java.util.Objects) VariableDeclarationExpr(org.drools.javaparser.ast.expr.VariableDeclarationExpr) UnknownType(org.drools.javaparser.ast.type.UnknownType) DrlxParseUtil.findAllChildrenRecursive(org.drools.modelcompiler.builder.generator.DrlxParseUtil.findAllChildrenRecursive) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Modifier(org.drools.javaparser.ast.Modifier) SimpleName(org.drools.javaparser.ast.expr.SimpleName) StringUtils(org.drools.core.util.StringUtils) LambdaExpr(org.drools.javaparser.ast.expr.LambdaExpr) Parameter(org.drools.javaparser.ast.body.Parameter) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 4 with BlockStmt

use of org.drools.javaparser.ast.stmt.BlockStmt in project drools by kiegroup.

the class ModelGenerator method processRule.

private static void processRule(KnowledgeBuilderImpl kbuilder, TypeResolver typeResolver, PackageModel packageModel, PackageDescr packageDescr, RuleDescr ruleDescr, boolean isPattern) {
    RuleContext context = new RuleContext(kbuilder, packageModel, ruleDescr, typeResolver, isPattern);
    for (Entry<String, Object> kv : ruleDescr.getNamedConsequences().entrySet()) {
        context.addNamedConsequence(kv.getKey(), kv.getValue().toString());
    }
    new ModelGeneratorVisitor(context, packageModel).visit(getExtendedLhs(packageDescr, ruleDescr));
    final String ruleMethodName = "rule_" + toId(ruleDescr.getName());
    MethodDeclaration ruleMethod = new MethodDeclaration(EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), RULE_TYPE, ruleMethodName);
    ruleMethod.setJavadocComment(" Rule name: " + ruleDescr.getName() + " ");
    VariableDeclarationExpr ruleVar = new VariableDeclarationExpr(RULE_TYPE, RULE_CALL);
    MethodCallExpr ruleCall = new MethodCallExpr(null, RULE_CALL);
    if (!ruleDescr.getNamespace().isEmpty()) {
        ruleCall.addArgument(new StringLiteralExpr(ruleDescr.getNamespace()));
    }
    ruleCall.addArgument(new StringLiteralExpr(ruleDescr.getName()));
    RuleUnitDescr ruleUnitDescr = context.getRuleUnitDescr();
    MethodCallExpr buildCallScope = ruleUnitDescr != null ? new MethodCallExpr(ruleCall, UNIT_CALL).addArgument(new ClassExpr(classToReferenceType(ruleUnitDescr.getRuleUnitClass()))) : ruleCall;
    for (MethodCallExpr attributeExpr : ruleAttributes(context, ruleDescr)) {
        attributeExpr.setScope(buildCallScope);
        buildCallScope = attributeExpr;
    }
    for (MethodCallExpr metaAttributeExpr : ruleMetaAttributes(context, ruleDescr)) {
        metaAttributeExpr.setScope(buildCallScope);
        buildCallScope = metaAttributeExpr;
    }
    MethodCallExpr buildCall = new MethodCallExpr(buildCallScope, BUILD_CALL, NodeList.nodeList(context.getExpressions()));
    BlockStmt ruleVariablesBlock = new BlockStmt();
    createUnitData(ruleUnitDescr, ruleVariablesBlock);
    createVariables(kbuilder, ruleVariablesBlock, packageModel, context);
    ruleMethod.setBody(ruleVariablesBlock);
    MethodCallExpr executeCall = new Consequence(context).createCall(ruleDescr, ruleDescr.getConsequence().toString(), ruleVariablesBlock, false);
    buildCall.addArgument(executeCall);
    ruleVariablesBlock.addStatement(new AssignExpr(ruleVar, buildCall, AssignExpr.Operator.ASSIGN));
    ruleVariablesBlock.addStatement(new ReturnStmt(RULE_CALL));
    packageModel.putRuleMethod(ruleMethodName, ruleMethod);
}
Also used : VariableDeclarationExpr(org.drools.javaparser.ast.expr.VariableDeclarationExpr) MethodDeclaration(org.drools.javaparser.ast.body.MethodDeclaration) RuleUnitDescr(org.drools.core.ruleunit.RuleUnitDescr) BlockStmt(org.drools.javaparser.ast.stmt.BlockStmt) StringLiteralExpr(org.drools.javaparser.ast.expr.StringLiteralExpr) AssignExpr(org.drools.javaparser.ast.expr.AssignExpr) ClassExpr(org.drools.javaparser.ast.expr.ClassExpr) ModelGeneratorVisitor(org.drools.modelcompiler.builder.generator.visitor.ModelGeneratorVisitor) ReturnStmt(org.drools.javaparser.ast.stmt.ReturnStmt) MethodCallExpr(org.drools.javaparser.ast.expr.MethodCallExpr)

Example 5 with BlockStmt

use of org.drools.javaparser.ast.stmt.BlockStmt 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)

Aggregations

BlockStmt (org.drools.javaparser.ast.stmt.BlockStmt)13 MethodCallExpr (org.drools.javaparser.ast.expr.MethodCallExpr)9 Statement (org.drools.javaparser.ast.stmt.Statement)9 MethodDeclaration (org.drools.javaparser.ast.body.MethodDeclaration)8 NameExpr (org.drools.javaparser.ast.expr.NameExpr)8 ClassOrInterfaceType (org.drools.javaparser.ast.type.ClassOrInterfaceType)8 AssignExpr (org.drools.javaparser.ast.expr.AssignExpr)6 Expression (org.drools.javaparser.ast.expr.Expression)6 VariableDeclarationExpr (org.drools.javaparser.ast.expr.VariableDeclarationExpr)6 Type (org.drools.javaparser.ast.type.Type)6 ArrayList (java.util.ArrayList)5 Collection (java.util.Collection)5 List (java.util.List)5 JavaParser (org.drools.javaparser.JavaParser)5 Modifier (org.drools.javaparser.ast.Modifier)5 ClassExpr (org.drools.javaparser.ast.expr.ClassExpr)5 StringLiteralExpr (org.drools.javaparser.ast.expr.StringLiteralExpr)5 PackageModel (org.drools.modelcompiler.builder.PackageModel)5 Collectors.toList (java.util.stream.Collectors.toList)4 JavaParser.parseExpression (org.drools.javaparser.JavaParser.parseExpression)4