Search in sources :

Example 66 with LeftTuple

use of org.drools.core.reteoo.LeftTuple in project drools by kiegroup.

the class Misc2Test method testBetaMemoryLeakOnSegmentUnlinking.

@Test
@Ignore
public void testBetaMemoryLeakOnSegmentUnlinking() {
    // DROOLS-915
    String drl = "rule R1 when\n" + "    $a : Integer(this == 1)\n" + "    $b : String()\n" + "    $c : Integer(this == 2)\n" + "    $d : Integer(this == 3)\n" + "then \n" + "end\n" + "rule R2 when\n" + "    $a : Integer(this == 1)\n" + "    $b : String()\n" + "then \n" + "end\n";
    KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession();
    FactHandle fh1 = ksession.insert(1);
    FactHandle fh2 = ksession.insert(2);
    FactHandle fh3 = ksession.insert(3);
    FactHandle fhtest = ksession.insert("test");
    ksession.fireAllRules();
    ksession.delete(fh3);
    ksession.fireAllRules();
    ksession.delete(fh1);
    ksession.delete(fh2);
    ksession.delete(fhtest);
    ksession.fireAllRules();
    NodeMemories nodeMemories = ((InternalWorkingMemory) ksession).getNodeMemories();
    for (int i = 0; i < nodeMemories.length(); i++) {
        Memory memory = nodeMemories.peekNodeMemory(i);
        if (memory != null && memory.getSegmentMemory() != null) {
            SegmentMemory segmentMemory = memory.getSegmentMemory();
            System.out.println(memory);
            LeftTuple deleteFirst = memory.getSegmentMemory().getStagedLeftTuples().getDeleteFirst();
            System.out.println(deleteFirst);
            assertNull(deleteFirst);
        }
    }
}
Also used : InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) SegmentMemory(org.drools.core.reteoo.SegmentMemory) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) WorkingMemory(org.drools.core.WorkingMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) Memory(org.drools.core.common.Memory) SegmentMemory(org.drools.core.reteoo.SegmentMemory) KieHelper(org.kie.internal.utils.KieHelper) KieSession(org.kie.api.runtime.KieSession) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) NodeMemories(org.drools.core.common.NodeMemories) LeftTuple(org.drools.core.reteoo.LeftTuple) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 67 with LeftTuple

use of org.drools.core.reteoo.LeftTuple in project drools by kiegroup.

the class BaseMannersTest method getContinueProcessing.

/**
 * <pre>
 * rule continue() {
 *     Context context;
 *     when {
 *         context : Context( state == Context.CHECK_DONE )
 *     } then {
 *         context.setState( Context.ASSIGN_SEATS );
 *     }
 * }
 * </pre>
 * @return
 * @throws InvalidRuleException
 */
private RuleImpl getContinueProcessing() throws InvalidRuleException {
    final RuleImpl rule = new RuleImpl("continueProcessng");
    // -----------
    // 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");
    // ------------
    // context.setName( Context.ASSIGN_SEATS );
    // ------------
    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.ASSIGN_SEATS);
                drools.update(tuple.get(contextDeclaration), context);
            // System.err.println( "continue processing" );
            } 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) 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 68 with LeftTuple

use of org.drools.core.reteoo.LeftTuple 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 69 with LeftTuple

use of org.drools.core.reteoo.LeftTuple 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 70 with LeftTuple

use of org.drools.core.reteoo.LeftTuple in project drools by kiegroup.

the class EvalGenerator method generate.

public static void generate(final EvalStub stub, final Tuple tuple, final Declaration[] declarations, final WorkingMemory workingMemory) {
    final String[] globals = stub.getGlobals();
    final String[] globalTypes = stub.getGlobalTypes();
    // Sort declarations based on their offset, so it can ascend the tuple's parents stack only once
    final List<DeclarationMatcher> declarationMatchers = matchDeclarationsToTuple(declarations);
    final ClassGenerator generator = createInvokerClassGenerator(stub, workingMemory).setInterfaces(EvalExpression.class, CompiledInvoker.class);
    generator.addMethod(ACC_PUBLIC, "createContext", generator.methodDescr(Object.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            mv.visitInsn(ACONST_NULL);
            mv.visitInsn(ARETURN);
        }
    }).addMethod(ACC_PUBLIC, "clone", generator.methodDescr(EvalExpression.class), new ClassGenerator.MethodBody() {

        public void body(MethodVisitor mv) {
            mv.visitVarInsn(ALOAD, 0);
            mv.visitInsn(ARETURN);
        }
    }).addMethod(ACC_PUBLIC, "replaceDeclaration", generator.methodDescr(null, Declaration.class, Declaration.class)).addMethod(ACC_PUBLIC, "evaluate", generator.methodDescr(Boolean.TYPE, Tuple.class, Declaration[].class, WorkingMemory.class, Object.class), new String[] { "java/lang/Exception" }, new GeneratorHelper.EvaluateMethod() {

        public void body(MethodVisitor mv) {
            objAstorePos = 7;
            String[] expectedDeclarations = stub.getExpectedDeclarationTypes();
            int[] declarationsParamsPos = new int[declarations.length];
            mv.visitVarInsn(ALOAD, 1);
            cast(LeftTuple.class);
            // LeftTuple
            mv.visitVarInsn(ASTORE, 5);
            Tuple currentTuple = tuple;
            for (DeclarationMatcher matcher : declarationMatchers) {
                int i = matcher.getOriginalIndex();
                declarationsParamsPos[i] = objAstorePos;
                currentTuple = traverseTuplesUntilDeclaration(currentTuple, matcher.getRootDistance(), 5);
                mv.visitVarInsn(ALOAD, 2);
                push(i);
                // declarations[i]
                mv.visitInsn(AALOAD);
                // workingMemory
                mv.visitVarInsn(ALOAD, 3);
                mv.visitVarInsn(ALOAD, 5);
                invokeInterface(LeftTuple.class, "getFactHandle", InternalFactHandle.class);
                // tuple.getFactHandle().getObject()
                invokeInterface(InternalFactHandle.class, "getObject", Object.class);
                storeObjectFromDeclaration(declarations[i], expectedDeclarations[i]);
            }
            // @{ruleClassName}.@{methodName}(@foreach{declarations}, @foreach{globals})
            StringBuilder evalMethodDescr = new StringBuilder("(");
            for (int i = 0; i < declarations.length; i++) {
                // declarations[i]
                load(declarationsParamsPos[i]);
                evalMethodDescr.append(typeDescr(expectedDeclarations[i]));
            }
            // @foreach{type : globalTypes, identifier : globals} @{type} @{identifier} = ( @{type} ) workingMemory.getGlobal( "@{identifier}" );
            parseGlobals(globals, globalTypes, 3, evalMethodDescr);
            evalMethodDescr.append(")Z");
            mv.visitMethodInsn(INVOKESTATIC, stub.getInternalRuleClassName(), stub.getMethodName(), evalMethodDescr.toString());
            mv.visitInsn(IRETURN);
        }
    });
    stub.setEval(generator.<EvalExpression>newInstance());
}
Also used : WorkingMemory(org.drools.core.WorkingMemory) DeclarationMatcher(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.DeclarationMatcher) LeftTuple(org.drools.core.reteoo.LeftTuple) MethodVisitor(org.mvel2.asm.MethodVisitor) EvalExpression(org.drools.core.spi.EvalExpression) GeneratorHelper.createInvokerClassGenerator(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.createInvokerClassGenerator) InternalFactHandle(org.drools.core.common.InternalFactHandle) GeneratorHelper.matchDeclarationsToTuple(org.drools.core.rule.builder.dialect.asm.GeneratorHelper.matchDeclarationsToTuple) LeftTuple(org.drools.core.reteoo.LeftTuple) Tuple(org.drools.core.spi.Tuple)

Aggregations

LeftTuple (org.drools.core.reteoo.LeftTuple)125 RightTuple (org.drools.core.reteoo.RightTuple)41 TupleMemory (org.drools.core.reteoo.TupleMemory)37 InternalFactHandle (org.drools.core.common.InternalFactHandle)34 FastIterator (org.drools.core.util.FastIterator)22 BetaConstraints (org.drools.core.common.BetaConstraints)21 BetaMemory (org.drools.core.reteoo.BetaMemory)21 ContextEntry (org.drools.core.rule.ContextEntry)20 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)18 PhreakJoinNode.updateChildLeftTuple (org.drools.core.phreak.PhreakJoinNode.updateChildLeftTuple)16 AccumulateContext (org.drools.core.reteoo.AccumulateNode.AccumulateContext)13 SegmentMemory (org.drools.core.reteoo.SegmentMemory)13 Test (org.junit.Test)13 KieSession (org.kie.api.runtime.KieSession)13 Tuple (org.drools.core.spi.Tuple)12 WorkingMemory (org.drools.core.WorkingMemory)11 LeftInputAdapterNode (org.drools.core.reteoo.LeftInputAdapterNode)11 FromMemory (org.drools.core.reteoo.FromNode.FromMemory)10 AccumulateMemory (org.drools.core.reteoo.AccumulateNode.AccumulateMemory)9 ArrayList (java.util.ArrayList)8