Package org.drools.core.impl

Examples of org.drools.core.impl.StatefulKnowledgeSessionImpl


        conf.setOption( EventProcessingOption.STREAM );
        final KnowledgeBase kbase = loadKnowledgeBase( conf, "test_CEP_SimpleTimeWindow.drl" );
       
        KieSessionConfiguration sconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
        sconf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );
        StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl)createKnowledgeSession( kbase, sconf );

        WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger( (WorkingMemory) wm );
        File testTmpDir = new File( "target/test-tmp/" );
        testTmpDir.mkdirs();
        logger.setFileName( "target/test-tmp/testIdleTimeAndTimeToNextJob-audit" );

        try {
            List results = new ArrayList();

            wm.setGlobal( "results",
                          results );

            // how to initialize the clock?
            // how to configure the clock?
            SessionPseudoClock clock = (SessionPseudoClock) wm.getSessionClock();
            clock.advanceTime( 5,
                               TimeUnit.SECONDS ); // 5 seconds

            // there is no next job, so returns -1
            assertEquals( -1,
                          wm.getTimeToNextJob() );
            wm.insert( new OrderEvent( "1",
                                       "customer A",
                                       70 ) );
            assertEquals( 0,
                          wm.getIdleTime() );
            // now, there is a next job in 30 seconds: expire the event
            assertEquals( 30000,
                          wm.getTimeToNextJob() );

            wm.fireAllRules();
            assertEquals( 1,
                          results.size() );
            assertEquals( 70,
                          ((Number) results.get( 0 )).intValue() );

            // advance clock and assert new data
            clock.advanceTime( 10,
                               TimeUnit.SECONDS ); // 10 seconds
            // next job is in 20 seconds: expire the event
            assertEquals( 20000,
                          wm.getTimeToNextJob() );

            wm.insert( new OrderEvent( "2",
                                       "customer A",
                                       60 ) );
            wm.fireAllRules();

            assertEquals( 2,
                          results.size() );
            assertEquals( 65,
                          ((Number) results.get( 1 )).intValue() );

            // advance clock and assert new data
            clock.advanceTime( 10,
                               TimeUnit.SECONDS ); // 10 seconds
            // next job is in 10 seconds: expire the event
            assertEquals( 10000,
                          wm.getTimeToNextJob() );

            wm.insert( new OrderEvent( "3",
                                       "customer A",
                                       50 ) );
            wm.fireAllRules();
            assertEquals( 3,
                          results.size() );
            assertEquals( 60,
                          ((Number) results.get( 2 )).intValue() );

            // advance clock and assert new data
            clock.advanceTime( 10,
                               TimeUnit.SECONDS ); // 10 seconds
            // advancing clock time will cause events to expire
            assertEquals( 0,
                          wm.getIdleTime() );
            // next job is in 10 seconds: expire another event
            //assertEquals( 10000, iwm.getTimeToNextJob());

            wm.insert( new OrderEvent( "4",
                                       "customer A",
                                       25 ) );
            wm.fireAllRules();

            // first event should have expired, making average under the rule threshold, so no additional rule fire
            assertEquals( 3,
                          results.size() );

            // advance clock and assert new data
            clock.advanceTime( 10,
                               TimeUnit.SECONDS ); // 10 seconds

            wm.insert( new OrderEvent( "5",
                                       "customer A",
                                       70 ) );
            assertEquals( 0,
                          wm.getIdleTime() );

            //        wm  = SerializationHelper.serializeObject(wm);
            wm.fireAllRules();

            // still under the threshold, so no fire
            assertEquals( 3,
                          results.size() );
        } finally {
View Full Code Here


        PersisterHelper.writeToStreamWithHeader( context,
                                                 _session );
    }

    private static ProtobufMessages.KnowledgeSession serializeSession(MarshallerWriteContext context) throws IOException {
        StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) context.wm;

        try {
            wm.getLock().lock();
            for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
                if (ep instanceof NamedEntryPoint) {
                    ((NamedEntryPoint)ep).lock();
                }
            }

            ((InternalAgenda)wm.getAgenda()).unstageActivations();

            evaluateRuleActivations( wm );

            ProtobufMessages.RuleData.Builder _ruleData = ProtobufMessages.RuleData.newBuilder();

            long time = 0;
            if ( context.wm.getTimerService() instanceof PseudoClockScheduler ) {
                time = context.clockTime;
            }
            _ruleData.setLastId( wm.getFactHandleFactory().getId() );
            _ruleData.setLastRecency( wm.getFactHandleFactory().getRecency() );

            InternalFactHandle handle = context.wm.getInitialFactHandle();
            if ( handle != null ) {
                // can be null for RETE, if fireAllRules has not yet been called
                ProtobufMessages.FactHandle _ifh = ProtobufMessages.FactHandle.newBuilder()
                        .setType( ProtobufMessages.FactHandle.HandleType.INITIAL_FACT )
                        .setId( handle.getId() )
                        .setRecency( handle.getRecency() )
                        .build();
                _ruleData.setInitialFact( _ifh );
            }

            writeAgenda( context, _ruleData );

            writeNodeMemories( context, _ruleData );

            for ( EntryPoint wmep : wm.getWorkingMemoryEntryPoints().values() ) {
                org.drools.core.marshalling.impl.ProtobufMessages.EntryPoint.Builder _epb = ProtobufMessages.EntryPoint.newBuilder();
                _epb.setEntryPointId( wmep.getEntryPointId() );

                writeObjectTypeConfiguration( context,
                                              ((InternalWorkingMemoryEntryPoint)wmep).getObjectTypeConfigurationRegistry(),
                                              _epb );

                writeFactHandles( context,
                                  _epb,
                                  ((NamedEntryPoint) wmep).getObjectStore() );

                writeTruthMaintenanceSystem( context,
                                             wmep,
                                             _epb );

                _ruleData.addEntryPoint( _epb.build() );
            }

            writeActionQueue( context,
                              _ruleData );

            ProtobufMessages.KnowledgeSession.Builder _session = ProtobufMessages.KnowledgeSession.newBuilder()
                    .setMultithread( false )
                    .setTime( time )
                    .setRuleData( _ruleData.build() );

            if ( processMarshaller != null ) {
                Builder _pdata = ProtobufMessages.ProcessData.newBuilder();
                if ( context.marshalProcessInstances ) {
                    context.parameterObject = _pdata;
                    processMarshaller.writeProcessInstances( context );
                }

                if ( context.marshalWorkItems ) {
                    context.parameterObject = _pdata;
                    processMarshaller.writeWorkItems( context );
                }

                // this now just assigns the writer, it will not write out any timer information
                context.parameterObject = _pdata;
                processMarshaller.writeProcessTimers( context );

                _session.setProcessData( _pdata.build() );
            }

            Timers _timers = writeTimers( context.wm.getTimerService().getTimerJobInstances( context.wm.getId() ),
                                          context );
            if ( _timers != null ) {
                _session.setTimers( _timers );
            }

            return _session.build();
        } finally {
            for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
                if (ep instanceof NamedEntryPoint) {
                    ((NamedEntryPoint)ep).unlock();
                }
            }
            wm.getLock().unlock();
        }
    }
View Full Code Here

    }

    public static void writeActionQueue(MarshallerWriteContext context,
                                        ProtobufMessages.RuleData.Builder _session) throws IOException {

        StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) context.wm;
        if ( !wm.getActionQueue().isEmpty() ) {
            ProtobufMessages.ActionQueue.Builder _queue = ProtobufMessages.ActionQueue.newBuilder();

            WorkingMemoryAction[] queue = wm.getActionQueue().toArray( new WorkingMemoryAction[wm.getActionQueue().size()] );
            for ( int i = queue.length - 1; i >= 0; i-- ) {
                _queue.addAction( queue[i].serialize( context ) );
            }
            _session.setActionQueue( _queue.build() );
        }
View Full Code Here

     * Create a new session into which to read the stream data
     */
    public static StatefulKnowledgeSessionImpl readSession(MarshallerReaderContext context,
                                                    int id) throws IOException,
                                                           ClassNotFoundException {
        StatefulKnowledgeSessionImpl session = readSession( context,
                                                     id,
                                                     EnvironmentFactory.newEnvironment(),
                                                     SessionConfiguration.getDefaultInstance() );
        return session;
    }
View Full Code Here

                                                    SessionConfiguration config) throws IOException,
                                                                                ClassNotFoundException {

        ProtobufMessages.KnowledgeSession _session = loadAndParseSession( context );

        StatefulKnowledgeSessionImpl session = createAndInitializeSession( context,
                                                                    id,
                                                                    environment,
                                                                    config,
                                                                    _session );

        return readSession( _session,
                            session,
                            (InternalAgenda) session.getAgenda(),
                            context );
    }
View Full Code Here

        readAgenda( context,
                    _session.getRuleData(),
                    agenda );

        WorkingMemoryFactory wmFactory = context.kBase.getConfiguration().getComponentFactory().getWorkingMemoryFactory();
        StatefulKnowledgeSessionImpl session = ( StatefulKnowledgeSessionImpl ) wmFactory.createWorkingMemory( id,
                                                                                                 context.kBase,
                                                                                                 handleFactory,
                                                                                                 null,
                                                                                                 1, // pCTx starts at 1, as InitialFact is 0
                                                                                                 config,
View Full Code Here

    }

    public static void readActionQueue(MarshallerReaderContext context,
                                       RuleData _session) throws IOException,
                                                         ClassNotFoundException {
        StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) context.wm;
        Queue<WorkingMemoryAction> actionQueue = wm.getActionQueue();
        for ( ProtobufMessages.ActionQueue.Action _action : _session.getActionQueue().getActionList() ) {
            actionQueue.offer( PersisterHelper.deserializeWorkingMemoryAction( context,
                                                                               _action ) );
        }
    }
View Full Code Here

                                                                       environment );

        int id = ((KnowledgeBaseImpl) this.kbase).nextWorkingMemoryCounter();
        RuleBaseConfiguration conf = ((KnowledgeBaseImpl) this.kbase).getConfiguration();

        StatefulKnowledgeSessionImpl session = ProtobufInputMarshaller.readSession( context,
                                                                             id,
                                                                             environment,
                                                                             (SessionConfiguration) config );
        context.close();
        if ( ((SessionConfiguration) config).isKeepReference() ) {
View Full Code Here

                                                           new MockTupleSource(idGenerator.getNextId()),
                                                           rule1,
                                                           rule1.getLhs(),
                                                           0,
                                                           buildContext);
        StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newStatefulKnowledgeSession();

        final InternalAgenda agenda = (InternalAgenda) ksession.getAgenda();

        final Consequence consequence = new Consequence() {
            private static final long serialVersionUID = 510l;

            public void evaluate(KnowledgeHelper knowledgeHelper,
                                 WorkingMemory workingMemory) {
                LinkedList<LogicalDependency<M>> list = ((DefaultKnowledgeHelper) knowledgeHelper).getpreviousJustified();
                if (list != null) {
                    for (SimpleLogicalDependency dep = (SimpleLogicalDependency ) list.getFirst(); dep != null; dep =  ( SimpleLogicalDependency ) dep.getNext() ){
                        knowledgeHelper.insertLogical( dep.getObject(), dep.getMode() );
                    }
                }
            }

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

            }

            public void writeExternal(ObjectOutput out) throws IOException {

            }

            public String getName() {
                return "default";
            }
        };

        rule1.setConsequence( consequence );

        final DefaultFactHandle handle1 = (DefaultFactHandle) ksession.insert( "o1" );
        final RuleTerminalNodeLeftTuple tuple1 = new RuleTerminalNodeLeftTuple( handle1,
                                                                                node,
                                                                                true );

        final PropagationContext context1 = pctxFactory.createPropagationContext(0, PropagationContext.INSERTION, null, null, new DefaultFactHandle());

        // Test single activation for a single logical assertions
        node.assertLeftTuple( tuple1,
                              context1,
                              ksession );

        final String logicalString = new String( "logical" );
        InternalFactHandle logicalHandle = (InternalFactHandle) ksession.insert( logicalString,
                                                                                      null,
                                                                                      false,
                                                                                      true,
                                                                                      rule1,
                                                                                      (Activation) tuple1.getObject() );
        new RightTuple( logicalHandle,
                        sink );
        context1.setFactHandle( handle1 );
        // Retract the tuple and test the logically asserted fact was also deleted
        node.retractLeftTuple( tuple1,
                               context1,
                               ksession );

        ksession.executeQueuedActions();

        assertLength( 1,
                      sink.getRetracted() );

        Object[] values = (Object[]) sink.getRetracted().get( 0 );

        assertSame( logicalHandle,
                    ((RightTuple) values[0]).getFactHandle() );

        // Test single activation for a single logical assertions. This also
        // tests that logical assertions live on after the related Activation
        // has fired.
        node.assertLeftTuple( tuple1,
                              context1,
                              ksession );
        logicalHandle = (InternalFactHandle) ksession.insert( logicalString,
                                                                   null,
                                                                   false,
                                                                   true,
                                                                   rule1,
                                                                   (Activation) tuple1.getObject() );

        new RightTuple( logicalHandle,
                        sink );

        agenda.fireNextItem( null, 0, -1 );

        node.retractLeftTuple( tuple1,
                               context1,
                               ksession );

        ksession.executeQueuedActions();

        assertLength( 2,
                      sink.getRetracted() );

        values = (Object[]) sink.getRetracted().get( 1 );
View Full Code Here

                                                            rule1,
                                                            rule1.getLhs(),
                                                            0,
                                                            buildContext );

        StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newStatefulKnowledgeSession();

        final Agenda agenda = ksession.getAgenda();

        final Consequence consequence = new Consequence() {
            private static final long serialVersionUID = 510l;

            public void evaluate(KnowledgeHelper knowledgeHelper,
                                 WorkingMemory workingMemory) {
                LinkedList< LogicalDependency<M>> list = ((DefaultKnowledgeHelper)knowledgeHelper).getpreviousJustified();
                if ( list != null ) {
                    for ( SimpleLogicalDependency dep = ( SimpleLogicalDependency ) list.getFirst(); dep != null; dep =  ( SimpleLogicalDependency ) dep.getNext() ){
                        knowledgeHelper.insertLogical( dep.getObject(), dep.getMode() );
                    }
                }
            }

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

            }

            public void writeExternal(ObjectOutput out) throws IOException {

            }

            public String getName() {
                return "default";
            }
        };
        rule1.setConsequence( consequence );

        final DefaultFactHandle handle1 = new DefaultFactHandle( 1,
                                                                 "cheese" );
        final RuleTerminalNodeLeftTuple tuple1 = new RuleTerminalNodeLeftTuple( handle1,
                                                                                node,
                                                                                true );

        final PropagationContext context1 = pctxFactory.createPropagationContext(0, PropagationContext.INSERTION, null, null, new DefaultFactHandle());

        // Test single activation for a single logical assertions
        node.assertLeftTuple( tuple1,
                              context1,
                              ksession );

        final String logicalString1 = new String( "logical" );
        FactHandle logicalHandle1 = ksession.insert( logicalString1,
                                                          null,
                                                          false,
                                                          true,
                                                          rule1,
                                                          (Activation) tuple1.getObject() );

        final String logicalString2 = new String( "logical" );
        FactHandle logicalHandle2 = ksession.insert( logicalString2,
                                                          null,
                                                          false,
                                                          true,
                                                          rule1,
                                                          (Activation) tuple1.getObject() );

        assertSame( logicalHandle1,
                    logicalHandle2 );

        // little sanity check using normal assert
        logicalHandle1 = ksession.insert( logicalString1 );
        logicalHandle2 = ksession.insert( logicalString2 );

        // If assert behavior in working memory is IDENTITY,
        // returned handles must not be the same
        if ( RuleBaseConfiguration.AssertBehaviour.IDENTITY.equals( kBase.getConfiguration().getAssertBehaviour() ) ) {
View Full Code Here

TOP

Related Classes of org.drools.core.impl.StatefulKnowledgeSessionImpl

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.