Search in sources :

Example 1 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class KiePackagesBuilder method buildPattern.

private Pattern buildPattern(RuleContext ctx, GroupElement group, Condition condition) {
    org.drools.model.Pattern<?> modelPattern = (org.drools.model.Pattern) condition;
    Pattern pattern = addPatternForVariable(ctx, group, modelPattern.getPatternVariable());
    for (Binding binding : modelPattern.getBindings()) {
        Declaration declaration = new Declaration(binding.getBoundVariable().getName(), new LambdaReadAccessor(binding.getBoundVariable().getType(), binding.getBindingFunction()), pattern, true);
        pattern.addDeclaration(declaration);
        if (binding.getReactOn() != null) {
            addFieldsToPatternWatchlist(pattern, binding.getReactOn());
        }
        ctx.addInnerDeclaration(binding.getBoundVariable(), declaration);
    }
    Declaration queryArgDecl = ctx.getQueryDeclaration(modelPattern.getPatternVariable());
    if (queryArgDecl != null) {
        pattern.addConstraint(new UnificationConstraint(queryArgDecl));
    }
    addConstraintsToPattern(ctx, pattern, modelPattern, modelPattern.getConstraint());
    addFieldsToPatternWatchlist(pattern, modelPattern.getWatchedProps());
    return pattern;
}
Also used : Binding(org.drools.model.Binding) QueryCallPattern(org.drools.model.patterns.QueryCallPattern) AccumulatePattern(org.drools.model.AccumulatePattern) Pattern(org.drools.core.rule.Pattern) Declaration(org.drools.core.rule.Declaration) WindowDeclaration(org.drools.core.rule.WindowDeclaration) TypeDeclarationUtil.createTypeDeclaration(org.drools.modelcompiler.util.TypeDeclarationUtil.createTypeDeclaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration) LambdaReadAccessor(org.drools.modelcompiler.constraints.LambdaReadAccessor) UnificationConstraint(org.drools.modelcompiler.constraints.UnificationConstraint)

Example 2 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class KiePackagesBuilder method addPatternForVariable.

private Pattern addPatternForVariable(RuleContext ctx, GroupElement group, Variable patternVariable) {
    Pattern pattern = new Pattern(ctx.getNextPatternIndex(), // offset will be set by ReteooBuilder
    0, getObjectType(patternVariable), patternVariable.getName(), true);
    if (patternVariable instanceof org.drools.model.Declaration) {
        org.drools.model.Declaration decl = (org.drools.model.Declaration) patternVariable;
        if (decl.getSource() != null) {
            if (decl.getSource() instanceof EntryPoint) {
                pattern.setSource(new EntryPointId(((EntryPoint) decl.getSource()).getName()));
            } else if (decl.getSource() instanceof WindowReference) {
                WindowReference<?> window = (WindowReference) decl.getSource();
                if (!ctx.getPkg().getWindowDeclarations().containsKey(window.getName())) {
                    createWindowReference(ctx, window);
                }
                pattern.setSource(new org.drools.core.rule.WindowReference(window.getName()));
            } else if (decl.getSource() instanceof From) {
                From<?> from = (From) decl.getSource();
                DataProvider provider = new LambdaDataProvider(ctx.getDeclaration(from.getVariable()), from.getProvider(), from.isReactive());
                org.drools.core.rule.From fromSource = new org.drools.core.rule.From(provider);
                fromSource.setResultPattern(pattern);
                pattern.setSource(fromSource);
            } else if (decl.getSource() instanceof UnitData) {
                UnitData unitData = (UnitData) decl.getSource();
                pattern.setSource(new EntryPointId(ctx.getRule().getRuleUnitClassName() + "." + unitData.getName()));
            } else {
                throw new UnsupportedOperationException("Unknown source: " + decl.getSource());
            }
        } else {
            Accumulate accSource = ctx.getAccumulateSource(patternVariable);
            if (accSource != null) {
                for (RuleConditionElement element : group.getChildren()) {
                    if (element instanceof Pattern && ((Pattern) element).getSource() == accSource) {
                        if (accSource instanceof MultiAccumulate) {
                            ((Pattern) element).getConstraints().forEach(pattern::addConstraint);
                            ((Pattern) element).getDeclarations().values().forEach(d -> {
                                pattern.addDeclaration(d);
                                d.setPattern(pattern);
                            });
                        }
                        group.getChildren().remove(element);
                        break;
                    }
                }
                pattern.setSource(accSource);
            }
        }
        if (decl.getWindow() != null) {
            pattern.addBehavior(createWindow(decl.getWindow()));
        }
    }
    ctx.registerPattern(patternVariable, pattern);
    return pattern;
}
Also used : QueryCallPattern(org.drools.model.patterns.QueryCallPattern) AccumulatePattern(org.drools.model.AccumulatePattern) Pattern(org.drools.core.rule.Pattern) MultiAccumulate(org.drools.core.rule.MultiAccumulate) EntryPoint(org.drools.model.EntryPoint) From(org.drools.model.From) RuleConditionElement(org.drools.core.rule.RuleConditionElement) WindowReference(org.drools.model.WindowReference) UnitData(org.drools.model.UnitData) MultiAccumulate(org.drools.core.rule.MultiAccumulate) SingleAccumulate(org.drools.core.rule.SingleAccumulate) Accumulate(org.drools.core.rule.Accumulate) LambdaDataProvider(org.drools.modelcompiler.constraints.LambdaDataProvider) DataProvider(org.drools.core.spi.DataProvider) EntryPointId(org.drools.core.rule.EntryPointId) LambdaDataProvider(org.drools.modelcompiler.constraints.LambdaDataProvider) Declaration(org.drools.core.rule.Declaration) WindowDeclaration(org.drools.core.rule.WindowDeclaration) TypeDeclarationUtil.createTypeDeclaration(org.drools.modelcompiler.util.TypeDeclarationUtil.createTypeDeclaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Example 3 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class RuleBuilderTest method testBuildBigDecimalLiteralConstraint.

@Test
public void testBuildBigDecimalLiteralConstraint() throws Exception {
    final PackageDescr pkgDescr = new PackageDescr("org.drools");
    final RuleDescr ruleDescr = new RuleDescr("Test Rule");
    AndDescr andDescr = new AndDescr();
    PatternDescr patDescr = new PatternDescr("java.math.BigDecimal", "$bd");
    ExprConstraintDescr fcd = new ExprConstraintDescr("this == 10");
    patDescr.addConstraint(fcd);
    andDescr.addDescr(patDescr);
    ruleDescr.setLhs(andDescr);
    ruleDescr.setConsequence("");
    pkgDescr.addRule(ruleDescr);
    final KnowledgeBuilderImpl kBuilder = new KnowledgeBuilderImpl();
    kBuilder.addPackage(pkgDescr);
    assertTrue(kBuilder.getErrors().toString(), kBuilder.getErrors().isEmpty());
    final RuleImpl rule = kBuilder.getPackages()[0].getRule("Test Rule");
    final GroupElement and = rule.getLhs();
    final Pattern pat = (Pattern) and.getChildren().get(0);
    if (pat.getConstraints().get(0) instanceof MvelConstraint) {
        final MvelConstraint fc = (MvelConstraint) pat.getConstraints().get(0);
        assertTrue("Wrong class. Expected java.math.BigDecimal. Found: " + fc.getField().getValue().getClass(), fc.getField().getValue() instanceof BigDecimal);
    }
}
Also used : Pattern(org.drools.core.rule.Pattern) PatternDescr(org.drools.compiler.lang.descr.PatternDescr) AndDescr(org.drools.compiler.lang.descr.AndDescr) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) GroupElement(org.drools.core.rule.GroupElement) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) ExprConstraintDescr(org.drools.compiler.lang.descr.ExprConstraintDescr) BigDecimal(java.math.BigDecimal) Test(org.junit.Test)

Example 4 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class MVELConsequenceBuilderTest method testSimpleExpression.

@Test
public void testSimpleExpression() throws Exception {
    PackageDescr pkgDescr = new PackageDescr("pkg1");
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl();
    pkgBuilder.addPackage(pkgDescr);
    InternalKnowledgePackage pkg = pkgBuilder.getPackageRegistry("pkg1").getPackage();
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.setNamespace("pkg1");
    ruleDescr.setConsequence("modify (cheese) {price = 5 };\nretract (cheese)");
    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 ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjeectType, "cheese");
    final GroupElement subrule = new GroupElement(GroupElement.AND);
    subrule.addChild(pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("cheese", pattern.getDeclaration());
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);
    final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
    builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    PropagationContextFactory pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    kBase.addPackage(pkg);
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
    f0.removeLeftTuple(tuple);
    final AgendaItem item = new AgendaItemImpl(0, tuple, 10, pctxFactory.createPropagationContext(1, PropagationContext.Type.DELETION, null, tuple != null ? (TerminalNode) tuple.getTupleSink() : null, null), new RuleTerminalNode(0, new CompositeObjectSinkAdapterTest.MockBetaNode(), context.getRule(), subrule, 0, new BuildContext(kBase)), null);
    final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
    kbHelper.setActivation(item);
    ((MVELConsequence) context.getRule().getConsequence()).compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
    context.getRule().getConsequence().evaluate(kbHelper, ksession);
    assertEquals(5, cheddar.getPrice());
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) HashMap(java.util.HashMap) GroupElement(org.drools.core.rule.GroupElement) Cheese(org.drools.compiler.Cheese) MVELConsequence(org.drools.core.base.mvel.MVELConsequence) AgendaItem(org.drools.core.common.AgendaItem) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) AgendaItemImpl(org.drools.core.common.AgendaItemImpl) Declaration(org.drools.core.rule.Declaration) ImportDeclaration(org.drools.core.rule.ImportDeclaration) PackageDescr(org.drools.compiler.lang.descr.PackageDescr) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) RuleTerminalNode(org.drools.core.reteoo.RuleTerminalNode) Pattern(org.drools.core.rule.Pattern) PropagationContextFactory(org.drools.core.common.PropagationContextFactory) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) DialectCompiletimeRegistry(org.drools.compiler.compiler.DialectCompiletimeRegistry) DefaultKnowledgeHelper(org.drools.core.base.DefaultKnowledgeHelper) BuildContext(org.drools.core.reteoo.builder.BuildContext) RuleBuildContext(org.drools.compiler.rule.builder.RuleBuildContext) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) RuleDescr(org.drools.compiler.lang.descr.RuleDescr) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) CompositeObjectSinkAdapterTest(org.drools.core.reteoo.CompositeObjectSinkAdapterTest) Test(org.junit.Test)

Example 5 with Pattern

use of org.drools.core.rule.Pattern in project drools by kiegroup.

the class MVELConsequenceBuilderTest method testImperativeCodeError.

@Test
public void testImperativeCodeError() throws Exception {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.setConsequence("if (cheese.price == 10) { cheese.price = 5; }");
    Properties properties = new Properties();
    properties.setProperty("drools.dialect.default", "mvel");
    KnowledgeBuilderConfigurationImpl cfg1 = new KnowledgeBuilderConfigurationImpl(properties);
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, cfg1);
    PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry dialectRegistry = pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect(pkgRegistry.getDialect());
    final RuleBuildContext context = new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);
    final InstrumentedDeclarationScopeResolver declarationResolver = new InstrumentedDeclarationScopeResolver();
    final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjeectType);
    final PatternExtractor extractor = new PatternExtractor(cheeseObjeectType);
    final Declaration declaration = new Declaration("cheese", extractor, pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("cheese", declaration);
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);
    final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
    builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
    final AgendaItem item = new AgendaItemImpl(0, tuple, 10, null, null, null);
    final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
    kbHelper.setActivation(item);
    try {
        ((MVELConsequence) context.getRule().getConsequence()).compile((MVELDialectRuntimeData) pkgBuilder.getPackageRegistry(pkg.getName()).getDialectRuntimeRegistry().getDialectData("mvel"));
        context.getRule().getConsequence().evaluate(kbHelper, ksession);
        fail("should throw an exception, as 'if' is not allowed");
    } catch (Exception e) {
    }
    assertEquals(10, cheddar.getPrice());
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) KnowledgeBuilderConfigurationImpl(org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl) HashMap(java.util.HashMap) Cheese(org.drools.compiler.Cheese) MVELConsequence(org.drools.core.base.mvel.MVELConsequence) Properties(java.util.Properties) AgendaItem(org.drools.core.common.AgendaItem) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) AgendaItemImpl(org.drools.core.common.AgendaItemImpl) Declaration(org.drools.core.rule.Declaration) ImportDeclaration(org.drools.core.rule.ImportDeclaration) 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) DefaultKnowledgeHelper(org.drools.core.base.DefaultKnowledgeHelper) PatternExtractor(org.drools.core.spi.PatternExtractor) DroolsParserException(org.drools.compiler.compiler.DroolsParserException) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) 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) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) CompositeObjectSinkAdapterTest(org.drools.core.reteoo.CompositeObjectSinkAdapterTest) Test(org.junit.Test)

Aggregations

Pattern (org.drools.core.rule.Pattern)190 ClassObjectType (org.drools.core.base.ClassObjectType)103 Test (org.junit.Test)98 Declaration (org.drools.core.rule.Declaration)79 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)69 GroupElement (org.drools.core.rule.GroupElement)49 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)45 ArrayList (java.util.ArrayList)35 IOException (java.io.IOException)33 ObjectType (org.drools.core.spi.ObjectType)32 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)28 Variable (org.drools.model.Variable)25 LambdaConstraint (org.drools.modelcompiler.constraints.LambdaConstraint)25 List (java.util.List)24 Accumulate (org.drools.core.rule.Accumulate)24 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)23 KieBase (org.kie.api.KieBase)23 Collection (java.util.Collection)21 QueryImpl (org.drools.core.rule.QueryImpl)21 KieSession (org.kie.api.runtime.KieSession)21