Search in sources :

Example 21 with GroupElement

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

the class BaseMannersTest method getFindSeating.

/**
 * <pre>
 *    rule findSeating() {
 *       Context context;
 *       int seatingId, seatingPid;
 *       String seatingRightGuestName, leftGuestName;
 *       Sex rightGuestSex;
 *       Hobby rightGuestHobby;
 *       Count count;
 *
 *       when {
 *           context : Context( state == Context.ASSIGN_SEATS )
 *           Seating( seatingId:id, seatingPid:pid, pathDone == true
 *                    seatingRightSeat:rightSeat seatingRightGuestName:rightGuestName )
 *           Guest( name == seatingRightGuestName, rightGuestSex:sex, rightGuestHobby:hobby )
 *           Guest( leftGuestName:name , sex != rightGuestSex, hobby == rightGuestHobby )
 *
 *           count : Count()
 *
 *           not ( Path( id == seatingId, guestName == leftGuestName) )
 *           not ( Chosen( id == seatingId, guestName == leftGuestName, hobby == rightGuestHobby) )
 *       } then {
 *           int newSeat = rightSeat + 1;
 *           drools.assert( new Seating( coung.getValue(), rightSeat, rightSeatName, leftGuestName, newSeat, countValue, id, false );
 *           drools.assert( new Path( countValue, leftGuestName, newSeat );
 *           drools.assert( new Chosen( id, leftGuestName, rightGuestHobby ) );
 *
 *           System.err.println( &quot;seat &quot; + rightSeat + &quot; &quot; + rightSeatName + &quot; &quot; + leftGuestName );
 *
 *           count.setCount(  countValue + 1 );
 *           context.setPath( Context.MAKE_PATH );
 *       }
 *    }
 * </pre>
 *
 * @return
 * @throws InvalidRuleException
 */
private RuleImpl getFindSeating() throws InvalidRuleException {
    final RuleImpl rule = new RuleImpl("findSeating");
    // ---------------
    // context : Context( state == Context.ASSIGN_SEATS )
    // ---------------
    final Pattern contextPattern = new Pattern(0, this.contextType, "context");
    contextPattern.addConstraint(getLiteralConstraint(contextPattern, "state", Context.ASSIGN_SEATS));
    rule.addPattern(contextPattern);
    final Declaration contextDeclaration = rule.getDeclaration("context");
    // -------------------------------
    // Seating( seatingId:id, seatingPid:pid, pathDone == true
    // seatingRightSeat:rightSeat seatingRightGuestName:rightGuestName )
    // -------------------------------
    final Pattern seatingPattern = new Pattern(1, this.seatingType);
    setFieldDeclaration(seatingPattern, "id", "seatingId");
    setFieldDeclaration(seatingPattern, "pid", "seatingPid");
    seatingPattern.addConstraint(getLiteralConstraint(seatingPattern, "pathDone", true));
    setFieldDeclaration(seatingPattern, "rightSeat", "seatingRightSeat");
    setFieldDeclaration(seatingPattern, "rightGuestName", "seatingRightGuestName");
    rule.addPattern(seatingPattern);
    final Declaration seatingIdDeclaration = rule.getDeclaration("seatingId");
    final Declaration seatingPidDeclaration = rule.getDeclaration("seatingPid");
    final Declaration seatingRightGuestNameDeclaration = rule.getDeclaration("seatingRightGuestName");
    final Declaration seatingRightSeatDeclaration = rule.getDeclaration("seatingRightSeat");
    // --------------
    // Guest( name == seatingRightGuestName, rightGuestSex:sex,
    // rightGuestHobby:hobby )
    // ---------------
    final Pattern rightGuestPattern = new Pattern(2, this.guestType);
    rightGuestPattern.addConstraint(getBoundVariableConstraint(rightGuestPattern, "name", seatingRightGuestNameDeclaration, "=="));
    setFieldDeclaration(rightGuestPattern, "sex", "rightGuestSex");
    setFieldDeclaration(rightGuestPattern, "hobby", "rightGuestHobby");
    rule.addPattern(rightGuestPattern);
    final Declaration rightGuestSexDeclaration = rule.getDeclaration("rightGuestSex");
    final Declaration rightGuestHobbyDeclaration = rule.getDeclaration("rightGuestHobby");
    // ----------------
    // Guest( leftGuestName:name , sex != rightGuestSex, hobby ==
    // rightGuestHobby )
    // ----------------
    final Pattern leftGuestPattern = new Pattern(3, this.guestType);
    setFieldDeclaration(leftGuestPattern, "name", "leftGuestName");
    leftGuestPattern.addConstraint(getBoundVariableConstraint(rightGuestPattern, "hobby", rightGuestHobbyDeclaration, "=="));
    leftGuestPattern.addConstraint(getBoundVariableConstraint(leftGuestPattern, "sex", rightGuestSexDeclaration, "!="));
    rule.addPattern(leftGuestPattern);
    final Declaration leftGuestNameDeclaration = rule.getDeclaration("leftGuestName");
    // ---------------
    // count : Count()
    // ---------------
    final Pattern count = new Pattern(4, this.countType, "count");
    rule.addPattern(count);
    final Declaration countDeclaration = rule.getDeclaration("count");
    // --------------
    // not ( Path( id == seatingId, guestName == leftGuestName) )
    // --------------
    final Pattern notPathPattern = new Pattern(5, this.pathType);
    notPathPattern.addConstraint(getBoundVariableConstraint(notPathPattern, "id", seatingIdDeclaration, "=="));
    notPathPattern.addConstraint(getBoundVariableConstraint(notPathPattern, "guestName", leftGuestNameDeclaration, "=="));
    final GroupElement notPath = GroupElementFactory.newNotInstance();
    notPath.addChild(notPathPattern);
    rule.addPattern(notPath);
    // ------------
    // not ( Chosen( id == seatingId, guestName == leftGuestName, hobby ==
    // rightGuestHobby ) )
    // ------------
    final Pattern notChosenPattern = new Pattern(6, this.chosenType);
    notChosenPattern.addConstraint(getBoundVariableConstraint(notChosenPattern, "id", seatingIdDeclaration, "=="));
    notChosenPattern.addConstraint(getBoundVariableConstraint(notChosenPattern, "guestName", leftGuestNameDeclaration, "=="));
    notChosenPattern.addConstraint(getBoundVariableConstraint(notChosenPattern, "hobby", rightGuestHobbyDeclaration, "=="));
    final GroupElement notChosen = GroupElementFactory.newNotInstance();
    notChosen.addChild(notChosenPattern);
    rule.addPattern(notChosen);
    // ------------
    // int newSeat = rightSeat + 1;
    // drools.assert( new Seating( coung.getValue(), rightSeat,
    // rightSeatName, leftGuestName, newSeat, countValue, id, false );
    // drools.assert( new Path( countValue, leftGuestName, newSeat );
    // drools.assert( new Chosen( id, leftGuestName, rightGuestHobby ) );
    // 
    // System.err.println( "seat " + rightSeat + " " + rightSeatName + " " +
    // leftGuestName );
    // 
    // count.setCount( countValue + 1 );
    // context.setPath( Context.MAKE_PATH );
    // ------------
    final Consequence consequence = new Consequence() {

        public void evaluate(KnowledgeHelper drools, WorkingMemory workingMemory) throws ConsequenceException {
            try {
                // MemoryVisitor visitor = new MemoryVisitor( ( InternalWorkingMemory ) workingMemory );
                // visitor.visit( workingMemory.getRuleBase() );
                RuleImpl rule = drools.getRule();
                LeftTuple tuple = (LeftTuple) drools.getTuple();
                Context context = (Context) drools.get(contextDeclaration);
                Count count = (Count) drools.get(countDeclaration);
                int seatId = seatingIdDeclaration.getExtractor().getIntValue((InternalWorkingMemory) workingMemory, tuple.get(seatingIdDeclaration).getObject());
                int seatingRightSeat = seatingRightSeatDeclaration.getExtractor().getIntValue((InternalWorkingMemory) workingMemory, tuple.get(seatingRightSeatDeclaration).getObject());
                String leftGuestName = (String) drools.get(leftGuestNameDeclaration);
                String rightGuestName = (String) drools.get(seatingRightGuestNameDeclaration);
                Hobby rightGuestHobby = (Hobby) drools.get(rightGuestHobbyDeclaration);
                Seating seating = new Seating(count.getValue(), seatId, false, seatingRightSeat, rightGuestName, seatingRightSeat + 1, leftGuestName);
                drools.insert(seating);
                Path path = new Path(count.getValue(), seatingRightSeat + 1, leftGuestName);
                drools.insert(path);
                Chosen chosen = new Chosen(seatId, leftGuestName, rightGuestHobby);
                drools.insert(chosen);
                count.setValue(count.getValue() + 1);
                // if ( count.getValue() == 5 ) {
                // drools.retractObject( tuple.getFactHandleForDeclaration( countDeclaration ) );
                // } else {
                // drools.update( tuple.getFactHandleForDeclaration( countDeclaration ),
                // count );
                // }
                drools.update(tuple.get(countDeclaration), count);
                context.setState(Context.MAKE_PATH);
                drools.update(tuple.get(contextDeclaration), context);
                System.err.println("find seating : " + seating + " : " + path + " : " + chosen);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ConsequenceException(e);
            }
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            return "default";
        }
    };
    rule.setConsequence(consequence);
    return rule;
}
Also used : Pattern(org.drools.core.rule.Pattern) ObjectOutput(java.io.ObjectOutput) WorkingMemory(org.drools.core.WorkingMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) GroupElement(org.drools.core.rule.GroupElement) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) LeftTuple(org.drools.core.reteoo.LeftTuple) BetaNodeFieldConstraint(org.drools.core.spi.BetaNodeFieldConstraint) AlphaNodeFieldConstraint(org.drools.core.spi.AlphaNodeFieldConstraint) InvalidRuleException(org.drools.core.rule.InvalidRuleException) IOException(java.io.IOException) ConsequenceException(org.drools.core.spi.ConsequenceException) IntrospectionException(java.beans.IntrospectionException) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) ConsequenceException(org.drools.core.spi.ConsequenceException)

Example 22 with GroupElement

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

the class ForallBuilder method build.

/**
 * @inheritDoc
 */
public void build(final BuildContext context, final BuildUtils utils, final RuleConditionElement rce) {
    final Forall forall = (Forall) rce;
    context.pushRuleComponent(forall);
    // forall can be translated into
    // not( basePattern and not( <remaining_patterns>+ ) )
    // so we just do that:
    final GroupElement and = GroupElementFactory.newAndInstance();
    and.addChild(forall.getBasePattern());
    final GroupElement not2 = GroupElementFactory.newNotInstance();
    if (forall.getRemainingPatterns().size() == 1) {
        if (forall.isEmptyBetaConstraints()) {
            // The reason why this is here is because forall can inject a
            // "this == " + BASE_IDENTIFIER $__forallBaseIdentifier
            // Which we don't want to actually count in the case of forall node linking
            context.setEmptyForAllBetaConstraints();
        }
        not2.addChild(forall.getRemainingPatterns().get(0));
        and.addChild(not2);
    } else if (forall.getRemainingPatterns().size() > 1) {
        final GroupElement and2 = GroupElementFactory.newAndInstance();
        for (Pattern pattern : forall.getRemainingPatterns()) {
            and2.addChild(pattern);
        }
        not2.addChild(and2);
        and.addChild(not2);
    }
    final GroupElement not = GroupElementFactory.newNotInstance();
    not.addChild(and);
    // get builder for the CEs
    final ReteooComponentBuilder builder = utils.getBuilderFor(not);
    // builds the CEs
    builder.build(context, utils, not);
    context.popRuleComponent();
}
Also used : Pattern(org.drools.core.rule.Pattern) GroupElement(org.drools.core.rule.GroupElement) Forall(org.drools.core.rule.Forall)

Example 23 with GroupElement

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

the class GroupElementBuilder method build.

/**
 * @inheritDoc
 */
public void build(final BuildContext context, final BuildUtils utils, final RuleConditionElement rce) {
    final GroupElement ge = (GroupElement) rce;
    final ReteooComponentBuilder builder = this.geBuilders.get(ge.getType());
    context.push(ge);
    context.pushRuleComponent(ge);
    builder.build(context, utils, rce);
    context.pop();
    context.popRuleComponent();
}
Also used : GroupElement(org.drools.core.rule.GroupElement)

Example 24 with GroupElement

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

the class GroupElementBuilder method requiresLeftActivation.

/**
 * @inheritDoc
 */
public boolean requiresLeftActivation(final BuildUtils utils, final RuleConditionElement rce) {
    final GroupElement ge = (GroupElement) rce;
    final ReteooComponentBuilder builder = this.geBuilders.get(ge.getType());
    return builder.requiresLeftActivation(utils, rce);
}
Also used : GroupElement(org.drools.core.rule.GroupElement)

Example 25 with GroupElement

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

the class DeclarationScopeResolver method getDeclarations.

/**
 * Return all declarations scoped to the current
 * RuleConditionElement in the build stack
 */
public Map<String, Declaration> getDeclarations(RuleImpl rule, String consequenceName) {
    Map<String, Declaration> declarations = new HashMap<String, Declaration>();
    for (RuleConditionElement aBuildStack : this.buildStack) {
        // if we are inside of an OR we don't want each previous stack entry added because we can't see those variables
        if (aBuildStack instanceof GroupElement && ((GroupElement) aBuildStack).getType() == GroupElement.Type.OR) {
            continue;
        }
        // this may be optimized in the future to only re-add elements at
        // scope breaks, like "NOT" and "EXISTS"
        Map<String, Declaration> innerDeclarations = aBuildStack instanceof GroupElement ? ((GroupElement) aBuildStack).getInnerDeclarations(consequenceName) : aBuildStack.getInnerDeclarations();
        declarations.putAll(innerDeclarations);
    }
    if (null != rule.getParent()) {
        return getAllExtendedDeclaration(rule.getParent(), declarations);
    }
    return declarations;
}
Also used : HashMap(java.util.HashMap) GroupElement(org.drools.core.rule.GroupElement) Declaration(org.drools.core.rule.Declaration) RuleConditionElement(org.drools.core.rule.RuleConditionElement)

Aggregations

GroupElement (org.drools.core.rule.GroupElement)29 Pattern (org.drools.core.rule.Pattern)16 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)14 Test (org.junit.Test)13 Declaration (org.drools.core.rule.Declaration)6 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)5 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)5 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)5 CompositeObjectSinkAdapterTest (org.drools.core.reteoo.CompositeObjectSinkAdapterTest)5 RuleConditionElement (org.drools.core.rule.RuleConditionElement)4 ObjectInput (java.io.ObjectInput)3 ObjectOutput (java.io.ObjectOutput)3 HashMap (java.util.HashMap)3 AndDescr (org.drools.compiler.lang.descr.AndDescr)3 WorkingMemory (org.drools.core.WorkingMemory)3 ClassObjectType (org.drools.core.base.ClassObjectType)3 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)3 RuleTerminalNode (org.drools.core.reteoo.RuleTerminalNode)3 IntrospectionException (java.beans.IntrospectionException)2 IOException (java.io.IOException)2