Search in sources :

Example 31 with AttributeDescr

use of org.drools.drl.ast.descr.AttributeDescr in project drools by kiegroup.

the class RuleParserTest method testAutofocus.

@Test
public void testAutofocus() throws Exception {
    final RuleDescr rule = (RuleDescr) parseResource("rule", "autofocus.drl");
    assertFalse(parser.getErrors().toString(), parser.hasErrors());
    assertNotNull(rule);
    assertEquals("rule1", rule.getName());
    final AttributeDescr att = (AttributeDescr) rule.getAttributes().get("auto-focus");
    assertEquals("true", att.getValue());
    assertEquals("auto-focus", att.getName());
}
Also used : RuleDescr(org.drools.drl.ast.descr.RuleDescr) AttributeDescr(org.drools.drl.ast.descr.AttributeDescr) Test(org.junit.Test)

Example 32 with AttributeDescr

use of org.drools.drl.ast.descr.AttributeDescr in project drools by kiegroup.

the class RuleParserTest method testAttributes_alternateSyntax.

@Test
public void testAttributes_alternateSyntax() throws Exception {
    final RuleDescr rule = (RuleDescr) parseResource("rule", "rule_attributes_alt.drl");
    assertEquals("simple_rule", rule.getName());
    assertEqualsIgnoreWhitespace("bar();", (String) rule.getConsequence());
    final Map<String, AttributeDescr> attrs = rule.getAttributes();
    assertEquals(6, attrs.size());
    AttributeDescr at = (AttributeDescr) attrs.get("salience");
    assertEquals("salience", at.getName());
    assertEquals("42", at.getValue());
    at = (AttributeDescr) attrs.get("agenda-group");
    assertEquals("agenda-group", at.getName());
    assertEquals("my_group", at.getValue());
    at = (AttributeDescr) attrs.get("no-loop");
    assertEquals("no-loop", at.getName());
    assertEquals("true", at.getValue());
    at = (AttributeDescr) attrs.get("lock-on-active");
    assertEquals("lock-on-active", at.getName());
    assertEquals("true", at.getValue());
    at = (AttributeDescr) attrs.get("duration");
    assertEquals("duration", at.getName());
    assertEquals("42", at.getValue());
    at = (AttributeDescr) attrs.get("activation-group");
    assertEquals("activation-group", at.getName());
    assertEquals("my_activation_group", at.getValue());
}
Also used : RuleDescr(org.drools.drl.ast.descr.RuleDescr) AttributeDescr(org.drools.drl.ast.descr.AttributeDescr) Test(org.junit.Test)

Example 33 with AttributeDescr

use of org.drools.drl.ast.descr.AttributeDescr in project drools by kiegroup.

the class CompositePackageDescr method internalAdd.

private void internalAdd(Resource resource, PackageDescr packageDescr) {
    for (ImportDescr descr : packageDescr.getImports()) {
        addImport(descr);
        descr.setResource(resource);
    }
    for (FunctionImportDescr descr : packageDescr.getFunctionImports()) {
        addFunctionImport(descr);
        descr.setResource(resource);
    }
    for (AccumulateImportDescr descr : packageDescr.getAccumulateImports()) {
        addAccumulateImport(descr);
        descr.setResource(resource);
    }
    for (AttributeDescr descr : packageDescr.getAttributes()) {
        addAttribute(descr);
        descr.setResource(resource);
    }
    for (GlobalDescr descr : packageDescr.getGlobals()) {
        addGlobal(descr);
        descr.setResource(resource);
    }
    for (FunctionDescr descr : packageDescr.getFunctions()) {
        addFunction(descr);
        descr.setResource(resource);
    }
    for (RuleDescr descr : packageDescr.getRules()) {
        addRule(descr);
        descr.setResource(resource);
    }
    // Avoid adding the same type declaration twice, see
    // TypeDeclarationTest.testDuplicatedTypeDeclarationInDifferentResources
    // IncrementalCompilationTest.testIncrementalCompilationWithAmbiguousRedeclares
    // RHDM-1738
    Set<TypeDeclarationDescr> typeDeclarationDescrs = new HashSet<>(getTypeDeclarations());
    for (TypeDeclarationDescr descr : packageDescr.getTypeDeclarations()) {
        if (!typeDeclarationDescrs.contains(descr)) {
            addTypeDeclaration(descr);
            descr.setResource(resource);
        }
    }
    for (EnumDeclarationDescr enumDescr : packageDescr.getEnumDeclarations()) {
        addEnumDeclaration(enumDescr);
        enumDescr.setResource(resource);
    }
    for (EntryPointDeclarationDescr descr : packageDescr.getEntryPointDeclarations()) {
        addEntryPointDeclaration(descr);
        descr.setResource(resource);
    }
    for (WindowDeclarationDescr descr : packageDescr.getWindowDeclarations()) {
        addWindowDeclaration(descr);
        descr.setResource(resource);
    }
    packageDescr.getPreferredPkgUUID().ifPresent(pkgUUID -> {
        if (getPreferredPkgUUID().isPresent() && !pkgUUID.equals(getPreferredPkgUUID().get())) {
            throw new RuntimeException(String.format("Trying to overwrite preferredPkgUUID %s with a different value %s", getPreferredPkgUUID().get(), pkgUUID));
        }
        setPreferredPkgUUID(pkgUUID);
    });
}
Also used : GlobalDescr(org.drools.drl.ast.descr.GlobalDescr) FunctionImportDescr(org.drools.drl.ast.descr.FunctionImportDescr) TypeDeclarationDescr(org.drools.drl.ast.descr.TypeDeclarationDescr) AccumulateImportDescr(org.drools.drl.ast.descr.AccumulateImportDescr) EntryPointDeclarationDescr(org.drools.drl.ast.descr.EntryPointDeclarationDescr) AccumulateImportDescr(org.drools.drl.ast.descr.AccumulateImportDescr) FunctionImportDescr(org.drools.drl.ast.descr.FunctionImportDescr) ImportDescr(org.drools.drl.ast.descr.ImportDescr) FunctionDescr(org.drools.drl.ast.descr.FunctionDescr) EnumDeclarationDescr(org.drools.drl.ast.descr.EnumDeclarationDescr) RuleDescr(org.drools.drl.ast.descr.RuleDescr) AttributeDescr(org.drools.drl.ast.descr.AttributeDescr) WindowDeclarationDescr(org.drools.drl.ast.descr.WindowDeclarationDescr) HashSet(java.util.HashSet)

Example 34 with AttributeDescr

use of org.drools.drl.ast.descr.AttributeDescr 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) {
    final List<MethodCallExpr> ruleAttributes = new ArrayList<>();
    final Set<Entry<String, AttributeDescr>> excludingDialect = ruleDescr.getAttributes().entrySet().stream().filter(r -> !r.getKey().equals("dialect")).collect(Collectors.toSet());
    for (Entry<String, AttributeDescr> as : excludingDialect) {
        MethodCallExpr attributeCall = new MethodCallExpr(null, ATTRIBUTE_CALL);
        attributeCall.addArgument(attributesMap.get(as.getKey()));
        String value = as.getValue().getValue().trim();
        switch(as.getKey()) {
            case "salience":
                try {
                    Integer.parseInt(value);
                    attributeCall.addArgument(value);
                } catch (NumberFormatException nfe) {
                    addDynamicAttributeArgument(context, attributeCall, value, int.class);
                }
                break;
            case "enabled":
                if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) {
                    attributeCall.addArgument(value.toLowerCase());
                } else {
                    addDynamicAttributeArgument(context, attributeCall, value, boolean.class);
                }
                break;
            case "no-loop":
            case "auto-focus":
            case "lock-on-active":
                attributeCall.addArgument(value);
                break;
            case "agenda-group":
            case "activation-group":
            case "ruleflow-group":
            case "duration":
                attributeCall.addArgument(toStringLiteral(value));
                break;
            case "timer":
                if (validateTimer(value)) {
                    attributeCall.addArgument(toStringLiteral(value));
                } else {
                    context.addCompilationError(new InvalidExpressionErrorResult(value));
                }
                break;
            case "calendars":
                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("java.util.GregorianCalendar.from(java.time.LocalDate.parse(\"%s\", " + DATE_TIME_FORMATTER_FIELD + ").atStartOfDay(java.time.ZoneId.systemDefault()))", as.getValue().getValue())));
                break;
            default:
                throw new UnsupportedOperationException("Unhandled case for rule attribute: " + as.getKey());
        }
        ruleAttributes.add(attributeCall);
    }
    return ruleAttributes;
}
Also used : ClassExpr(com.github.javaparser.ast.expr.ClassExpr) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) ModelGeneratorVisitor(org.drools.modelcompiler.builder.generator.visitor.ModelGeneratorVisitor) AnnotationDescr(org.drools.drl.ast.descr.AnnotationDescr) TypeResolver(org.drools.core.addon.TypeResolver) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) AttributeDescr(org.drools.drl.ast.descr.AttributeDescr) BehaviorDescr(org.drools.drl.ast.descr.BehaviorDescr) InvalidExpressionErrorResult(org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult) ExpressionTyperContext(org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyperContext) ClassUtil.asJavaSourceName(org.drools.modelcompiler.util.ClassUtil.asJavaSourceName) NullLiteralExpr(com.github.javaparser.ast.expr.NullLiteralExpr) ParseExpressionErrorResult(org.drools.modelcompiler.builder.errors.ParseExpressionErrorResult) Type(com.github.javaparser.ast.type.Type) DrlxParseUtil.generateLambdaWithoutParameters(org.drools.modelcompiler.builder.generator.DrlxParseUtil.generateLambdaWithoutParameters) Map(java.util.Map) Expression(com.github.javaparser.ast.expr.Expression) BUILD_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.BUILD_CALL) DEFAULT_RULE_UNIT(org.drools.kiesession.session.StatefulKnowledgeSessionImpl.DEFAULT_RULE_UNIT) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) PackageModel(org.drools.modelcompiler.builder.PackageModel) NodeList(com.github.javaparser.ast.NodeList) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) Set(java.util.Set) StaticJavaParser.parseExpression(com.github.javaparser.StaticJavaParser.parseExpression) Collectors(java.util.stream.Collectors) StringLiteralExpr(com.github.javaparser.ast.expr.StringLiteralExpr) TimerUtil.validateTimer(org.drools.modelcompiler.util.TimerUtil.validateTimer) Modifier(com.github.javaparser.ast.Modifier) VariableDeclarationExpr(com.github.javaparser.ast.expr.VariableDeclarationExpr) CoreComponentsBuilder(org.drools.core.base.CoreComponentsBuilder) METADATA_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.METADATA_CALL) List(java.util.List) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) AnnotationDefinition(org.drools.core.factmodel.AnnotationDefinition) Entry(java.util.Map.Entry) Optional(java.util.Optional) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ATTRIBUTE_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.ATTRIBUTE_CALL) DrlxParseUtil.toStringLiteral(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toStringLiteral) DOMAIN_CLASS_METADATA_INSTANCE(org.drools.modelcompiler.builder.PackageModel.DOMAIN_CLASS_METADATA_INSTANCE) RuleDescr(org.drools.drl.ast.descr.RuleDescr) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) HashMap(java.util.HashMap) Behavior(org.drools.core.rule.Behavior) ENTRY_POINT_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.ENTRY_POINT_CALL) QueryDescr(org.drools.drl.ast.descr.QueryDescr) RuleUnitDescription(org.kie.internal.ruleunit.RuleUnitDescription) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) WINDOW_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.WINDOW_CALL) DslMethodNames.createDslTopLevelMethod(org.drools.modelcompiler.builder.generator.DslMethodNames.createDslTopLevelMethod) AndDescr(org.drools.drl.ast.descr.AndDescr) DATE_TIME_FORMATTER_FIELD(org.drools.modelcompiler.builder.PackageModel.DATE_TIME_FORMATTER_FIELD) Variable(org.drools.model.Variable) PackageDescr(org.drools.drl.ast.descr.PackageDescr) AssignExpr(com.github.javaparser.ast.expr.AssignExpr) SUPPLY_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.SUPPLY_CALL) DrlxParseUtil.toClassOrInterfaceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.toClassOrInterfaceType) DECLARATION_OF_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.DECLARATION_OF_CALL) DOMAIN_CLASSESS_METADATA_FILE_NAME(org.drools.modelcompiler.builder.PackageModel.DOMAIN_CLASSESS_METADATA_FILE_NAME) StringUtil.toId(org.drools.modelcompiler.util.StringUtil.toId) TimeUtils(org.drools.core.time.TimeUtils) UnknownDeclarationError(org.drools.modelcompiler.builder.errors.UnknownDeclarationError) ExpressionTyper(org.drools.modelcompiler.builder.generator.expressiontyper.ExpressionTyper) DrlxParseUtil.classToReferenceType(org.drools.modelcompiler.builder.generator.DrlxParseUtil.classToReferenceType) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) Rule(org.drools.model.Rule) RULE_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.RULE_CALL) UNIT_CALL(org.drools.modelcompiler.builder.generator.DslMethodNames.UNIT_CALL) ArrayList(java.util.ArrayList) Entry(java.util.Map.Entry) InvalidExpressionErrorResult(org.drools.modelcompiler.builder.errors.InvalidExpressionErrorResult) Expression(com.github.javaparser.ast.expr.Expression) StaticJavaParser.parseExpression(com.github.javaparser.StaticJavaParser.parseExpression) AttributeDescr(org.drools.drl.ast.descr.AttributeDescr) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Aggregations

AttributeDescr (org.drools.drl.ast.descr.AttributeDescr)34 RuleDescr (org.drools.drl.ast.descr.RuleDescr)26 Test (org.junit.Test)21 PackageDescr (org.drools.drl.ast.descr.PackageDescr)13 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)7 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)6 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)6 RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)5 DialectCompiletimeRegistry (org.drools.compiler.compiler.DialectCompiletimeRegistry)4 HashSet (java.util.HashSet)3 List (java.util.List)3 Pattern (org.drools.core.rule.Pattern)3 AndDescr (org.drools.drl.ast.descr.AndDescr)3 FunctionImportDescr (org.drools.drl.ast.descr.FunctionImportDescr)3 ImportDescr (org.drools.drl.ast.descr.ImportDescr)3 ArrayList (java.util.ArrayList)2 Calendar (java.util.Calendar)2 HashMap (java.util.HashMap)2 KnowledgeBuilderConfigurationImpl (org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl)2 PackageRegistry (org.drools.compiler.compiler.PackageRegistry)2