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