use of org.drools.javaparser.ast.expr.MethodCallExpr 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.expr.MethodCallExpr 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();
}
use of org.drools.javaparser.ast.expr.MethodCallExpr in project drools by kiegroup.
the class DrlxParseUtil method toMethodCallWithClassCheck.
public static TypedExpression toMethodCallWithClassCheck(RuleContext context, Expression expr, String bindingId, Class<?> clazz, TypeResolver typeResolver) {
final Deque<ParsedMethod> callStackLeftToRight = new LinkedList<>();
createExpressionCall(expr, callStackLeftToRight);
Class<?> previousClass = clazz;
Expression previousScope = null;
for (ParsedMethod e : callStackLeftToRight) {
if (e.expression instanceof NameExpr || e.expression instanceof FieldAccessExpr) {
if (e.fieldToResolve.equals(bindingId)) {
continue;
}
if (previousClass == null) {
try {
previousClass = typeResolver.resolveType(e.fieldToResolve);
previousScope = new NameExpr(e.fieldToResolve);
} catch (ClassNotFoundException e1) {
// ignore
}
if (previousClass == null) {
previousClass = context.getDeclarationById(e.fieldToResolve).map(DeclarationSpec::getDeclarationClass).orElseThrow(() -> new RuntimeException("Unknown field: " + e.fieldToResolve));
previousScope = e.expression;
}
} else {
TypedExpression te = nameExprToMethodCallExpr(e.fieldToResolve, previousClass, previousScope);
Class<?> returnType = te.getType();
previousScope = te.getExpression();
previousClass = returnType;
}
} else if (e.expression instanceof MethodCallExpr) {
Class<?> returnType = returnTypeOfMethodCallExpr(context, typeResolver, (MethodCallExpr) e.expression, previousClass, null);
MethodCallExpr cloned = ((MethodCallExpr) e.expression.clone()).setScope(previousScope);
previousScope = cloned;
previousClass = returnType;
}
}
return new TypedExpression(previousScope, previousClass);
}
use of org.drools.javaparser.ast.expr.MethodCallExpr in project drools by kiegroup.
the class ModelGenerator method addUnitData.
private static void addUnitData(String unitVar, Class<?> type, BlockStmt ruleBlock) {
Type declType = classToReferenceType(type);
ClassOrInterfaceType varType = JavaParser.parseClassOrInterfaceType(UnitData.class.getCanonicalName());
varType.setTypeArguments(declType);
VariableDeclarationExpr var_ = new VariableDeclarationExpr(varType, toVar(unitVar), Modifier.FINAL);
MethodCallExpr unitDataCall = new MethodCallExpr(null, UNIT_DATA_CALL);
unitDataCall.addArgument(new ClassExpr(declType));
unitDataCall.addArgument(new StringLiteralExpr(unitVar));
AssignExpr var_assign = new AssignExpr(var_, unitDataCall, AssignExpr.Operator.ASSIGN);
ruleBlock.addStatement(var_assign);
}
use of org.drools.javaparser.ast.expr.MethodCallExpr in project drools by kiegroup.
the class ModelGenerator method ruleAttributes.
/**
* Build a list of method calls, representing each needed {@link org.drools.model.impl.RuleBuilder#attribute(org.drools.model.Rule.Attribute, Object)}
* starting from a drools-compiler {@link RuleDescr}.
* The tuple represent the Rule Attribute expressed in JavParser form, and the attribute value expressed in JavaParser form.
*/
private static List<MethodCallExpr> ruleAttributes(RuleContext context, RuleDescr ruleDescr) {
List<MethodCallExpr> ruleAttributes = new ArrayList<>();
for (Entry<String, AttributeDescr> as : ruleDescr.getAttributes().entrySet()) {
// dialect=mvel is not an attribute of DSL expr(), so we check it before.
if (as.getKey().equals("dialect")) {
if (as.getValue().getValue().equals("mvel")) {
context.setRuleDialect(RuleDialect.MVEL);
}
continue;
}
MethodCallExpr attributeCall = new MethodCallExpr(null, ATTRIBUTE_CALL);
attributeCall.addArgument(attributesMap.get(as.getKey()));
switch(as.getKey()) {
case "dialect":
throw new RuntimeException("should not have reached this part of the code");
case "no-loop":
case "salience":
case "enabled":
case "auto-focus":
case "lock-on-active":
attributeCall.addArgument(parseExpression(as.getValue().getValue()));
break;
case "agenda-group":
case "activation-group":
case "ruleflow-group":
case "duration":
case "timer":
attributeCall.addArgument(new StringLiteralExpr(as.getValue().getValue()));
break;
case "calendars":
String value = as.getValue().getValue().trim();
if (value.startsWith("[")) {
value = value.substring(1, value.length() - 1).trim();
}
Expression arrayExpr = parseExpression("new String[] { " + value + " }");
attributeCall.addArgument(arrayExpr);
break;
case "date-effective":
case "date-expires":
attributeCall.addArgument(parseExpression(String.format("GregorianCalendar.from(LocalDate.parse(\"%s\", dateTimeFormatter).atStartOfDay(ZoneId.systemDefault()))", as.getValue().getValue())));
break;
default:
throw new UnsupportedOperationException("Unhandled case for rule attribute: " + as.getKey());
}
ruleAttributes.add(attributeCall);
}
return ruleAttributes;
}
Aggregations