Search in sources :

Example 6 with RuleBuildContext

use of org.drools.compiler.rule.builder.RuleBuildContext in project drools by kiegroup.

the class MVELEvalBuilderTest method testSimpleExpression.

@Test
public void testSimpleExpression() {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
    final KnowledgeBuilderConfigurationImpl conf = pkgBuilder.getBuilderConfiguration();
    DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect("mvel");
    final RuleBuildContext context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
    final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
    final InternalReadAccessor extractor = store.getReader(Cheese.class, "price");
    final Pattern pattern = new Pattern(0, new ClassObjectType(int.class));
    final Declaration declaration = new Declaration("a", extractor, pattern);
    final Map map = new HashMap();
    map.put("a", declaration);
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);
    final EvalDescr evalDescr = new EvalDescr();
    evalDescr.setContent("a == 10");
    final MVELEvalBuilder builder = new MVELEvalBuilder();
    final EvalCondition eval = (EvalCondition) builder.build(context, evalDescr);
    ((MVELEvalExpression) eval.getEvalExpression()).compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    MockLeftTupleSink sink = new MockLeftTupleSink();
    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, sink, true);
    f0.removeLeftTuple(tuple);
    Object evalContext = eval.createContext();
    assertTrue(eval.isAllowed(tuple, ksession, evalContext));
    cheddar.setPrice(9);
    ksession.update(f0, cheddar);
    assertFalse(eval.isAllowed(tuple, ksession, evalContext));
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) HashMap(java.util.HashMap) MockLeftTupleSink(org.drools.compiler.reteoo.MockLeftTupleSink) Cheese(org.drools.compiler.Cheese) EvalCondition(org.drools.core.rule.EvalCondition) EvalDescr(org.drools.compiler.lang.descr.EvalDescr) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) Declaration(org.drools.core.rule.Declaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Pattern(org.drools.core.rule.Pattern) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) MVELEvalExpression(org.drools.core.base.mvel.MVELEvalExpression) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) HashMap(java.util.HashMap) Map(java.util.Map) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Test(org.junit.Test)

Example 7 with RuleBuildContext

use of org.drools.compiler.rule.builder.RuleBuildContext in project drools by kiegroup.

the class MVELSalienceBuilderTest method setUp.

@Before
public void setUp() throws Exception {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.addAttribute(new AttributeDescr("salience", "(p.age + 20)/2"));
    ruleDescr.setConsequence("");
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
    DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect("mvel");
    context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
    final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
    final ObjectType personObjeectType = new ClassObjectType(Person.class);
    final Pattern pattern = new Pattern(0, personObjeectType);
    final PatternExtractor extractor = new PatternExtractor(personObjeectType);
    final Declaration declaration = new Declaration("p", extractor, pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("p", declaration);
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);
    kBase = KnowledgeBaseFactory.newKnowledgeBase();
    SalienceBuilder salienceBuilder = new MVELSalienceBuilder();
    salienceBuilder.build(context);
    ((MVELSalienceExpression) context.getRule().getSalience()).compile((MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel"));
}
Also used : Pattern(org.drools.core.rule.Pattern) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) ClassObjectType(org.drools.core.base.ClassObjectType) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) HashMap(java.util.HashMap) SalienceBuilder(org.drools.compiler.rule.builder.SalienceBuilder) PatternExtractor(org.drools.core.spi.PatternExtractor) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) MVELSalienceExpression(org.drools.core.base.mvel.MVELSalienceExpression) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) Declaration(org.drools.core.rule.Declaration) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) AttributeDescr(org.drools.compiler.lang.descr.AttributeDescr) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Before(org.junit.Before)

Example 8 with RuleBuildContext

use of org.drools.compiler.rule.builder.RuleBuildContext in project drools by kiegroup.

the class JavaConsequenceBuilderPRAlwaysTest method setupTest.

private void setupTest(String consequence, Map<String, Object> namedConsequences) {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools");
    pkg.addImport(new ImportDeclaration("org.drools.compiler.Cheese"));
    KnowledgeBuilderConfigurationImpl conf = new KnowledgeBuilderConfigurationImpl();
    // Although it should be the default, for completeness we explicit this is the test cases how RHS should be rewritten as:
    conf.setOption(PropertySpecificOption.ALWAYS);
    KnowledgeBuilderImpl kBuilder = new KnowledgeBuilderImpl(pkg, conf);
    ruleDescr = new RuleDescr("test consequence builder");
    ruleDescr.setConsequence(consequence);
    for (Entry<String, Object> entry : namedConsequences.entrySet()) {
        ruleDescr.addNamedConsequences(entry.getKey(), entry.getValue());
    }
    RuleImpl rule = ruleDescr.toRule();
    PackageRegistry pkgRegistry = kBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry reg = kBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    context = new RuleBuildContext(kBuilder, ruleDescr, reg, pkg, reg.getDialect(pkgRegistry.getDialect()));
    rule.addPattern(new Pattern(0, new ClassObjectType(Cheese.class), "$cheese"));
    Pattern p = new Pattern(1, new ClassObjectType(Person.class), "$persone");
    Declaration declr = p.addDeclaration("age");
    final InternalReadAccessor extractor = PatternBuilder.getFieldReadAccessor(context, new BindingDescr("age", "age"), p, "age", declr, true);
    rule.addPattern(p);
    context.getDeclarationResolver().pushOnBuildStack(rule.getLhs());
    context.getDialect().getConsequenceBuilder().build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    for (String name : namedConsequences.keySet()) {
        context.getDialect().getConsequenceBuilder().build(context, name);
    }
    context.getDialect().addRule(context);
    pkgRegistry.getPackage().addRule(context.getRule());
    kBuilder.compileAll();
    kBuilder.reloadAll();
}
Also used : Pattern(org.drools.core.rule.Pattern) BindingDescr(org.drools.compiler.lang.descr.BindingDescr) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) ClassObjectType(org.drools.core.base.ClassObjectType) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) ImportDeclaration(org.drools.core.rule.ImportDeclaration) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) Declaration(org.drools.core.rule.Declaration) ImportDeclaration(org.drools.core.rule.ImportDeclaration) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) Person(org.drools.compiler.Person) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 9 with RuleBuildContext

use of org.drools.compiler.rule.builder.RuleBuildContext in project drools by kiegroup.

the class JavaConsequenceBuilderTest method setupTest.

private void setupTest(String consequence, Map<String, Object> namedConsequences) {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools");
    pkg.addImport(new ImportDeclaration("org.drools.compiler.Cheese"));
    KnowledgeBuilderConfigurationImpl conf = new KnowledgeBuilderConfigurationImpl();
    // this test was originally intended with PropertyReactive.ALLOWED:
    conf.setOption(PropertySpecificOption.ALLOWED);
    KnowledgeBuilderImpl kBuilder = new KnowledgeBuilderImpl(pkg, conf);
    ruleDescr = new RuleDescr("test consequence builder");
    ruleDescr.setConsequence(consequence);
    for (Entry<String, Object> entry : namedConsequences.entrySet()) {
        ruleDescr.addNamedConsequences(entry.getKey(), entry.getValue());
    }
    RuleImpl rule = ruleDescr.toRule();
    PackageRegistry pkgRegistry = kBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry reg = kBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    context = new RuleBuildContext(kBuilder, ruleDescr, reg, pkg, reg.getDialect(pkgRegistry.getDialect()));
    rule.addPattern(new Pattern(0, new ClassObjectType(Cheese.class), "$cheese"));
    Pattern p = new Pattern(1, new ClassObjectType(Person.class), "$persone");
    Declaration declr = p.addDeclaration("age");
    final InternalReadAccessor extractor = PatternBuilder.getFieldReadAccessor(context, new BindingDescr("age", "age"), p, "age", declr, true);
    rule.addPattern(p);
    context.getDeclarationResolver().pushOnBuildStack(rule.getLhs());
    context.getDialect().getConsequenceBuilder().build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    for (String name : namedConsequences.keySet()) {
        context.getDialect().getConsequenceBuilder().build(context, name);
    }
    context.getDialect().addRule(context);
    pkgRegistry.getPackage().addRule(context.getRule());
    kBuilder.compileAll();
    kBuilder.reloadAll();
}
Also used : Pattern(org.drools.core.rule.Pattern) BindingDescr(org.drools.compiler.lang.descr.BindingDescr) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) ClassObjectType(org.drools.core.base.ClassObjectType) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) ImportDeclaration(org.drools.core.rule.ImportDeclaration) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) Declaration(org.drools.core.rule.Declaration) ImportDeclaration(org.drools.core.rule.ImportDeclaration) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) Person(org.drools.compiler.Person) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 10 with RuleBuildContext

use of org.drools.compiler.rule.builder.RuleBuildContext in project drools by kiegroup.

the class MVELDialect method getMVELCompilationUnit.

public MVELCompilationUnit getMVELCompilationUnit(final String expression, final AnalysisResult analysis, Declaration[] previousDeclarations, Declaration[] localDeclarations, final Map<String, Class<?>> otherInputVariables, final PackageBuildContext context, String contextIndeifier, Class kcontextClass, boolean readLocalsFromTuple, MVELCompilationUnit.Scope scope) {
    Map<String, Class> resolvedInputs = new LinkedHashMap<String, Class>();
    List<String> ids = new ArrayList<String>();
    if (analysis.getBoundIdentifiers().getThisClass() != null || (localDeclarations != null && localDeclarations.length > 0)) {
        Class cls = analysis.getBoundIdentifiers().getThisClass();
        ids.add("this");
        resolvedInputs.put("this", // the only time cls is null is in accumumulate's acc/reverse
        (cls != null) ? cls : Object.class);
    }
    ids.add(contextIndeifier);
    resolvedInputs.put(contextIndeifier, kcontextClass);
    ids.add("kcontext");
    resolvedInputs.put("kcontext", kcontextClass);
    if (scope.hasRule()) {
        ids.add("rule");
        resolvedInputs.put("rule", Rule.class);
    }
    List<String> strList = new ArrayList<String>();
    for (String identifier : analysis.getIdentifiers()) {
        Class<?> type = analysis.getBoundIdentifiers().resolveVarType(identifier);
        if (type != null) {
            strList.add(identifier);
            ids.add(identifier);
            resolvedInputs.put(identifier, type);
        }
    }
    String[] globalIdentifiers = strList.toArray(new String[strList.size()]);
    strList.clear();
    for (String op : analysis.getBoundIdentifiers().getOperators().keySet()) {
        strList.add(op);
        ids.add(op);
        resolvedInputs.put(op, context.getConfiguration().getComponentFactory().getExpressionProcessor().getEvaluatorWrapperClass());
    }
    EvaluatorWrapper[] operators = new EvaluatorWrapper[strList.size()];
    for (int i = 0; i < operators.length; i++) {
        operators[i] = analysis.getBoundIdentifiers().getOperators().get(strList.get(i));
    }
    if (previousDeclarations != null) {
        for (Declaration decl : previousDeclarations) {
            if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) {
                ids.add(decl.getIdentifier());
                resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass());
            }
        }
    }
    if (localDeclarations != null) {
        for (Declaration decl : localDeclarations) {
            if (analysis.getBoundIdentifiers().getDeclrClasses().containsKey(decl.getIdentifier())) {
                ids.add(decl.getIdentifier());
                resolvedInputs.put(decl.getIdentifier(), decl.getDeclarationClass());
            }
        }
    }
    // "not bound" identifiers could be drools, kcontext and rule
    // but in the case of accumulate it could be vars from the "init" section.
    // String[] otherIdentifiers = otherInputVariables == null ? new String[]{} : new String[otherInputVariables.size()];
    strList = new ArrayList<String>();
    if (otherInputVariables != null) {
        MVELAnalysisResult mvelAnalysis = (MVELAnalysisResult) analysis;
        for (Entry<String, Class<?>> stringClassEntry : otherInputVariables.entrySet()) {
            if ((!analysis.getNotBoundedIdentifiers().contains(stringClassEntry.getKey()) && !mvelAnalysis.getMvelVariables().keySet().contains(stringClassEntry.getKey())) || "rule".equals(stringClassEntry.getKey())) {
                // and rule was already included
                continue;
            }
            ids.add(stringClassEntry.getKey());
            strList.add(stringClassEntry.getKey());
            resolvedInputs.put(stringClassEntry.getKey(), stringClassEntry.getValue());
        }
    }
    String[] otherIdentifiers = strList.toArray(new String[strList.size()]);
    String[] inputIdentifiers = new String[resolvedInputs.size()];
    String[] inputTypes = new String[resolvedInputs.size()];
    int i = 0;
    for (String id : ids) {
        inputIdentifiers[i] = id;
        inputTypes[i++] = resolvedInputs.get(id).getName();
    }
    String name;
    if (context != null && context.getPkg() != null && context.getPkg().getName() != null) {
        if (context instanceof RuleBuildContext) {
            name = context.getPkg().getName() + "." + ((RuleBuildContext) context).getRuleDescr().getClassName();
        } else {
            name = context.getPkg().getName() + ".Unknown";
        }
    } else {
        name = "Unknown";
    }
    return new MVELCompilationUnit(name, expression, globalIdentifiers, operators, previousDeclarations, localDeclarations, otherIdentifiers, inputIdentifiers, inputTypes, languageLevel, ((MVELAnalysisResult) analysis).isTypesafe(), readLocalsFromTuple);
}
Also used : EvaluatorWrapper(org.drools.core.base.EvaluatorWrapper) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) ArrayList(java.util.ArrayList) MVELCompilationUnit(org.drools.core.base.mvel.MVELCompilationUnit) LinkedHashMap(java.util.LinkedHashMap) Declaration(org.drools.core.rule.Declaration)

Aggregations

RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)35 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)24 DialectCompiletimeRegistry (org.drools.compiler.compiler.DialectCompiletimeRegistry)23 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)22 Test (org.junit.Test)18 RuleDescr (org.drools.drl.ast.descr.RuleDescr)17 Pattern (org.drools.core.rule.Pattern)16 ClassObjectType (org.drools.core.base.ClassObjectType)15 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)15 KnowledgeBuilderConfigurationImpl (org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl)14 Declaration (org.drools.core.rule.Declaration)14 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)13 HashMap (java.util.HashMap)12 PackageRegistry (org.drools.compiler.compiler.PackageRegistry)11 ImportDeclaration (org.drools.core.rule.ImportDeclaration)11 InternalFactHandle (org.drools.core.common.InternalFactHandle)8 KnowledgePackageImpl (org.drools.core.definitions.impl.KnowledgePackageImpl)8 LeftTupleImpl (org.drools.core.reteoo.LeftTupleImpl)8 ObjectType (org.drools.core.spi.ObjectType)7 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)6