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));
}
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;
}
}
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;
}
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);
}
}
Aggregations