Search in sources :

Example 1 with Declaration

use of org.drools.core.rule.Declaration 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 Declaration

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

the class KiePackagesBuilder method buildAccumulate.

private Accumulate buildAccumulate(RuleContext ctx, AccumulatePattern accPattern, RuleConditionElement source, Pattern pattern, List<String> usedVariableName, Binding binding) {
    AccumulateFunction[] accFunctions = accPattern.getAccumulateFunctions();
    Accumulate accumulate;
    if (accFunctions.length == 1) {
        final Class<?> functionClass = accFunctions[0].getFunctionClass();
        final Accumulator accumulator = createAccumulator(usedVariableName, binding, functionClass);
        final Variable boundVar = accPattern.getBoundVariables()[0];
        final Declaration declaration = new Declaration(boundVar.getName(), getReadAcessor(JAVA_CLASS_OBJECT_TYPE), pattern, true);
        pattern.addDeclaration(declaration);
        Declaration[] bindingDeclaration = binding != null ? new Declaration[0] : new Declaration[] { ctx.getPattern(accFunctions[0].getSource()).getDeclaration() };
        accumulate = new SingleAccumulate(source, bindingDeclaration, accumulator);
    } else {
        InternalReadAccessor reader = new SelfReferenceClassFieldReader(Object[].class);
        Accumulator[] accumulators = new Accumulator[accFunctions.length];
        for (int i = 0; i < accFunctions.length; i++) {
            final Class<?> functionClass = accFunctions[i].getFunctionClass();
            final Accumulator accumulator = createAccumulator(usedVariableName, binding, functionClass);
            Variable boundVar = accPattern.getBoundVariables()[i];
            pattern.addDeclaration(new Declaration(boundVar.getName(), new ArrayElementReader(reader, i, boundVar.getType()), pattern, true));
            accumulators[i] = accumulator;
        }
        accumulate = new MultiAccumulate(source, new Declaration[0], accumulators);
    }
    for (Variable boundVar : accPattern.getBoundVariables()) {
        ctx.addAccumulateSource(boundVar, accumulate);
    }
    return accumulate;
}
Also used : LambdaAccumulator(org.drools.modelcompiler.constraints.LambdaAccumulator) Accumulator(org.drools.core.spi.Accumulator) PrototypeVariable(org.drools.model.PrototypeVariable) Variable(org.drools.model.Variable) MultiAccumulate(org.drools.core.rule.MultiAccumulate) SingleAccumulate(org.drools.core.rule.SingleAccumulate) SingleConstraint(org.drools.model.SingleConstraint) QueryNameConstraint(org.drools.core.rule.constraint.QueryNameConstraint) LambdaConstraint(org.drools.modelcompiler.constraints.LambdaConstraint) FlowDSL.entryPoint(org.drools.model.FlowDSL.entryPoint) UnificationConstraint(org.drools.modelcompiler.constraints.UnificationConstraint) EntryPoint(org.drools.model.EntryPoint) Constraint(org.drools.model.Constraint) MultiAccumulate(org.drools.core.rule.MultiAccumulate) SingleAccumulate(org.drools.core.rule.SingleAccumulate) Accumulate(org.drools.core.rule.Accumulate) SelfReferenceClassFieldReader(org.drools.core.base.extractors.SelfReferenceClassFieldReader) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) ArrayElementReader(org.drools.core.base.extractors.ArrayElementReader) 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) AccumulateFunction(org.drools.model.functions.accumulate.AccumulateFunction)

Example 3 with Declaration

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

the class AccumulateNode method addAccFunctionDeclarationsToLeftMask.

private void addAccFunctionDeclarationsToLeftMask(InternalKnowledgeBase kbase, LeftTupleSource leftInput, Accumulate accumulate) {
    BitMask leftMask = getLeftInferredMask();
    ObjectType leftObjectType = leftInput.getObjectType();
    if (leftObjectType instanceof ClassObjectType) {
        TypeDeclaration typeDeclaration = kbase.getExactTypeDeclaration(((ClassObjectType) leftObjectType).getClassType());
        if (typeDeclaration != null && typeDeclaration.isPropertyReactive()) {
            List<String> accessibleProperties = typeDeclaration.getAccessibleProperties();
            for (Declaration decl : accumulate.getRequiredDeclarations()) {
                if (leftObjectType.equals(decl.getPattern().getObjectType())) {
                    leftMask = leftMask.setAll(calculatePositiveMask(typeDeclaration.getTypeClass(), decl.getPattern().getListenedProperties(), accessibleProperties));
                }
            }
        }
    }
    setLeftInferredMask(leftMask);
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) ClassObjectType(org.drools.core.base.ClassObjectType) BitMask(org.drools.core.util.bitmask.BitMask) TypeDeclaration(org.drools.core.rule.TypeDeclaration) Declaration(org.drools.core.rule.Declaration) TypeDeclaration(org.drools.core.rule.TypeDeclaration)

Example 4 with Declaration

use of org.drools.core.rule.Declaration 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 Declaration

use of org.drools.core.rule.Declaration 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

Declaration (org.drools.core.rule.Declaration)218 Pattern (org.drools.core.rule.Pattern)77 ClassObjectType (org.drools.core.base.ClassObjectType)66 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)49 Test (org.junit.Test)45 InternalFactHandle (org.drools.core.common.InternalFactHandle)44 TypeDeclaration (org.drools.core.rule.TypeDeclaration)43 ArrayList (java.util.ArrayList)34 BoundIdentifiers (org.drools.compiler.compiler.BoundIdentifiers)33 HashMap (java.util.HashMap)30 DescrBuildError (org.drools.compiler.compiler.DescrBuildError)30 Constraint (org.drools.core.spi.Constraint)22 Map (java.util.Map)20 Tuple (org.drools.core.spi.Tuple)20 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)19 ObjectType (org.drools.core.spi.ObjectType)19 Cheese (org.drools.core.test.model.Cheese)18 FieldIndex (org.drools.core.util.AbstractHashTable.FieldIndex)18 WindowDeclaration (org.drools.core.rule.WindowDeclaration)17 TypeDeclarationUtil.createTypeDeclaration (org.drools.modelcompiler.util.TypeDeclarationUtil.createTypeDeclaration)17