Search in sources :

Example 1 with MVELCompileable

use of org.drools.mvel.expr.MVELCompileable in project drools by kiegroup.

the class MVELAccumulateBuilderTest method testSimpleExpression.

@Test
public void testSimpleExpression() {
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl();
    pkgBuilder.addPackage(new PackageDescr("pkg1"));
    InternalKnowledgePackage pkg = pkgBuilder.getPackage("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    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 AccumulateDescr accDescr = new AccumulateDescr();
    final PatternDescr inputPattern = new PatternDescr("org.drools.mvel.compiler.Cheese", "$cheese");
    accDescr.setInputPattern(inputPattern);
    accDescr.setInitCode("total = 0;");
    accDescr.setActionCode("total += $cheese.price;");
    accDescr.setReverseCode("total -= $cheese.price;");
    accDescr.setResultCode("new Integer(total)");
    final MVELAccumulateBuilder builder = new MVELAccumulateBuilder();
    final Accumulate acc = (Accumulate) builder.build(context, accDescr);
    ((MVELCompileable) acc.getAccumulators()[0]).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());
    MockLeftTupleSink sink = new MockLeftTupleSink(buildContext);
    MockTupleSource source = new MockTupleSource(1, buildContext);
    source.setObjectCount(1);
    sink.setLeftTupleSource(source);
    final Cheese cheddar1 = new Cheese("cheddar", 10);
    final Cheese cheddar2 = new Cheese("cheddar", 8);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(new InitialFactImpl());
    final InternalFactHandle f1 = (InternalFactHandle) ksession.insert(cheddar1);
    final InternalFactHandle f2 = (InternalFactHandle) ksession.insert(cheddar2);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, sink, true);
    Object wmContext = acc.createWorkingMemoryContext();
    AccumulateNode.AccumulateContext accContext = new AccumulateNode.AccumulateContext();
    Object funcContext = acc.createFunctionContext();
    funcContext = acc.init(wmContext, accContext, funcContext, tuple, ksession);
    accContext.setFunctionContext(funcContext);
    Object value1 = acc.accumulate(wmContext, accContext, tuple, f1, ksession);
    acc.accumulate(wmContext, accContext, tuple, f2, ksession);
    assertEquals(new Integer(18), acc.getResult(wmContext, accContext, tuple, ksession));
    LeftTuple match = new FromNodeLeftTuple();
    match.setContextObject(value1);
    acc.tryReverse(wmContext, accContext, tuple, f1, null, match, ksession);
    assertEquals(new Integer(8), acc.getResult(wmContext, accContext, tuple, ksession));
}
Also used : MVELCompileable(org.drools.mvel.expr.MVELCompileable) PatternDescr(org.drools.drl.ast.descr.PatternDescr) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) AccumulateNode(org.drools.core.reteoo.AccumulateNode) MockLeftTupleSink(org.drools.core.reteoo.MockLeftTupleSink) Cheese(org.drools.mvel.compiler.Cheese) AccumulateDescr(org.drools.drl.ast.descr.AccumulateDescr) LeftTuple(org.drools.core.reteoo.LeftTuple) FromNodeLeftTuple(org.drools.core.reteoo.FromNodeLeftTuple) Accumulate(org.drools.core.rule.Accumulate) MVELAccumulateBuilder(org.drools.mvel.builder.MVELAccumulateBuilder) FromNodeLeftTuple(org.drools.core.reteoo.FromNodeLeftTuple) MockTupleSource(org.drools.core.reteoo.MockTupleSource) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) PackageDescr(org.drools.drl.ast.descr.PackageDescr) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.kiesession.rulebase.InternalKnowledgeBase) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) MVELDialect(org.drools.mvel.builder.MVELDialect) InitialFactImpl(org.drools.core.reteoo.InitialFactImpl) 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) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Test(org.junit.Test)

Example 2 with MVELCompileable

use of org.drools.mvel.expr.MVELCompileable in project drools by kiegroup.

the class MVELDialectRuntimeData method onBeforeExecute.

public void onBeforeExecute() {
    for (Wireable target : wireList) {
        for (MVELCompileable compileable : invokerLookups.get(target)) {
            compileable.compile(this);
            // now wire up the target
            target.wire(compileable);
        }
    }
    wireList.clear();
    for (MVELCompileable compileable : mvelReaders) {
        compileable.compile(this);
    }
    if (dirty) {
        rewireImportedMethods();
        dirty = false;
    }
}
Also used : MVELCompileable(org.drools.mvel.expr.MVELCompileable) Wireable(org.drools.core.spi.Wireable)

Example 3 with MVELCompileable

use of org.drools.mvel.expr.MVELCompileable 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 4 with MVELCompileable

use of org.drools.mvel.expr.MVELCompileable in project drools by kiegroup.

the class MVELAccumulateBuilder method build.

@SuppressWarnings("unchecked")
public RuleConditionElement build(final RuleBuildContext context, final BaseDescr descr, final Pattern prefixPattern) {
    boolean typesafe = context.isTypesafe();
    try {
        final AccumulateDescr accumDescr = (AccumulateDescr) descr;
        if (!accumDescr.hasValidInput()) {
            return null;
        }
        final RuleConditionBuilder builder = (RuleConditionBuilder) context.getDialect().getBuilder(accumDescr.getInput().getClass());
        // create source CE
        final RuleConditionElement source = builder.build(context, accumDescr.getInput());
        if (source == null) {
            return null;
        }
        MVELDialect dialect = (MVELDialect) context.getDialect();
        Map<String, Declaration> decls = context.getDeclarationResolver().getDeclarations(context.getRule());
        Map<String, Declaration> sourceOuterDeclr = source.getOuterDeclarations();
        Map<String, Class<?>> declarationClasses = DeclarationScopeResolver.getDeclarationClasses(decls);
        declarationClasses.putAll(DeclarationScopeResolver.getDeclarationClasses(sourceOuterDeclr));
        BoundIdentifiers boundIds = new BoundIdentifiers(declarationClasses, context);
        final boolean readLocalsFromTuple = PackageBuilderUtil.isReadLocalsFromTuple(context, accumDescr, source);
        Accumulator[] accumulators;
        if (accumDescr.isExternalFunction()) {
            // uses accumulate functions
            accumulators = buildExternalFunctions(context, accumDescr, dialect, decls, sourceOuterDeclr, boundIds, readLocalsFromTuple, source, declarationClasses);
        } else {
            // it is a custom accumulate
            accumulators = buildCustomAccumulate(context, accumDescr, dialect, decls, sourceOuterDeclr, boundIds, readLocalsFromTuple);
        }
        List<Declaration> requiredDeclarations = new ArrayList<Declaration>();
        for (Accumulator acc : accumulators) {
            MvelAccumulator mvelAcc = (MvelAccumulator) acc;
            Collections.addAll(requiredDeclarations, mvelAcc.getRequiredDeclarations());
        }
        MVELDialectRuntimeData data = (MVELDialectRuntimeData) context.getPkg().getDialectRuntimeRegistry().getDialectData("mvel");
        Accumulate accumulate;
        if (accumDescr.isMultiFunction()) {
            accumulate = new MultiAccumulate(source, requiredDeclarations.toArray(new Declaration[requiredDeclarations.size()]), accumulators, accumulators.length);
            int index = 0;
            for (Accumulator accumulator : accumulators) {
                data.addCompileable(((MultiAccumulate) accumulate).new Wirer(index++), (MVELCompileable) accumulator);
                ((MVELCompileable) accumulator).compile(data, context.getRule());
            }
        } else {
            accumulate = new SingleAccumulate(source, requiredDeclarations.toArray(new Declaration[requiredDeclarations.size()]), accumulators[0]);
            data.addCompileable(((SingleAccumulate) accumulate).new Wirer(), (MVELCompileable) accumulators[0]);
            ((MVELCompileable) accumulators[0]).compile(data, context.getRule());
        }
        return accumulate;
    } catch (Exception e) {
        AsmUtil.copyErrorLocation(e, descr);
        context.addError(new DescrBuildError(context.getParentDescr(), descr, e, "Unable to build expression for 'accumulate' : " + e.getMessage()));
        return null;
    } finally {
        context.setTypesafe(typesafe);
    }
}
Also used : Accumulator(org.drools.core.spi.Accumulator) MVELAccumulator(org.drools.mvel.expr.MVELAccumulator) MvelAccumulator(org.drools.core.spi.MvelAccumulator) MVELCompileable(org.drools.mvel.expr.MVELCompileable) ArrayList(java.util.ArrayList) AccumulateDescr(org.drools.drl.ast.descr.AccumulateDescr) MultiAccumulate(org.drools.core.rule.MultiAccumulate) SingleAccumulate(org.drools.core.rule.SingleAccumulate) Accumulate(org.drools.core.rule.Accumulate) MVELDialectRuntimeData(org.drools.mvel.MVELDialectRuntimeData) Declaration(org.drools.core.rule.Declaration) MultiAccumulate(org.drools.core.rule.MultiAccumulate) RuleConditionBuilder(org.drools.compiler.rule.builder.RuleConditionBuilder) RuleConditionElement(org.drools.core.rule.RuleConditionElement) SingleAccumulate(org.drools.core.rule.SingleAccumulate) MutableTypeConstraint(org.drools.core.rule.MutableTypeConstraint) MVELConstraint(org.drools.mvel.MVELConstraint) Constraint(org.drools.core.spi.Constraint) BoundIdentifiers(org.drools.compiler.compiler.BoundIdentifiers) DescrBuildError(org.drools.compiler.compiler.DescrBuildError) MvelAccumulator(org.drools.core.spi.MvelAccumulator)

Aggregations

MVELCompileable (org.drools.mvel.expr.MVELCompileable)4 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)2 Accumulate (org.drools.core.rule.Accumulate)2 AccumulateDescr (org.drools.drl.ast.descr.AccumulateDescr)2 MVELDialect (org.drools.mvel.builder.MVELDialect)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 KnowledgeBuilderConfigurationImpl (org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl)1 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)1 AnalysisResult (org.drools.compiler.compiler.AnalysisResult)1 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)1 Dialect (org.drools.compiler.compiler.Dialect)1 DialectCompiletimeRegistry (org.drools.compiler.compiler.DialectCompiletimeRegistry)1 RuleBuildContext (org.drools.compiler.rule.builder.RuleBuildContext)1 RuleConditionBuilder (org.drools.compiler.rule.builder.RuleConditionBuilder)1 InternalFactHandle (org.drools.core.common.InternalFactHandle)1 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)1 AccumulateNode (org.drools.core.reteoo.AccumulateNode)1 FromNodeLeftTuple (org.drools.core.reteoo.FromNodeLeftTuple)1 InitialFactImpl (org.drools.core.reteoo.InitialFactImpl)1