Search in sources :

Example 41 with RuleImpl

use of org.drools.core.definitions.rule.impl.RuleImpl in project drools by kiegroup.

the class BaseMannersTest method getAllDone.

/**
 * <pre>
 * rule all_done() {
 *     Context context;
 *     when {
 *         context : Context( state == Context.PRINT_RESULTS )
 *     } then {
 *     }
 * }
 * </pre>
 *
 * @return
 * @throws InvalidRuleException
 */
private RuleImpl getAllDone() throws InvalidRuleException {
    final RuleImpl rule = new RuleImpl("alldone");
    // -----------
    // context : Context( state == Context.PRINT_RESULTS )
    // -----------
    final Pattern contextPattern = new Pattern(0, this.contextType);
    contextPattern.addConstraint(getLiteralConstraint(contextPattern, "state", Context.PRINT_RESULTS));
    rule.addPattern(contextPattern);
    final Declaration contextDeclaration = rule.getDeclaration("context");
    // ------------
    // 
    // ------------
    final Consequence consequence = new Consequence() {

        public void evaluate(KnowledgeHelper drools, WorkingMemory workingMemory) throws ConsequenceException {
            try {
                System.err.println("all done");
            } catch (Exception e) {
                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) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) ConsequenceException(org.drools.core.spi.ConsequenceException) InvalidRuleException(org.drools.core.rule.InvalidRuleException) IOException(java.io.IOException) ConsequenceException(org.drools.core.spi.ConsequenceException) IntrospectionException(java.beans.IntrospectionException)

Example 42 with RuleImpl

use of org.drools.core.definitions.rule.impl.RuleImpl in project drools by kiegroup.

the class BaseMannersTest method getMakePath.

/**
 * <pre>
 *    rule makePath() {
 *        Context context;
 *        int seatingId, seatingPid, pathSeat;
 *        String pathGuestName;
 *
 *        when {
 *            Context( state == Context.MAKE_PATH )
 *            Seating( seatingId:id, seatingPid:pid, pathDone == false )
 *            Path( id == seatingPid, pathGuestName:guest, pathSeat:seat )
 *            (not Path( id == seatingId, guestName == pathGuestName )
 *        } else {
 *            drools.assert( new Path( seatingId, pathSeat, pathGuestName ) );
 *
 *        }
 *    }
 * </pre>
 *
 * @return
 * @throws InvalidRuleException
 */
private RuleImpl getMakePath() throws InvalidRuleException {
    final RuleImpl rule = new RuleImpl("makePath");
    // -----------
    // context : Context( state == Context.MAKE_PATH )
    // -----------
    final Pattern contextPattern = new Pattern(0, this.contextType);
    contextPattern.addConstraint(getLiteralConstraint(contextPattern, "state", Context.MAKE_PATH));
    rule.addPattern(contextPattern);
    // ---------------
    // Seating( seatingId:id, seatingPid:pid, pathDone == false )
    // ---------------
    final Pattern seatingPattern = new Pattern(1, this.seatingType);
    setFieldDeclaration(seatingPattern, "id", "seatingId");
    setFieldDeclaration(seatingPattern, "pid", "seatingPid");
    seatingPattern.addConstraint(getLiteralConstraint(seatingPattern, "pathDone", false));
    rule.addPattern(seatingPattern);
    final Declaration seatingIdDeclaration = rule.getDeclaration("seatingId");
    final Declaration seatingPidDeclaration = rule.getDeclaration("seatingPid");
    // -----------
    // Path( id == seatingPid, pathGuestName:guestName, pathSeat:seat )
    // -----------
    final Pattern pathPattern = new Pattern(2, this.pathType);
    pathPattern.addConstraint(getBoundVariableConstraint(pathPattern, "id", seatingPidDeclaration, "=="));
    setFieldDeclaration(pathPattern, "guestName", "pathGuestName");
    setFieldDeclaration(pathPattern, "seat", "pathSeat");
    rule.addPattern(pathPattern);
    final Declaration pathGuestNameDeclaration = rule.getDeclaration("pathGuestName");
    final Declaration pathSeatDeclaration = rule.getDeclaration("pathSeat");
    // -------------
    // (not Path( id == seatingId, guestName == pathGuestName )
    // -------------
    final Pattern notPathPattern = new Pattern(3, this.pathType);
    notPathPattern.addConstraint(getBoundVariableConstraint(notPathPattern, "id", seatingIdDeclaration, "=="));
    notPathPattern.addConstraint(getBoundVariableConstraint(notPathPattern, "guestName", pathGuestNameDeclaration, "=="));
    final GroupElement not = GroupElementFactory.newNotInstance();
    not.addChild(notPathPattern);
    rule.addPattern(not);
    // ------------
    // drools.assert( new Path( id, pathName, pathSeat ) );
    // ------------
    final Consequence consequence = new Consequence() {

        public void evaluate(KnowledgeHelper drools, WorkingMemory workingMemory) throws ConsequenceException {
            try {
                RuleImpl rule = drools.getRule();
                LeftTuple tuple = (LeftTuple) drools.getTuple();
                int id = seatingIdDeclaration.getExtractor().getIntValue((InternalWorkingMemory) workingMemory, tuple.get(seatingIdDeclaration).getObject());
                int seat = pathSeatDeclaration.getExtractor().getIntValue((InternalWorkingMemory) workingMemory, tuple.get(pathSeatDeclaration).getObject());
                String guestName = (String) drools.get(pathGuestNameDeclaration);
                Path path = new Path(id, seat, guestName);
                drools.insert(path);
            // System.err.println( "make path : " + path );
            } 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 43 with RuleImpl

use of org.drools.core.definitions.rule.impl.RuleImpl in project drools by kiegroup.

the class BaseMannersTest method getAreWeDone.

/**
 * <pre>
 * rule areWeDone() {
 *     Context context; LastSeat lastSear;
 *     when {
 *         context : Context( state == Context.CHECK_DONE )
 *         LastSeat( lastSeat: seat )
 *         Seating( rightSeat == lastSeat )
 *     } then {
 *         context.setState(Context.PRINT_RESULTS );
 *     }
 * }
 * </pre>
 *
 * @return
 * @throws InvalidRuleException
 */
private RuleImpl getAreWeDone() throws InvalidRuleException {
    final RuleImpl rule = new RuleImpl("areWeDone");
    // -----------
    // context : Context( state == Context.CHECK_DONE )
    // -----------
    final Pattern contextPattern = new Pattern(0, this.contextType, "context");
    contextPattern.addConstraint(getLiteralConstraint(contextPattern, "state", Context.CHECK_DONE));
    rule.addPattern(contextPattern);
    final Declaration contextDeclaration = rule.getDeclaration("context");
    // ---------------
    // LastSeat( lastSeat: seat )
    // ---------------
    final Pattern lastSeatPattern = new Pattern(1, this.lastSeatType);
    setFieldDeclaration(lastSeatPattern, "seat", "lastSeat");
    rule.addPattern(lastSeatPattern);
    final Declaration lastSeatDeclaration = rule.getDeclaration("lastSeat");
    // -------------
    // Seating( rightSeat == lastSeat )
    // -------------
    final Pattern seatingPattern = new Pattern(2, this.seatingType, null);
    seatingPattern.addConstraint(getBoundVariableConstraint(seatingPattern, "rightSeat", lastSeatDeclaration, "=="));
    rule.addPattern(seatingPattern);
    // ------------
    // context.setName( Context.PRINT_RESULTS );
    // ------------
    final Consequence consequence = new Consequence() {

        public void evaluate(KnowledgeHelper drools, WorkingMemory workingMemory) throws ConsequenceException {
            try {
                RuleImpl rule = drools.getRule();
                LeftTuple tuple = (LeftTuple) drools.getTuple();
                Context context = (Context) drools.get(contextDeclaration);
                context.setState(Context.PRINT_RESULTS);
                drools.update(tuple.get(contextDeclaration), context);
            // System.err.println( "We Are Done!!!" );
            } catch (Exception e) {
                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) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) ConsequenceException(org.drools.core.spi.ConsequenceException) LeftTuple(org.drools.core.reteoo.LeftTuple) InvalidRuleException(org.drools.core.rule.InvalidRuleException) IOException(java.io.IOException) ConsequenceException(org.drools.core.spi.ConsequenceException) IntrospectionException(java.beans.IntrospectionException)

Example 44 with RuleImpl

use of org.drools.core.definitions.rule.impl.RuleImpl in project drools by kiegroup.

the class AlphaNodeTest method testReturnValueConstraintAssertObject.

/*
     *  This just test AlphaNode With a different Constraint type.
     */
@Test
public void testReturnValueConstraintAssertObject() throws Exception {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    BuildContext buildContext = new BuildContext(kBase);
    buildContext.setRule(new RuleImpl("test"));
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final RuleImpl rule = new RuleImpl("test-rule");
    PropagationContextFactory pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    final PropagationContext context = pctxFactory.createPropagationContext(0, PropagationContext.Type.INSERTION, null, null, null);
    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());
    final InternalReadAccessor extractor = store.getReader(Cheese.class, "type");
    final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
    final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
    final AlphaNode alphaNode = new AlphaNode(buildContext.getNextId(), constraint, source, buildContext);
    final MockObjectSink sink = new MockObjectSink();
    alphaNode.addObjectSink(sink);
    final Cheese cheddar = new Cheese("cheddar", 5);
    final DefaultFactHandle f0 = (DefaultFactHandle) ksession.insert(cheddar);
    assertLength(0, sink.getAsserted());
    // object should assert as it passes text
    alphaNode.assertObject(f0, context, ksession);
    assertLength(1, sink.getAsserted());
    final Object[] list = (Object[]) sink.getAsserted().get(0);
    assertSame(cheddar, ksession.getObject((DefaultFactHandle) list[0]));
    final Cheese stilton = new Cheese("stilton", 6);
    f0.setObject(stilton);
    sink.getAsserted().clear();
    // object should not assert as it does not pass text
    alphaNode.assertObject(f0, context, ksession);
    assertLength(0, sink.getAsserted());
}
Also used : PropagationContextFactory(org.drools.core.common.PropagationContextFactory) PropagationContext(org.drools.core.spi.PropagationContext) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) Cheese(org.drools.core.test.model.Cheese) MvelConstraintTestUtil(org.drools.core.rule.MvelConstraintTestUtil) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) BuildContext(org.drools.core.reteoo.builder.BuildContext) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) FieldValue(org.drools.core.spi.FieldValue) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 45 with RuleImpl

use of org.drools.core.definitions.rule.impl.RuleImpl in project drools by kiegroup.

the class AlphaNodeTest method testUpdateSinkWithoutMemory.

@Test
public void testUpdateSinkWithoutMemory() {
    // An AlphaNode should try and repropagate from its source
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    BuildContext buildContext = new BuildContext(kBase);
    buildContext.setRule(new RuleImpl("test"));
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final RuleImpl rule = new RuleImpl("test-rule");
    PropagationContextFactory pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    final PropagationContext context = pctxFactory.createPropagationContext(0, PropagationContext.Type.INSERTION, null, null, null);
    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());
    final InternalReadAccessor extractor = store.getReader(Cheese.class, "type");
    final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
    final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
    final AlphaNode alphaNode = new AlphaNode(buildContext.getNextId(), constraint, source, // no memory
    buildContext);
    alphaNode.attach(buildContext);
    final MockObjectSink sink1 = new MockObjectSink();
    alphaNode.addObjectSink(sink1);
    // Assert a single fact which should be in the AlphaNode memory and also
    // propagated to the
    // the tuple sink
    final Cheese cheese = new Cheese("cheddar", 0);
    final DefaultFactHandle handle1 = new DefaultFactHandle(1, cheese);
    // adding handle to the mock source
    source.addFact(handle1);
    alphaNode.assertObject(handle1, context, ksession);
    // Create a fact that should not be propagated, since the alpha node restriction will filter it out
    final Cheese stilton = new Cheese("stilton", 10);
    final DefaultFactHandle handle2 = new DefaultFactHandle(2, stilton);
    // adding handle to the mock source
    source.addFact(handle2);
    alphaNode.assertObject(handle2, context, ksession);
    assertLength(1, sink1.getAsserted());
    // Attach a new tuple sink
    final MockObjectSink sink2 = new MockObjectSink();
    // Tell the alphanode to update the new node. Make sure the first sink1
    // is not updated
    // likewise the source should not do anything
    alphaNode.updateSink(sink2, context, ksession);
    assertLength(1, sink1.getAsserted());
    assertLength(1, sink2.getAsserted());
    assertEquals(1, source.getUdated());
}
Also used : PropagationContextFactory(org.drools.core.common.PropagationContextFactory) PropagationContext(org.drools.core.spi.PropagationContext) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) Cheese(org.drools.core.test.model.Cheese) MvelConstraintTestUtil(org.drools.core.rule.MvelConstraintTestUtil) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) BuildContext(org.drools.core.reteoo.builder.BuildContext) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) FieldValue(org.drools.core.spi.FieldValue) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Aggregations

RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)107 Test (org.junit.Test)51 Pattern (org.drools.core.rule.Pattern)30 InternalKnowledgePackage (org.drools.core.definitions.InternalKnowledgePackage)28 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)21 WorkingMemory (org.drools.core.WorkingMemory)21 KnowledgePackageImpl (org.drools.core.definitions.impl.KnowledgePackageImpl)18 BuildContext (org.drools.core.reteoo.builder.BuildContext)16 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)16 Consequence (org.drools.core.spi.Consequence)15 GroupElement (org.drools.core.rule.GroupElement)14 ClassObjectType (org.drools.core.base.ClassObjectType)13 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)13 IOException (java.io.IOException)12 ObjectInput (java.io.ObjectInput)12 ObjectOutput (java.io.ObjectOutput)12 PackageDescr (org.drools.compiler.lang.descr.PackageDescr)12 RuleTerminalNode (org.drools.core.reteoo.RuleTerminalNode)12 KnowledgeBuilderImpl (org.drools.compiler.builder.impl.KnowledgeBuilderImpl)11 KnowledgeBaseImpl (org.drools.core.impl.KnowledgeBaseImpl)11