Search in sources :

Example 71 with ObjectOutput

use of java.io.ObjectOutput in project drools by kiegroup.

the class KnowledgeBaseEventSupportTest method setUp.

/* (non-Javadoc)
     * @see junit.framework.TestCase#setUp()
     */
@Before
public void setUp() throws Exception {
    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    listener1 = new TestRuleBaseListener("(listener-1) ");
    listener2 = new TestRuleBaseListener("(listener-2) ");
    kbase.addEventListener(listener1);
    kbase.addEventListener(listener2);
    final RuleImpl rule1 = new RuleImpl("test1");
    final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjectType);
    ClassFieldAccessorStore store = new ClassFieldAccessorStore();
    store.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);
    final ClassFieldReader extractor = store.getReader(Cheese.class, "type");
    final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
    final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
    pattern.addConstraint(constraint);
    rule1.addPattern(pattern);
    rule1.setConsequence(new Consequence() {

        private static final long serialVersionUID = 510l;

        public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
        }

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

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            return "default";
        }
    });
    final RuleImpl rule2 = new RuleImpl("test2");
    final ClassObjectType cheeseObjectType2 = new ClassObjectType(Cheese.class);
    final Pattern pattern2 = new Pattern(0, cheeseObjectType2);
    final FieldValue field2 = FieldFactory.getInstance().getFieldValue("stilton");
    final MvelConstraint constraint2 = new MvelConstraintTestUtil("type == \"stilton\"", field, extractor);
    pattern2.addConstraint(constraint2);
    rule2.addPattern(pattern2);
    rule2.setConsequence(new Consequence() {

        private static final long serialVersionUID = 510l;

        public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
        }

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

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            return "default";
        }
    });
    pkg = new KnowledgePackageImpl("org.drools.test1");
    pkg.addRule(rule1);
    pkg.addRule(rule2);
}
Also used : Pattern(org.drools.core.rule.Pattern) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectOutput(java.io.ObjectOutput) WorkingMemory(org.drools.core.WorkingMemory) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) ClassFieldAccessorStore(org.drools.core.base.ClassFieldAccessorStore) IOException(java.io.IOException) MvelConstraintTestUtil(org.drools.core.rule.MvelConstraintTestUtil) IOException(java.io.IOException) ClassFieldAccessorCache(org.drools.core.base.ClassFieldAccessorCache) ClassFieldReader(org.drools.core.base.ClassFieldReader) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) FieldValue(org.drools.core.spi.FieldValue) ObjectInput(java.io.ObjectInput) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) Before(org.junit.Before)

Example 72 with ObjectOutput

use of java.io.ObjectOutput in project drools by kiegroup.

the class AgendaEventSupportTest method testAgendaEventListener.

// public void testIsSerializable() {
// assertTrue( Serializable.class.isAssignableFrom( AgendaEventSupport.class ) );
// }
@Test
@Ignore
public void testAgendaEventListener() throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    // create a simple package with one rule to test the events
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools.test");
    final RuleImpl rule = new RuleImpl("test1");
    rule.setEager(true);
    rule.setAgendaGroup("test group");
    final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjectType);
    pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg.getClassFieldAccessorStore().setEagerWire(true);
    final ClassFieldReader extractor = pkg.getClassFieldAccessorStore().getReader(Cheese.class, "type");
    final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");
    final MvelConstraint constraint = new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);
    pattern.addConstraint(constraint);
    rule.addPattern(pattern);
    rule.setConsequence(new Consequence() {

        public void evaluate(final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory) throws Exception {
        }

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

        public void writeExternal(ObjectOutput out) throws IOException {
        }

        public String getName() {
            // TODO Auto-generated method stub
            return null;
        }
    });
    pkg.addRule(rule);
    kbase.addPackages(Collections.singleton(pkg));
    // create a new working memory and add an AgendaEventListener
    KieSession ksession = kbase.newKieSession();
    final List agendaList = new ArrayList();
    final AgendaEventListener agendaEventListener = new AgendaEventListener() {

        public void matchCancelled(MatchCancelledEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void matchCreated(MatchCreatedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void afterMatchFired(AfterMatchFiredEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void agendaGroupPopped(AgendaGroupPoppedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void agendaGroupPushed(AgendaGroupPushedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void beforeMatchFired(BeforeMatchFiredEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void afterRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void beforeRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }

        public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) {
            assertNotNull(event.getKieRuntime());
            agendaList.add(event);
        }
    };
    ksession.addEventListener(agendaEventListener);
    assertEquals(1, ksession.getAgendaEventListeners().size());
    // assert the cheese fact
    final Cheese cheddar = new Cheese("cheddar", 15);
    FactHandle cheddarHandle = ksession.insert(cheddar);
    InternalAgenda agenda = (InternalAgenda) ksession.getAgenda();
    agenda.evaluateEagerList();
    // should be one MatchCreatedEvent
    assertEquals(1, agendaList.size());
    MatchCreatedEvent createdEvent = (MatchCreatedEvent) agendaList.get(0);
    assertSame(cheddarHandle, createdEvent.getMatch().getFactHandles().toArray()[0]);
    // clear the agenda to check CLEAR events occur
    ksession.getAgenda().clear();
    MatchCancelledEvent cancelledEvent = (MatchCancelledEvent) agendaList.get(1);
    assertEquals(MatchCancelledCause.CLEAR, cancelledEvent.getCause());
    agendaList.clear();
    // update results in an MatchCreatedEvent
    cheddar.setPrice(14);
    ksession.update(cheddarHandle, cheddar);
    agenda.evaluateEagerList();
    assertEquals(1, agendaList.size());
    createdEvent = (MatchCreatedEvent) agendaList.get(0);
    assertSame(cheddarHandle, createdEvent.getMatch().getFactHandles().toArray()[0]);
    agendaList.clear();
    // update should not result in cancelation+activation events
    cheddar.setPrice(14);
    ksession.update(cheddarHandle, cheddar);
    assertEquals(0, agendaList.size());
    // cancelledEvent = (ActivationCancelledEvent) agendaList.get( 0 );
    // assertEquals( ActivationCancelledCause.WME_MODIFY, cancelledEvent.getCause() );
    // assertSame( cheddarHandle,
    // cancelledEvent.getActivation().toFactHandles().toArray()[0] );
    // createdEvent = (ActivationCreatedEvent) agendaList.get( 1 );
    // assertSame( cheddarHandle,
    // createdEvent.getActivation().toFactHandles().toArray()[0] );
    // agendaList.clear();
    // retract results in a ActivationCancelledEvent, note the object is not resolveable now as it no longer exists
    ksession.retract(cheddarHandle);
    assertEquals(1, agendaList.size());
    cancelledEvent = (MatchCancelledEvent) agendaList.get(0);
    // invalidated handles no longer set the object to null
    assertNotNull(((InternalFactHandle) cancelledEvent.getMatch().getFactHandles().toArray()[0]).getObject());
    // re-assert the fact so we can test the agenda group events
    cheddarHandle = ksession.insert(cheddar);
    agendaList.clear();
    // setFocus results in an AgendaGroupPushedEvent
    ksession.getAgenda().getAgendaGroup("test group").setFocus();
    assertEquals(1, agendaList.size());
    final AgendaGroupPushedEvent pushedEvent = (AgendaGroupPushedEvent) agendaList.get(0);
    assertEquals("test group", pushedEvent.getAgendaGroup().getName());
    agendaList.clear();
    // fireAllRules results in a BeforeActivationFiredEvent and an AfterActivationFiredEvent
    // the AgendaGroup becomes empty, which results in a popped event.
    ksession.fireAllRules();
    assertEquals(3, agendaList.size());
    final BeforeMatchFiredEvent beforeEvent = (BeforeMatchFiredEvent) agendaList.get(0);
    assertSame(cheddarHandle, beforeEvent.getMatch().getFactHandles().toArray()[0]);
    final AfterMatchFiredEvent afterEvent = (AfterMatchFiredEvent) agendaList.get(1);
    assertSame(cheddarHandle, afterEvent.getMatch().getFactHandles().toArray()[0]);
    final AgendaGroupPoppedEvent poppedEvent = (AgendaGroupPoppedEvent) agendaList.get(2);
    assertEquals("test group", poppedEvent.getAgendaGroup().getName());
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) WorkingMemory(org.drools.core.WorkingMemory) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) ArrayList(java.util.ArrayList) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) Cheese(org.drools.core.test.model.Cheese) RuleFlowGroupDeactivatedEvent(org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent) MvelConstraintTestUtil(org.drools.core.rule.MvelConstraintTestUtil) InternalAgenda(org.drools.core.common.InternalAgenda) ClassFieldReader(org.drools.core.base.ClassFieldReader) MatchCancelledEvent(org.kie.api.event.rule.MatchCancelledEvent) AgendaEventListener(org.kie.api.event.rule.AgendaEventListener) BeforeMatchFiredEvent(org.kie.api.event.rule.BeforeMatchFiredEvent) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) FieldValue(org.drools.core.spi.FieldValue) MatchCreatedEvent(org.kie.api.event.rule.MatchCreatedEvent) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Pattern(org.drools.core.rule.Pattern) ObjectOutput(java.io.ObjectOutput) Consequence(org.drools.core.spi.Consequence) IOException(java.io.IOException) IOException(java.io.IOException) AfterMatchFiredEvent(org.kie.api.event.rule.AfterMatchFiredEvent) ClassFieldAccessorCache(org.drools.core.base.ClassFieldAccessorCache) AgendaGroupPoppedEvent(org.kie.api.event.rule.AgendaGroupPoppedEvent) RuleFlowGroupActivatedEvent(org.kie.api.event.rule.RuleFlowGroupActivatedEvent) AgendaGroupPushedEvent(org.kie.api.event.rule.AgendaGroupPushedEvent) ObjectInput(java.io.ObjectInput) KnowledgePackageImpl(org.drools.core.definitions.impl.KnowledgePackageImpl) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 73 with ObjectOutput

use of java.io.ObjectOutput in project drools by kiegroup.

the class BaseMannersTest method getAssignFirstSeatRule.

/**
 * <pre>
 *    rule assignFirstSeat() {
 *        Context context;
 *        Guest guest;
 *        Count count;
 *        when {
 *            context : Context( state == Context.START_UP )
 *            guest : Guest()
 *            count : Count()
 *        } then {
 *            String guestName = guest.getName();
 *            drools.assert( new Seating( count.getValue(), 1, true, 1, guestName, 1, guestName) );
 *            drools.assert( new Path( count.getValue(), 1, guestName ) );
 *            count.setCount(  count.getValue() + 1 );
 *
 *            System.err.println( &quot;seat 1 &quot; + guest.getName() + &quot; );
 *
 *            context.setPath( Context.ASSIGN_SEATS );
 *        }
 *    }
 * </pre>
 *
 * @return
 * @throws InvalidRuleException
 */
private RuleImpl getAssignFirstSeatRule() throws InvalidRuleException {
    final RuleImpl rule = new RuleImpl("assignFirstSeat");
    // -----------
    // context : Context( state == Context.START_UP )
    // -----------
    final Pattern contextPattern = new Pattern(0, this.contextType, "context");
    contextPattern.addConstraint(getLiteralConstraint(contextPattern, "state", Context.START_UP));
    rule.addPattern(contextPattern);
    final Declaration contextDeclaration = rule.getDeclaration("context");
    // -----------
    // guest: Guest()
    // -----------
    final Pattern guestPattern = new Pattern(1, this.guestType, "guest");
    rule.addPattern(guestPattern);
    final Declaration guestDeclaration = rule.getDeclaration("guest");
    // ------------
    // count : Count()
    // ------------
    final Pattern countPattern = new Pattern(2, this.countType, "count");
    rule.addPattern(countPattern);
    final Declaration countDeclaration = rule.getDeclaration("count");
    final Consequence consequence = new Consequence() {

        public void evaluate(KnowledgeHelper drools, WorkingMemory workingMemory) throws ConsequenceException {
            try {
                RuleImpl rule = drools.getRule();
                LeftTuple tuple = (LeftTuple) drools.getTuple();
                Guest guest = (Guest) drools.get(guestDeclaration);
                Context context = (Context) drools.get(contextDeclaration);
                Count count = (Count) drools.get(countDeclaration);
                String guestName = guest.getName();
                Seating seating = new Seating(count.getValue(), 0, true, 1, guestName, 1, guestName);
                drools.insert(seating);
                Path path = new Path(count.getValue(), 1, guestName);
                drools.insert(path);
                count.setValue(count.getValue());
                drools.update(tuple.get(countDeclaration), count);
                context.setState(Context.ASSIGN_SEATS);
                // drools.update( tuple.get( contextDeclaration ),
                // context );
                drools.update(tuple.get(contextDeclaration));
            // System.err.println( "assign first seat :  " + seating + " : " + 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) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) 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) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) ConsequenceException(org.drools.core.spi.ConsequenceException)

Example 74 with ObjectOutput

use of java.io.ObjectOutput in project drools by kiegroup.

the class BaseMannersTest method getPathDone.

/**
 * <pre>
 * rule pathDone() {
 *     Context context; Seating seating;
 *     when {
 *         context : Context( state == Context.MAKE_PATH )
 *         seating : Seating( pathDone == false )
 *     } then {
 *         seating.setPathDone( true );
 *         context.setName( Context.CHECK_DONE );
 *     }
 * }
 * </pre>
 *
 * @return
 * @throws InvalidRuleException
 */
private RuleImpl getPathDone() throws InvalidRuleException {
    final RuleImpl rule = new RuleImpl("pathDone");
    // -----------
    // context : Context( state == Context.MAKE_PATH )
    // -----------
    final Pattern contextPattern = new Pattern(0, this.contextType, "context");
    contextPattern.addConstraint(getLiteralConstraint(contextPattern, "state", Context.MAKE_PATH));
    rule.addPattern(contextPattern);
    final Declaration contextDeclaration = rule.getDeclaration("context");
    // ---------------
    // seating : Seating( pathDone == false )
    // ---------------
    final Pattern seatingPattern = new Pattern(1, this.seatingType, "seating");
    seatingPattern.addConstraint(getLiteralConstraint(seatingPattern, "pathDone", false));
    rule.addPattern(seatingPattern);
    final Declaration seatingDeclaration = rule.getDeclaration("seating");
    // ------------
    // context.setName( Context.CHECK_DONE );
    // seating.setPathDone( true );
    // ------------
    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);
                Seating seating = (Seating) drools.get(seatingDeclaration);
                seating.setPathDone(true);
                // if ( seating.getId() == 6 ) {
                // System.err.println( "pause" );
                // }
                drools.update(tuple.get(seatingDeclaration));
                context.setState(Context.CHECK_DONE);
                drools.update(tuple.get(contextDeclaration), context);
            // System.err.println( "path done" + seating );
            } 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) Consequence(org.drools.core.spi.Consequence) RuleImpl(org.drools.core.definitions.rule.impl.RuleImpl) 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) KnowledgeHelper(org.drools.core.spi.KnowledgeHelper) Declaration(org.drools.core.rule.Declaration) ObjectInput(java.io.ObjectInput) ConsequenceException(org.drools.core.spi.ConsequenceException)

Example 75 with ObjectOutput

use of java.io.ObjectOutput 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)

Aggregations

ObjectOutput (java.io.ObjectOutput)77 ObjectOutputStream (java.io.ObjectOutputStream)47 ByteArrayOutputStream (java.io.ByteArrayOutputStream)46 IOException (java.io.IOException)33 ObjectInput (java.io.ObjectInput)25 Test (org.junit.Test)20 ObjectInputStream (java.io.ObjectInputStream)15 ByteArrayInputStream (java.io.ByteArrayInputStream)14 WorkingMemory (org.drools.core.WorkingMemory)13 RuleImpl (org.drools.core.definitions.rule.impl.RuleImpl)12 Pattern (org.drools.core.rule.Pattern)12 Consequence (org.drools.core.spi.Consequence)12 KnowledgeHelper (org.drools.core.spi.KnowledgeHelper)12 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)8 Declaration (org.drools.core.rule.Declaration)8 IntrospectionException (java.beans.IntrospectionException)7 InvalidRuleException (org.drools.core.rule.InvalidRuleException)7 ConsequenceException (org.drools.core.spi.ConsequenceException)7 OutputStream (java.io.OutputStream)6 ClassObjectType (org.drools.core.base.ClassObjectType)6