Search in sources :

Example 6 with MVELDialect

use of org.drools.mvel.builder.MVELDialect in project drools by kiegroup.

the class MVELEvalBuilderTest method testSimpleExpression.

@Test
public void testSimpleExpression() {
    InternalKnowledgePackage pkg = CoreComponentFactory.get().createKnowledgePackage("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();
    BuildContext buildContext = new BuildContext(kBase, Collections.emptyList());
    org.drools.core.reteoo.MockLeftTupleSink sink = new MockLeftTupleSink(buildContext);
    MockTupleSource source = new MockTupleSource(1, buildContext);
    source.setObjectCount(1);
    sink.setLeftTupleSource(source);
    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.core.reteoo.MockLeftTupleSink) Cheese(org.drools.mvel.compiler.Cheese) EvalCondition(org.drools.core.rule.EvalCondition) MockTupleSource(org.drools.core.reteoo.MockTupleSource) EvalDescr(org.drools.drl.ast.descr.EvalDescr) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) MVELEvalBuilder(org.drools.mvel.builder.MVELEvalBuilder) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) Declaration(org.drools.core.rule.Declaration) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.kiesession.rulebase.InternalKnowledgeBase) Pattern(org.drools.core.rule.Pattern) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) MVELDialect(org.drools.mvel.builder.MVELDialect) MVELEvalExpression(org.drools.mvel.expr.MVELEvalExpression) MockLeftTupleSink(org.drools.core.reteoo.MockLeftTupleSink) BuildContext(org.drools.core.reteoo.builder.BuildContext) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) RuleDescr(org.drools.drl.ast.descr.RuleDescr) HashMap(java.util.HashMap) Map(java.util.Map) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Test(org.junit.Test)

Example 7 with MVELDialect

use of org.drools.mvel.builder.MVELDialect in project drools by kiegroup.

the class MVELSalienceBuilderTest method setUp.

@Before
public void setUp() throws Exception {
    InternalKnowledgePackage pkg = CoreComponentFactory.get().createKnowledgePackage("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();
    buildContext = new BuildContext(kBase, Collections.emptyList());
    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) MVELSalienceBuilder(org.drools.mvel.builder.MVELSalienceBuilder) PatternExtractor(org.drools.core.spi.PatternExtractor) MVELDialect(org.drools.mvel.builder.MVELDialect) MVELSalienceBuilder(org.drools.mvel.builder.MVELSalienceBuilder) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) BuildContext(org.drools.core.reteoo.builder.BuildContext) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) MVELSalienceExpression(org.drools.mvel.expr.MVELSalienceExpression) RuleDescr(org.drools.drl.ast.descr.RuleDescr) Declaration(org.drools.core.rule.Declaration) AttributeDescr(org.drools.drl.ast.descr.AttributeDescr) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Before(org.junit.Before)

Example 8 with MVELDialect

use of org.drools.mvel.builder.MVELDialect in project drools by kiegroup.

the class MVELConstraintBuilder method buildMvelFieldReadAccessor.

@Override
public InternalReadAccessor buildMvelFieldReadAccessor(RuleBuildContext context, BaseDescr descr, Pattern pattern, ObjectType objectType, String fieldName, boolean reportError) {
    InternalReadAccessor reader;
    Dialect dialect = context.getDialect();
    try {
        MVELDialect mvelDialect = (MVELDialect) context.getDialect("mvel");
        context.setDialect(mvelDialect);
        final AnalysisResult analysis = context.getDialect().analyzeExpression(context, descr, fieldName, new BoundIdentifiers(pattern, context, Collections.EMPTY_MAP, objectType));
        if (analysis == null) {
            // something bad happened
            if (reportError) {
                registerDescrBuildError(context, descr, "Unable to analyze expression '" + fieldName + "'");
            }
            return null;
        }
        final BoundIdentifiers usedIdentifiers = analysis.getBoundIdentifiers();
        if (!usedIdentifiers.getGlobals().isEmpty()) {
            // cannot create a read accessors here when using globals
            return null;
        }
        if (!usedIdentifiers.getDeclrClasses().isEmpty()) {
            if (reportError && descr instanceof BindingDescr) {
                registerDescrBuildError(context, descr, "Variables can not be used inside bindings. Variable " + usedIdentifiers.getDeclrClasses().keySet() + " is being used in binding '" + fieldName + "'");
            }
            return null;
        }
        reader = ((MVELKnowledgePackageImpl) context.getPkg()).getClassFieldAccessorStore().getMVELReader(context.getPkg().getName(), objectType.getClassName(), fieldName, context.isTypesafe(), ((MVELAnalysisResult) analysis).getReturnType());
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        ((MVELCompileable) reader).compile(data, context.getRule());
        data.addCompileable((MVELCompileable) reader);
    } catch (final Exception e) {
        if (reportError) {
            AsmUtil.copyErrorLocation(e, descr);
            registerDescrBuildError(context, descr, e, "Unable to create reader for '" + fieldName + "':" + e.getMessage());
        }
        // if there was an error, set the reader back to null
        reader = null;
    } finally {
        context.setDialect(dialect);
    }
    return reader;
}
Also used : BindingDescr(org.drools.drl.ast.descr.BindingDescr) MVELCompileable(org.drools.mvel.expr.MVELCompileable) MVELAnalysisResult(org.drools.mvel.builder.MVELAnalysisResult) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) MVELDialect(org.drools.mvel.builder.MVELDialect) Dialect(org.drools.compiler.compiler.Dialect) MVELDialect(org.drools.mvel.builder.MVELDialect) AnalysisResult(org.drools.compiler.compiler.AnalysisResult) MVELAnalysisResult(org.drools.mvel.builder.MVELAnalysisResult) IOException(java.io.IOException) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers)

Example 9 with MVELDialect

use of org.drools.mvel.builder.MVELDialect in project drools by kiegroup.

the class MVELConstraintBuilder method buildCompilationUnit.

private MVELCompilationUnit buildCompilationUnit(final RuleBuildContext context, final Declaration[] previousDeclarations, final Declaration[] localDeclarations, final PredicateDescr predicateDescr, final AnalysisResult analysis) {
    if (context.isTypesafe() && analysis instanceof MVELAnalysisResult) {
        Class<?> returnClass = ((MVELAnalysisResult) analysis).getReturnType();
        if (returnClass != Boolean.class && returnClass != Boolean.TYPE) {
            context.addError(new DescrBuildError(context.getParentDescr(), predicateDescr, null, "Predicate '" + predicateDescr.getContent() + "' must be a Boolean expression\n" + predicateDescr.positionAsString()));
        }
    }
    MVELDialect dialect = (MVELDialect) context.getDialect("mvel");
    MVELCompilationUnit unit = null;
    try {
        Map<String, Class<?>> declIds = context.getDeclarationResolver().getDeclarationClasses(context.getRule());
        Pattern p = (Pattern) context.getDeclarationResolver().peekBuildStack();
        if (p.getObjectType() instanceof ClassObjectType) {
            declIds.put("this", ((ClassObjectType) p.getObjectType()).getClassType());
        }
        unit = dialect.getMVELCompilationUnit((String) predicateDescr.getContent(), analysis, previousDeclarations, localDeclarations, null, context, "drools", KnowledgeHelper.class, context.isInXpath(), MVELCompilationUnit.Scope.CONSTRAINT);
    } catch (final Exception e) {
        copyErrorLocation(e, predicateDescr);
        context.addError(new DescrBuildError(context.getParentDescr(), predicateDescr, e, "Unable to build expression for 'inline-eval' : " + e.getMessage() + "'" + predicateDescr.getContent() + "'\n" + e.getMessage()));
    }
    return unit;
}
Also used : Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) MVELCompilationUnit(org.drools.mvel.expr.MVELCompilationUnit) MVELDialect(org.drools.mvel.builder.MVELDialect) IOException(java.io.IOException) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) PatternBuilder.registerDescrBuildError(org.drools.compiler.rule.builder.PatternBuilder.registerDescrBuildError) MVELAnalysisResult(org.drools.mvel.builder.MVELAnalysisResult) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper)

Aggregations

MVELDialect (org.drools.mvel.builder.MVELDialect)9 Declaration (org.drools.core.rule.Declaration)6 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)5 DialectCompiletimeRegistry (org.drools.compiler.compiler.DialectCompiletimeRegistry)5 RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)5 ClassObjectType (org.drools.core.base.ClassObjectType)5 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)5 Pattern (org.drools.core.rule.Pattern)5 RuleDescr (org.drools.drl.ast.descr.RuleDescr)5 HashMap (java.util.HashMap)4 InternalFactHandle (org.drools.core.common.InternalFactHandle)4 LeftTupleImpl (org.drools.core.reteoo.LeftTupleImpl)4 BuildContext (org.drools.core.reteoo.builder.BuildContext)4 InternalKnowledgeBase (org.drools.kiesession.rulebase.InternalKnowledgeBase)4 StatefulKnowledgeSessionImpl (org.drools.kiesession.session.StatefulKnowledgeSessionImpl)4 MVELAnalysisResult (org.drools.mvel.builder.MVELAnalysisResult)4 Cheese (org.drools.mvel.compiler.Cheese)4 Test (org.junit.Test)4 IOException (java.io.IOException)3 KnowledgeBuilderConfigurationImpl (org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl)3