Search in sources :

Example 96 with ClassOrInterfaceDeclaration

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

the class QueryDefGenerator method generate.

public CompilationUnit generate() {
    CompilationUnit cu = new CompilationUnit("org.drools.model");
    cu.setImports(nodeList(parseImport("import org.drools.model.view.QueryCallViewItem;")));
    ClassOrInterfaceDeclaration clazz = classDeclaration(cu);
    callMethod(clazz);
    callMethodInterface(clazz);
    getters(clazz);
    return cu;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)

Example 97 with ClassOrInterfaceDeclaration

use of com.github.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.withClass(cu);
    cu.setPackageDeclaration(name);
    cu.getImports().add(new ImportDeclaration(new Name(Arrays.class.getCanonicalName()), false, false));
    cu.getImports().add(new ImportDeclaration(new Name(List.class.getCanonicalName()), false, false));
    cu.getImports().add(new ImportDeclaration(new Name(Rule.class.getCanonicalName()), false, false));
    String currentRulesMethodClassName = rulesFileName + "Rules" + index;
    ClassOrInterfaceDeclaration rulesClass = cu.addClass(currentRulesMethodClassName);
    rulesClass.addImplementedType(RulesSupplier.class);
    return buildRulesField(rulesClass);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ImportDeclaration(com.github.javaparser.ast.ImportDeclaration) NodeList(com.github.javaparser.ast.NodeList) List(java.util.List) ArrayList(java.util.ArrayList) Collectors.toList(java.util.stream.Collectors.toList) Rule(org.drools.model.Rule) Arrays(java.util.Arrays) ClassUtil.asJavaSourceName(org.drools.modelcompiler.util.ClassUtil.asJavaSourceName) SimpleName(com.github.javaparser.ast.expr.SimpleName) Name(com.github.javaparser.ast.expr.Name)

Example 98 with ClassOrInterfaceDeclaration

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

the class PackageModel method getRulesSource.

public RuleSourceResult getRulesSource() {
    boolean hasRuleUnit = !ruleUnits.isEmpty();
    CompilationUnit cu = new CompilationUnit();
    cu.setPackageDeclaration(name);
    manageImportForCompilationUnit(cu);
    ClassOrInterfaceDeclaration rulesClass = cu.addClass(rulesFileName);
    rulesClass.addImplementedType(Model.class.getCanonicalName());
    if (hasRuleUnit) {
        rulesClass.addModifier(Modifier.Keyword.ABSTRACT);
    }
    BodyDeclaration<?> dateFormatter = parseBodyDeclaration("public final static java.time.format.DateTimeFormatter " + DATE_TIME_FORMATTER_FIELD + " = new java.time.format.DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(org.drools.core.util.DateUtils.getDateFormatMask()).toFormatter(java.util.Locale.ENGLISH);\n");
    rulesClass.addMember(dateFormatter);
    BodyDeclaration<?> getNameMethod = parseBodyDeclaration("    @Override\n" + "    public String getName() {\n" + "        return \"" + name + "\";\n" + "    }\n");
    rulesClass.addMember(getNameMethod);
    String entryPointsBuilder = entryPoints.isEmpty() ? "java.util.Collections.emptyList()" : "java.util.Arrays.asList(D.entryPoint(\"" + entryPoints.stream().collect(joining("\"), D.entryPoint(\"")) + "\"))";
    BodyDeclaration<?> getEntryPointsMethod = parseBodyDeclaration("    @Override\n" + "    public java.util.List<org.drools.model.EntryPoint> getEntryPoints() {\n" + "        return " + entryPointsBuilder + ";\n" + "    }\n");
    rulesClass.addMember(getEntryPointsMethod);
    BodyDeclaration<?> getGlobalsMethod = parseBodyDeclaration("    @Override\n" + "    public java.util.List<org.drools.model.Global> getGlobals() {\n" + "        return globals;\n" + "    }\n");
    rulesClass.addMember(getGlobalsMethod);
    BodyDeclaration<?> getTypeMetaDataMethod = parseBodyDeclaration("    @Override\n" + "    public java.util.List<org.drools.model.TypeMetaData> getTypeMetaDatas() {\n" + "        return typeMetaDatas;\n" + "    }\n");
    rulesClass.addMember(getTypeMetaDataMethod);
    for (Map.Entry<String, TypedExpression> dateField : dateFields.entrySet()) {
        FieldDeclaration f = rulesClass.addField(dateField.getValue().getJPType(), dateField.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());
        f.getVariables().get(0).setInitializer(dateField.getValue().getExpression());
    }
    for (Map.Entry<String, MethodCallExpr> windowReference : windowReferences.entrySet()) {
        FieldDeclaration f = rulesClass.addField(WINDOW_REFERENCE_TYPE, windowReference.getKey(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());
        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(), publicModifier().getKeyword(), staticModifier().getKeyword(), finalModifier().getKeyword());
        field.getVariables().get(0).setInitializer(queryDef.getValue().getMethodCallExpr());
    }
    // 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);
    buildArtifactsDeclaration(getGlobals().keySet(), rulesClass, rulesListInitializerBody, "org.drools.model.Global", "globals", true);
    if (!typeMetaDataExpressions.isEmpty()) {
        BodyDeclaration<?> typeMetaDatasList = parseBodyDeclaration("java.util.List<org.drools.model.TypeMetaData> typeMetaDatas = new java.util.ArrayList<>();");
        rulesClass.addMember(typeMetaDatasList);
        for (Expression expr : typeMetaDataExpressions) {
            addInitStatement(rulesListInitializerBody, expr, "typeMetaDatas");
        }
    } else {
        BodyDeclaration<?> typeMetaDatasList = parseBodyDeclaration("java.util.List<org.drools.model.TypeMetaData> typeMetaDatas = java.util.Collections.emptyList();");
        rulesClass.addMember(typeMetaDatasList);
    }
    functions.forEach(rulesClass::addMember);
    RuleSourceResult results = new RuleSourceResult(cu);
    if (hasRuleUnit) {
        ruleMethods.keySet().forEach(unitName -> {
            String className = rulesFileName + "_" + unitName;
            ClassOrInterfaceDeclaration unitClass = createClass(className, results);
            unitClass.addExtendedType(rulesFileName);
            InitializerDeclaration unitInitializer = new InitializerDeclaration();
            BlockStmt unitInitializerBody = new BlockStmt();
            unitInitializer.setBody(unitInitializerBody);
            generateRulesInUnit(unitName, unitInitializerBody, results, unitClass);
            Set<QueryModel> queries = queriesByRuleUnit.get(unitName);
            Collection<String> queryNames = queries == null ? Collections.emptyList() : queries.stream().map(QueryModel::getName).map(name -> QUERY_METHOD_PREFIX + name).collect(toList());
            Collection<MethodDeclaration> queryImpls = queryNames.stream().map(queryMethods::get).collect(toList());
            generateQueriesInUnit(unitClass, unitInitializerBody, queryNames, queryImpls);
            if (!unitInitializerBody.getStatements().isEmpty()) {
                unitClass.addMember(unitInitializer);
            }
        });
    } else {
        generateRulesInUnit(DEFAULT_RULE_UNIT, rulesListInitializerBody, results, rulesClass);
        generateQueriesInUnit(rulesClass, rulesListInitializerBody, queryMethods.keySet(), queryMethods.values());
    }
    if (!rulesListInitializerBody.getStatements().isEmpty()) {
        rulesClass.addMember(rulesListInitializer);
    }
    return results;
}
Also used : ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) CompilationUnit(com.github.javaparser.ast.CompilationUnit) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) InitializerDeclaration(com.github.javaparser.ast.body.InitializerDeclaration) Expression(com.github.javaparser.ast.expr.Expression) TypedExpression(org.drools.modelcompiler.builder.generator.TypedExpression) Model(org.drools.model.Model) CreatedClass(org.drools.modelcompiler.util.lambdareplace.CreatedClass) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 99 with ClassOrInterfaceDeclaration

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

the class RuleWriter method getRuleSources.

public List<RuleFileSource> getRuleSources() {
    List<RuleFileSource> rules = new ArrayList<>();
    for (CompilationUnit cu : rulesSource.getModelClasses()) {
        final Optional<ClassOrInterfaceDeclaration> classOptional = cu.findFirst(ClassOrInterfaceDeclaration.class);
        if (classOptional.isPresent()) {
            String addFileName = classOptional.get().getNameAsString();
            if (EXTERNALIZE_LAMBDAS && pkgModel.getConfiguration().isExternaliseCanonicalModelLambda()) {
                new ExecModelLambdaPostProcessor(pkgModel, cu).convertLambdas();
                if (checkNonExternalisedLambda) {
                    checkNonExternalisedLambda(cu);
                }
                rules.add(new RuleFileSource(addFileName, cu));
            } else {
                rules.add(new RuleFileSource(addFileName, cu));
            }
        }
    }
    return rules;
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ArrayList(java.util.ArrayList) ExecModelLambdaPostProcessor(org.drools.modelcompiler.util.lambdareplace.ExecModelLambdaPostProcessor)

Example 100 with ClassOrInterfaceDeclaration

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

the class GeneratedClassDeclarationTest method testClassWithMethod.

@Test
public void testClassWithMethod() {
    TestTypeDefinition typeDefinition = new TestTypeDefinition("TestClass");
    TestMethodDefinition methodDefinition = new TestMethodDefinition("methodName1", "int", "{ return 0; }");
    typeDefinition.getMethods().add(methodDefinition);
    GeneratedClassDeclaration generatedClassDeclaration = new GeneratedClassDeclaration(typeDefinition);
    ClassOrInterfaceDeclaration actual = generatedClassDeclaration.toClassDeclaration();
    String expectedClass = "public class TestClass implements java.io.Serializable {\n" + "\n" + "    public TestClass() {\n" + "    }\n" + "\n" + "    @java.lang.Override()\n" + "    public java.lang.String toString() {\n" + "        return \"TestClass\" + \"( \" + \" )\";\n" + "    }\n" + "\n" + "    int methodName1() {\n" + "        return 0;\n" + "    }\n" + "}";
    verifyBodyWithBetterDiff(expectedClass, actual);
}
Also used : ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Test(org.junit.Test)

Aggregations

ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)261 Test (org.junit.Test)174 CompilationUnit (com.github.javaparser.ast.CompilationUnit)164 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)84 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)79 AbstractResolutionTest (com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest)71 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)52 Context (com.github.javaparser.symbolsolver.core.resolution.Context)39 ClassOrInterfaceDeclarationContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.ClassOrInterfaceDeclarationContext)38 CompilationUnitContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.CompilationUnitContext)37 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)36 Expression (com.github.javaparser.ast.expr.Expression)33 TypeSolver (com.github.javaparser.symbolsolver.model.resolution.TypeSolver)28 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)27 MemoryTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.MemoryTypeSolver)24 HashMap (java.util.HashMap)21 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)20 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)20 KiePMMLException (org.kie.pmml.api.exceptions.KiePMMLException)20 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)19