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;
}
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;
}
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;
}
use of org.drools.javaparser.ast.stmt.BlockStmt in project drools by kiegroup.
the class Consequence method rewriteConsequenceBlock.
private String rewriteConsequenceBlock(String consequence) {
int modifyPos = StringUtils.indexOfOutOfQuotes(consequence, "modify");
if (modifyPos < 0) {
return consequence;
}
int lastCopiedEnd = 0;
StringBuilder sb = new StringBuilder();
sb.append(consequence.substring(lastCopiedEnd, modifyPos));
lastCopiedEnd = modifyPos + 1;
for (; modifyPos >= 0; modifyPos = StringUtils.indexOfOutOfQuotes(consequence, "modify", modifyPos + 6)) {
int declStart = consequence.indexOf('(', modifyPos + 6);
int declEnd = consequence.indexOf(')', declStart + 1);
if (declEnd < 0) {
continue;
}
String decl = consequence.substring(declStart + 1, declEnd).trim();
if (!context.getDeclarationById(decl).isPresent()) {
continue;
}
int blockStart = consequence.indexOf('{', declEnd + 1);
int blockEnd = consequence.indexOf('}', blockStart + 1);
if (blockEnd < 0) {
continue;
}
if (lastCopiedEnd < modifyPos) {
sb.append(consequence.substring(lastCopiedEnd, modifyPos));
}
NameExpr declAsNameExpr = new NameExpr(decl);
String originalBlock = consequence.substring(blockStart + 1, blockEnd).trim();
BlockStmt modifyBlock = JavaParser.parseBlock("{" + originalBlock + ";}");
List<MethodCallExpr> originalMethodCalls = modifyBlock.findAll(MethodCallExpr.class);
for (MethodCallExpr mc : originalMethodCalls) {
Expression mcWithScope = org.drools.modelcompiler.builder.generator.DrlxParseUtil.prepend(declAsNameExpr, mc);
modifyBlock.replace(mc, mcWithScope);
}
for (Statement n : modifyBlock.getStatements()) {
if (!(n instanceof EmptyStmt)) {
sb.append(n);
}
}
sb.append("update(").append(decl).append(");\n");
lastCopiedEnd = blockEnd + 1;
}
if (lastCopiedEnd < consequence.length()) {
sb.append(consequence.substring(lastCopiedEnd));
}
return sb.toString();
}
use of org.drools.javaparser.ast.stmt.BlockStmt in project drools by kiegroup.
the class Consequence method rewriteRHS.
private boolean rewriteRHS(BlockStmt ruleBlock, BlockStmt rhs) {
AtomicBoolean requireDrools = new AtomicBoolean(false);
List<MethodCallExpr> methodCallExprs = rhs.findAll(MethodCallExpr.class);
List<MethodCallExpr> updateExprs = new ArrayList<>();
for (MethodCallExpr methodCallExpr : methodCallExprs) {
if (isDroolsMethod(methodCallExpr)) {
if (!methodCallExpr.getScope().isPresent()) {
methodCallExpr.setScope(new NameExpr("drools"));
}
if (knowledgeHelperMethods.contains(methodCallExpr.getNameAsString())) {
methodCallExpr.setScope(asKnoledgeHelperExpression);
} else if (methodCallExpr.getNameAsString().equals("update")) {
updateExprs.add(methodCallExpr);
} else if (methodCallExpr.getNameAsString().equals("retract")) {
methodCallExpr.setName(new SimpleName("delete"));
}
requireDrools.set(true);
}
}
for (MethodCallExpr updateExpr : updateExprs) {
Expression argExpr = updateExpr.getArgument(0);
if (argExpr instanceof NameExpr) {
String updatedVar = ((NameExpr) argExpr).getNameAsString();
Class<?> updatedClass = context.getDeclarationById(updatedVar).map(DeclarationSpec::getDeclarationClass).orElseThrow(RuntimeException::new);
MethodCallExpr bitMaskCreation = new MethodCallExpr(new NameExpr(BitMask.class.getCanonicalName()), "getPatternMask");
bitMaskCreation.addArgument(new ClassExpr(JavaParser.parseClassOrInterfaceType(updatedClass.getCanonicalName())));
methodCallExprs.subList(0, methodCallExprs.indexOf(updateExpr)).stream().filter(mce -> mce.getScope().isPresent() && hasScope(mce, updatedVar)).map(mce -> ClassUtils.setter2property(mce.getNameAsString())).filter(Objects::nonNull).distinct().forEach(s -> bitMaskCreation.addArgument(new StringLiteralExpr(s)));
VariableDeclarationExpr bitMaskVar = new VariableDeclarationExpr(BITMASK_TYPE, "mask_" + updatedVar, Modifier.FINAL);
AssignExpr bitMaskAssign = new AssignExpr(bitMaskVar, bitMaskCreation, AssignExpr.Operator.ASSIGN);
ruleBlock.addStatement(bitMaskAssign);
updateExpr.addArgument("mask_" + updatedVar);
}
}
return requireDrools.get();
}
Aggregations