Search in sources :

Example 6 with ClassOrInterfaceDeclaration

use of org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration 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 7 with ClassOrInterfaceDeclaration

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

the class PackageModel method buildRulesField.

private MethodCallExpr buildRulesField(RuleSourceResult results, int index) {
    CompilationUnit cu = new CompilationUnit();
    results.with(cu);
    cu.setPackageDeclaration(name);
    cu.addImport(JavaParser.parseImport("import " + Arrays.class.getCanonicalName() + ";"));
    cu.addImport(JavaParser.parseImport("import " + List.class.getCanonicalName() + ";"));
    cu.addImport(JavaParser.parseImport("import " + Rule.class.getCanonicalName() + ";"));
    String currentRulesMethodClassName = rulesFileName + "Rules" + index;
    ClassOrInterfaceDeclaration rulesClass = cu.addClass(currentRulesMethodClassName);
    return buildRulesField(rulesClass);
}
Also used : CompilationUnit(org.drools.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration)

Example 8 with ClassOrInterfaceDeclaration

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

the class DrlxCompiler method addToFileSystem.

private static void addToFileSystem(KieFileSystem kfs, File file, List<String> units) {
    if (file.isDirectory()) {
        for (File subfile : file.listFiles()) {
            addToFileSystem(kfs, subfile, units);
        }
    } else {
        CompilationUnit compilationUnit;
        try {
            compilationUnit = JavaParser.parse(new FileReader(file));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        ClassOrInterfaceDeclaration unitClass = (ClassOrInterfaceDeclaration) compilationUnit.getType(0);
        String pkg = compilationUnit.getPackageDeclaration().map(PackageDeclaration::getNameAsString).orElse("defaultpkg");
        String unit = unitClass.getNameAsString();
        String unitPath = pkg.replace(".", "/") + "/" + unit;
        kfs.write("src/main/java/" + unitPath + ".java", toJava(compilationUnit));
        if (hasRules(compilationUnit)) {
            kfs.write("src/main/resources/" + unitPath + ".drl", toDrl(compilationUnit));
        }
        if (unitClass.getImplementedTypes().stream().anyMatch(type -> type.getNameAsString().equals("RuleUnit"))) {
            units.add(pkg + "." + unit);
        }
    }
}
Also used : CompilationUnit(org.drools.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(org.drools.javaparser.ast.body.ClassOrInterfaceDeclaration) FileNotFoundException(java.io.FileNotFoundException) FileReader(java.io.FileReader) File(java.io.File)

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