org.kie.api.runtime.KieSessionConfiguration Java Examples

The following examples show how to use org.kie.api.runtime.KieSessionConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSession( String ruleFile ) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newClassPathResource(ruleFile),
                     ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
            fail();
        }
    } finally {
        System.setProperty("drools.negatable", "off");
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
    kBase.addPackages( kBuilder.getKnowledgePackages() );


    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );

    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #2
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private KieSession marsallStatefulKnowledgeSession(KieSession ksession) throws IOException,
                                                                                                   ClassNotFoundException {
    Globals globals = ksession.getGlobals();

    KieBase kbase = ksession.getKieBase();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    MarshallerFactory.newMarshaller( kbase ).marshall( out,
                                                       ksession );

    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( TimerJobFactoryOption.get("trackable") );
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );

    Environment env = EnvironmentFactory.newEnvironment();
    env.set( EnvironmentName.GLOBALS, globals );
    ksession = MarshallerFactory.newMarshaller( kbase ).unmarshall( new ByteArrayInputStream( out.toByteArray() ), ksconf, env );

    return ksession;
}
 
Example #3
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieSession newKieSession(String kSessionName, Environment environment, KieSessionConfiguration conf) {
    KieSessionModelImpl kSessionModel = kSessionName != null ?
                                        (KieSessionModelImpl) getKieSessionModel(kSessionName) :
                                        (KieSessionModelImpl) findKieSessionModel(false);

    if ( kSessionModel == null ) {
        log.error("Unknown KieSession name: " + kSessionName);
        return null;
    }

    KieBase kBase = getKieBaseFromKieSessionModel( kSessionModel );
    if ( kBase == null ) return null;

    KieSession kSession = kBase.newKieSession( conf != null ? conf : getKieSessionConfiguration( kSessionModel ), environment );
    registerNewKieSession( kSessionModel, ( InternalKnowledgeBase ) kBase, kSession );
    return kSession;
}
 
Example #4
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
StatefulSessionPool createKieSessionsPool(String kSessionName, KieSessionConfiguration conf, Environment env, int initialSize, boolean stateless) {
    KieSessionModel kSessionModel = kSessionName != null ? getKieSessionModel(kSessionName) : findKieSessionModel(false);
    if ( kSessionModel == null ) {
        log.error("Unknown KieSession name: " + kSessionName);
        return null;
    }
    KnowledgeBaseImpl kBase = (KnowledgeBaseImpl) getKieBaseFromKieSessionModel( kSessionModel );
    return kBase == null ? null : new StatefulSessionPool(kBase, initialSize, () -> {
        SessionConfiguration sessConf = conf != null ? (SessionConfiguration) conf : kBase.getSessionConfiguration();
        StatefulKnowledgeSessionImpl kSession = stateless ?
                kBase.internalCreateStatefulKnowledgeSession( env, sessConf, false ).setStateless( true ) :
                (StatefulKnowledgeSessionImpl) kBase.newKieSession( sessConf, env );
        registerNewKieSession( kSessionModel, ( InternalKnowledgeBase ) kBase, kSession );
        return kSession;
    });
}
 
Example #5
Source File: KnowledgeBaseImpl.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
KieSession newKieSession(KieSessionConfiguration conf, Environment environment, boolean fromPool) {
    // NOTE if you update here, you'll also need to update the JPAService
    if ( conf == null ) {
        conf = getSessionConfiguration();
    }

    SessionConfiguration sessionConfig = (SessionConfiguration) conf;

    if ( environment == null ) {
        environment = EnvironmentFactory.newEnvironment();
    }

    if ( this.getConfiguration().isSequential() ) {
        throw new RuntimeException( "Cannot have a stateful rule session, with sequential configuration set to true" );
    }

    readLock();
    try {
        return internalCreateStatefulKnowledgeSession( environment, sessionConfig, fromPool );
    } finally {
        readUnlock();
    }
}
 
Example #6
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromString( String drlString, KieBaseConfiguration kbConf ) {
    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent( drlString, ResourceType.DRL );

    Results res = kieHelper.verify();
    if ( res.hasMessages( Message.Level.ERROR ) ) {
        fail( res.getMessages( Message.Level.ERROR ).toString() );
    }

    if ( kbConf == null ) {
        kbConf = KieServices.Factory.get().newKieBaseConfiguration();
    }
    kbConf.setOption( EqualityBehaviorOption.EQUALITY );
    KieBase kieBase = kieHelper.build( kbConf );


    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );
    return kieBase.newKieSession( ksConf, null );
}
 
Example #7
Source File: JTMSTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromString( String drlString) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newByteArrayResource(drlString.getBytes()),
                     ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
            fail();
        }
    } finally {
        System.setProperty("drools.negatable", "off");
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase( );
    kBase.addPackages( kBuilder.getKnowledgePackages() );

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.JTMS );
    
    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #8
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static KieSession marshallAndUnmarshall(KieBase kbase1, KieBase kbase2, KieSession ksession, KieSessionConfiguration sessionConfig) {
    // Serialize and Deserialize
    try {
        KieMarshallers kieMarshallers = KieServices.Factory.get().getMarshallers();
        Marshaller marshaller = kieMarshallers.newMarshaller( kbase1 );
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        marshaller.marshall(baos, ksession);
        marshaller = kieMarshallers.newMarshaller( kbase2 );
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        baos.close();
        ksession = marshaller.unmarshall(bais, sessionConfig, null);
        bais.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("unexpected exception :" + e.getMessage());
    }
    return ksession;
}
 
Example #9
Source File: JTMSTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromFile( String ruleFile ) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add( ResourceFactory.newClassPathResource( ruleFile, getClass() ),
            ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
        fail();
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase( );
    kBase.addPackages( kBuilder.getKnowledgePackages() );

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.JTMS );
    
    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #10
Source File: FireUntilHaltAccumulateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
        System.err.println(kbuilder.getErrors().toString());
    }
    final KieBaseConfiguration config =
            KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption( EventProcessingOption.STREAM);

    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(config);
    kbase.addPackages(kbuilder.getKnowledgePackages());

    final KieSessionConfiguration sessionConfig =
            KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ));

    this.statefulSession = kbase.newKieSession(sessionConfig, null);
    this.stockFactory = new StockFactory(kbase);
}
 
Example #11
Source File: LengthSlidingWindowTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void checkPrice( String drl, double expectedPrice ) {
    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
                                         .build( EventProcessingOption.STREAM )
                                         .newKieSession( sessionConfig, null );

    List<Double> list = new ArrayList<Double>();
    ksession.setGlobal( "list", list );

    ksession.insert( "RHT" );
    ksession.insert( new StockTick( 1L, "RHT", 10.0 ) );
    ksession.insert( new StockTick( 2L, "RHT", 10.0 ) );
    ksession.insert( new StockTick( 3L, "ABC", 20.0 ) );
    ksession.insert( new StockTick( 4L, "RHT", 10.0 ) );
    ksession.insert( new StockTick( 5L, "XYZ", 20.0 ) );
    ksession.insert( new StockTick( 6L, "XYZ", 20.0 ) );
    ksession.insert( new StockTick( 7L, "RHT", 10.0 ) );

    ksession.fireAllRules();

    assertEquals( 1, list.size() );
    assertEquals( expectedPrice, (double)list.get(0), 0.01 );
}
 
Example #12
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void testEventsExpiredInThePast(final String drl) {
    final KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    final KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    final KieBase kieBase = helper.build( EventProcessingOption.STREAM );
    final KieSession kieSession = kieBase.newKieSession( sessionConfig, null );

    PseudoClockScheduler clock = kieSession.getSessionClock();

    final long currentTime = clock.getCurrentTime();

    clock.advanceTime(100, TimeUnit.MILLISECONDS);

    kieSession.insert(new BasicEvent(new Date(currentTime + 20), 10L, "20ms-30ms"));
    clock.advanceTime(1, TimeUnit.MILLISECONDS);
    kieSession.insert(new BasicEvent(new Date(currentTime + 20), 20L, "20ms-40ms"));

    clock.advanceTime(100, TimeUnit.MILLISECONDS);

    assertThat(kieSession.fireAllRules()).isEqualTo(1);
    clock.advanceTime(10, TimeUnit.MILLISECONDS);
    assertThat(kieSession.getObjects()).isEmpty();
}
 
Example #13
Source File: CustomWorkItemHandlerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterHandlerWithKsessionUsingConfiguration() {
    KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    Properties props = new Properties();
    props.setProperty("drools.workItemHandlers", "CustomWorkItemHandlers.conf");
    KieSessionConfiguration config = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(props);
    
    KieSession ksession = kbase.newKieSession(config, EnvironmentFactory.newEnvironment());
    assertNotNull(ksession);
    // this test would fail on creation of the work item manager if injecting session is not supported
    WorkItemManager manager = ksession.getWorkItemManager();
    assertNotNull(manager);
    
    Map<String, WorkItemHandler> handlers = ((SessionConfiguration)config).getWorkItemHandlers();
    assertNotNull(handlers);
    assertEquals(1, handlers.size());
    assertTrue(handlers.containsKey("Custom"));
}
 
Example #14
Source File: ProtobufMarshaller.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public ReadSessionResult unmarshallWithMessage(final InputStream stream,
                                               KieSessionConfiguration config,
                                               Environment environment) throws IOException, ClassNotFoundException {
    if ( config == null ) {
        config = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    }

    if ( environment == null ) {
        environment = KieServices.get().newEnvironment();
    }

    MarshallerReaderContext context = getMarshallerReaderContext(stream, environment);
    int id = ((KnowledgeBaseImpl) this.kbase).nextWorkingMemoryCounter();
    ReadSessionResult readSessionResult = ProtobufInputMarshaller.readSession(context,
                                                                              id,
                                                                              environment,
                                                                              (SessionConfiguration) config,
                                                                              initializer);
    context.close();
    if ( ((SessionConfiguration) config).isKeepReference() ) {
        ((KnowledgeBaseImpl) this.kbase).addStatefulSession(readSessionResult.getSession());
    }
    return readSessionResult;
}
 
Example #15
Source File: JPAKnowledgeService.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static StatefulKnowledgeSession loadStatefulKnowledgeSession(Long id,
        KieBase kbase,
        KieSessionConfiguration configuration,
        Environment environment) {
    return (StatefulKnowledgeSession)getJPAKnowledgeServiceProvider().loadKieSession(id,
    kbase,
    configuration,
    environment);
}
 
Example #16
Source File: AbstractBaseTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSession createKieSession(boolean serializeKbase, KiePackage... pkg) throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Arrays.asList(pkg));
    if( serializeKbase ) { 
        kbase = JbpmSerializationHelper.serializeObject( kbase );
    }

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ForceEagerActivationOption.YES );
    return kbase.newKieSession(conf, null);
}
 
Example #17
Source File: FactHandleMarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatefulKnowledgeSessionImpl createWorkingMemory(InternalKnowledgeBase kBase) {
    // WorkingMemoryEntryPoint
    KieSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksconf.setOption( ClockTypeOption.get( "pseudo" ) );
    SessionConfiguration sessionConf = ((SessionConfiguration) ksconf);
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl(1L, kBase, true, sessionConf, EnvironmentFactory.newEnvironment());
    
    return wm;
}
 
Example #18
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void readWrite(KieBase knowledgeBase,
                       KieSession ksession,
                       KieSessionConfiguration config) {
    try {
        Marshaller marshaller = MarshallerFactory.newMarshaller( knowledgeBase );
        ByteArrayOutputStream o = new ByteArrayOutputStream();
        marshaller.marshall( o, ksession );
        ksession = marshaller.unmarshall( new ByteArrayInputStream( o.toByteArray() ), config, KieServices.get().newEnvironment() );
        ksession.fireAllRules();
        //scheduler = ksession.<SessionClock>getSessionClock();
    } catch ( Exception e ) {
        throw new RuntimeException( e );
    }
}
 
Example #19
Source File: StatelessKnowledgeSessionImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public StatelessKnowledgeSessionImpl(KieSessionConfiguration conf,
                                     StatefulSessionPool pool) {
    this.kBase = pool.getKieBase();
    this.conf = conf != null ? (SessionConfiguration) conf : kBase.getSessionConfiguration();
    this.environment = null;
    this.pool = pool;
    wmCreated = new AtomicLong(1);
}
 
Example #20
Source File: ActivationIteratorTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEagerEvaluation() throws Exception {
    String str =
            "package org.simple \n" +
            "rule xxx @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n" +
            "rule yyy @Propagation(EAGER) \n" +
            "when \n" +
            "  $s : String()\n" +
            "then \n" +
            "end  \n";

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ForceEagerActivationOption.YES );

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = createKnowledgeSession(kbase, conf);

    final List list = new ArrayList();

    AgendaEventListener agendaEventListener = new DefaultAgendaEventListener() {
        public void matchCreated(org.kie.api.event.rule.MatchCreatedEvent event) {
            list.add("activated");
        }
    };
    ksession.addEventListener(agendaEventListener);

    ksession.insert("test");

    assertEquals(2, list.size());
}
 
Example #21
Source File: PseudoClockEventsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private int processStocks(int stockCount, AgendaEventListener agendaEventListener, String drlContentString)
        throws Exception {
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(EventProcessingOption.STREAM);
    KieBase kbase = loadKnowledgeBaseFromString(kconf, drlContentString);

    KieSessionConfiguration ksessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksessionConfig.setOption(ClockTypeOption.get("pseudo"));
    ksessionConfig.setProperty("keep.reference", "true");
    final KieSession ksession = kbase.newKieSession(ksessionConfig, null);
    ksession.addEventListener(agendaEventListener);

    PseudoClockScheduler clock = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock();

    Thread fireUntilHaltThread = new Thread(ksession::fireUntilHalt, "Engine's thread");
    fireUntilHaltThread.start();
    try {
        Thread.currentThread().setName("Feeding thread");

        for (int stIndex = 1; stIndex <= stockCount; stIndex++) {
            clock.advanceTime(20, TimeUnit.SECONDS);
            Thread.sleep( 100 );
            final StockTickInterface st = new StockTick(stIndex,
                                                        "RHT",
                                                        100 * stIndex,
                                                        100 * stIndex);
            ksession.insert(st);
            Thread.sleep( 100 );
        }

        Thread.sleep(100);
    } finally {
        ksession.halt();
        ksession.dispose();
    }
    
    fireUntilHaltThread.join(5000);

    return stockCount;
}
 
Example #22
Source File: JPAKnowledgeService.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * Deprecated use {@link #loadStatefulKnowledgeSession(Long, KieBase, KieSessionConfiguration, Environment)} instead
 */
@Deprecated
public static StatefulKnowledgeSession loadStatefulKnowledgeSession(int id,
                                                                    KieBase kbase,
                                                                    KieSessionConfiguration configuration,
                                                                    Environment environment) {
    return (StatefulKnowledgeSession)getJPAKnowledgeServiceProvider().loadKieSession(id,
            kbase,
            configuration,
            environment);
}
 
Example #23
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public StatelessKieSession newStatelessKieSession(String kSessionName, KieSessionConfiguration conf) {
    KieSessionModelImpl kSessionModel = kSessionName != null ?
                                        (KieSessionModelImpl) getKieSessionModel(kSessionName) :
                                        (KieSessionModelImpl) findKieSessionModel(true);

    if ( kSessionModel == null ) {
        log.error("Unknown KieSession name: " + kSessionName);
        return null;
    }
    if (kSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
        throw new RuntimeException("Trying to create a stateless KieSession from a stateful KieSessionModel: " + kSessionModel.getName());
    }
    KieBase kBase = getKieBase( kSessionModel.getKieBaseModel().getName() );
    if ( kBase == null ) {
        log.error("Unknown KieBase name: " + kSessionModel.getKieBaseModel().getName());
        return null;
    }

    StatelessKieSession statelessKieSession = kBase.newStatelessKieSession( conf != null ? conf : getKieSessionConfiguration( kSessionModel ) );
    if (isJndiAvailable()) {
        wireSessionComponents( kSessionModel, statelessKieSession );
    }
    registerLoggers(kSessionModel, statelessKieSession);

    ((StatelessKnowledgeSessionImpl) statelessKieSession).initMBeans(containerId, ((InternalKnowledgeBase) kBase).getId(), kSessionModel.getName());

    statelessKSessions.put(kSessionModel.getName(), statelessKieSession);
    return statelessKieSession;
}
 
Example #24
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSessionConfiguration getKieSessionConfiguration( String kSessionName ) {
    KieSessionModelImpl kSessionModel = (KieSessionModelImpl) kProject.getKieSessionModel( kSessionName );
    if ( kSessionModel == null ) {
        log.error("Unknown KieSession name: " + kSessionName);
        return null;
    }
    return getKieSessionConfiguration( kSessionModel );
}
 
Example #25
Source File: DefeasibilityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected KieSession getSessionFromString( String drlString) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    try {
        System.setProperty("drools.negatable", "on");
        kBuilder.add(ResourceFactory.newByteArrayResource(drlString.getBytes()),
                     ResourceType.DRL);
        if (kBuilder.hasErrors()) {
            System.err.println(kBuilder.getErrors());
            fail();
        }
    } finally {
        System.setProperty("drools.negatable", "off");
    }

    KieBaseConfiguration kieBaseConfiguration = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieBaseConfiguration.setOption( EqualityBehaviorOption.EQUALITY );

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase( kieBaseConfiguration );
    kBase.addPackages( kBuilder.getKnowledgePackages() );

    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );

    KieSession kSession = kBase.newKieSession( ksConf, null );
    return kSession;
}
 
Example #26
Source File: JPAKnowledgeService.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static StatefulKnowledgeSession newStatefulKnowledgeSession(KieBase kbase,
                                                                   KieSessionConfiguration configuration,
                                                                   Environment environment) {
    return (StatefulKnowledgeSession)getJPAKnowledgeServiceProvider().newKieSession(kbase,
            configuration,
            environment);
}
 
Example #27
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlpha() {
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new A(1) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.insert( new A(2) );

    sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS );
    ksession.fireAllRules();
    assertEquals(2, counter.get());
}
 
Example #28
Source File: StatelessKnowledgeSessionImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public StatelessKnowledgeSessionImpl(InternalKnowledgeBase kBase,
                                     KieSessionConfiguration conf) {
    this.kBase = (KnowledgeBaseImpl)kBase;
    this.conf = conf != null ? (SessionConfiguration) conf : kBase.getSessionConfiguration();
    this.environment = EnvironmentFactory.newEnvironment();
    this.pool = null;
    wmCreated = new AtomicLong(0);
}
 
Example #29
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBetaRightExpired() {
    // DROOLS-1329
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "import " + B.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "declare B @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "  $b: B( id == $Aid )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \",\" + $b + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new A(1) );

    sessionClock.advanceTime( 20, TimeUnit.MILLISECONDS );
    ksession.insert( new B(1) );

    ksession.fireAllRules();
    assertEquals(0, counter.get());
}
 
Example #30
Source File: ExpirationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testBetaLeftExpired() {
    // DROOLS-1329
    String drl = "import " + A.class.getCanonicalName() + "\n" +
                 "import " + B.class.getCanonicalName() + "\n" +
                 "declare A @role( event ) @expires(11ms) end\n" +
                 "declare B @role( event ) @expires(11ms) end\n" +
                 "global java.util.concurrent.atomic.AtomicInteger counter;\n" +
                 "rule R0 when\n" +
                 "  $a: A( $Aid: id > 0 )\n" +
                 "  $b: B( id == $Aid )\n" +
                 "then\n" +
                 "  System.out.println(\"[\" + $a + \",\" + $b + \"]\");" +
                 "  counter.incrementAndGet();\n" +
                 "end";

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) );

    KieHelper helper = new KieHelper();
    helper.addContent( drl, ResourceType.DRL );
    KieBase kbase = helper.build( EventProcessingOption.STREAM );
    KieSession ksession = kbase.newKieSession( sessionConfig, null );

    PseudoClockScheduler sessionClock = ksession.getSessionClock();

    AtomicInteger counter = new AtomicInteger( 0 );
    ksession.setGlobal( "counter", counter );

    ksession.insert( new B(1) );

    sessionClock.advanceTime( 20, TimeUnit.MILLISECONDS );
    ksession.insert( new A(1) );

    ksession.fireAllRules();
    assertEquals(0, counter.get());
}