Search in sources :

Example 86 with KieBaseConfiguration

use of org.kie.api.KieBaseConfiguration in project drools by kiegroup.

the class MultithreadTest method testRaceOnAccumulateNodeSimple.

@Test(timeout = 5000)
public void testRaceOnAccumulateNodeSimple() throws InterruptedException {
    final String drl = "package org.drools.integrationtests;\n" + "" + "import " + Server.class.getCanonicalName() + ";\n" + "import " + IntEvent.class.getCanonicalName() + ";\n" + "" + "declare IntEvent\n" + "  @role ( event )\n" + "  @expires( 15s )\n" + "end\n" + "\n" + "" + "rule \"average temperature\"\n" + "when\n" + "  $s : Server (hostname == \"hiwaesdk\")\n" + " $avg := Number( ) from accumulate ( " + "      IntEvent ( $temp : data ) over window:length(10) from entry-point ep01; " + "      average ($temp)\n" + "  )\n" + "then\n" + "  $s.avgTemp = $avg.intValue();\n" + "  System.out.println( $avg );\n" + "end\n" + "\n";
    final KieBaseConfiguration kbconfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconfig.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBaseFromString(kbconfig, drl);
    final KieSession session = kbase.newKieSession();
    final EntryPoint ep01 = session.getEntryPoint("ep01");
    final Runner t = new Runner(session);
    t.start();
    Thread.sleep(1000);
    final Server hiwaesdk = new Server("hiwaesdk");
    session.insert(hiwaesdk);
    final long LIMIT = 20;
    for (long i = LIMIT; i > 0; i--) {
        // Thread.sleep (0x1); }
        ep01.insert(new IntEvent((int) i));
        if (i % 1000 == 0) {
            System.out.println(i);
        }
    }
    try {
        Thread.sleep(1000);
        System.out.println("Halting ..");
        session.halt();
    } catch (final Exception e) {
        Assertions.fail(e.getMessage());
    }
    if (t.getError() != null) {
        Assertions.fail(t.getError().getMessage());
    }
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) KieBase(org.kie.api.KieBase) EntryPoint(org.kie.api.runtime.rule.EntryPoint) KieSession(org.kie.api.runtime.KieSession) Test(org.junit.Test)

Example 87 with KieBaseConfiguration

use of org.kie.api.KieBaseConfiguration in project drools by kiegroup.

the class MultithreadTest method testSlidingTimeWindows.

@Test(timeout = 1000000)
public void testSlidingTimeWindows() {
    final String str = "package org.drools\n" + "global java.util.List list; \n" + "import " + StockTick.class.getCanonicalName() + "; \n" + "" + "declare StockTick @role(event) end\n" + "" + "rule R\n" + "when\n" + " accumulate( $st : StockTick() over window:time(400ms)\n" + "             from entry-point X,\n" + "             $c : count(1) )" + "then\n" + "   list.add( $c ); \n" + "end \n";
    final List<Exception> errors = new ArrayList<Exception>();
    final KieBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBaseFromString(kbconf, str);
    final KieSession ksession = kbase.newKieSession();
    final EntryPoint ep = ksession.getEntryPoint("X");
    final List list = new ArrayList();
    ksession.setGlobal("list", list);
    final Executor executor = Executors.newCachedThreadPool(new ThreadFactory() {

        public Thread newThread(final Runnable r) {
            final Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    });
    // runs for 10 seconds
    final int RUN_TIME = 5000;
    final int THREAD_NR = 2;
    final CompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(executor);
    ecs.submit(new Callable<Boolean>() {

        public Boolean call() throws Exception {
            try {
                ksession.fireUntilHalt();
                return true;
            } catch (final Exception e) {
                errors.add(e);
                e.printStackTrace();
                return false;
            }
        }
    });
    for (int i = 0; i < THREAD_NR; i++) {
        ecs.submit(new Callable<Boolean>() {

            public Boolean call() throws Exception {
                try {
                    final String s = Thread.currentThread().getName();
                    final long endTS = System.currentTimeMillis() + RUN_TIME;
                    int j = 0;
                    long lastTimeInserted = -1;
                    while (System.currentTimeMillis() < endTS) {
                        final long currentTimeInMillis = System.currentTimeMillis();
                        if (currentTimeInMillis > lastTimeInserted) {
                            lastTimeInserted = currentTimeInMillis;
                            ep.insert(new StockTick(j++, s, 0.0, 0));
                        }
                    }
                    return true;
                } catch (final Exception e) {
                    errors.add(e);
                    e.printStackTrace();
                    return false;
                }
            }
        });
    }
    boolean success = true;
    for (int i = 0; i < THREAD_NR; i++) {
        try {
            success = ecs.take().get() && success;
        } catch (final Exception e) {
            errors.add(e);
        }
    }
    ksession.halt();
    try {
        success = ecs.take().get() && success;
    } catch (final Exception e) {
        errors.add(e);
    }
    for (final Exception e : errors) {
        e.printStackTrace();
    }
    Assertions.assertThat(errors).isEmpty();
    Assertions.assertThat(success).isTrue();
    ksession.dispose();
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) ArrayList(java.util.ArrayList) EntryPoint(org.kie.api.runtime.rule.EntryPoint) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) EntryPoint(org.kie.api.runtime.rule.EntryPoint) KieBaseConfiguration(org.kie.api.KieBaseConfiguration) Executor(java.util.concurrent.Executor) StockTick(org.drools.compiler.StockTick) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 88 with KieBaseConfiguration

use of org.kie.api.KieBaseConfiguration in project drools by kiegroup.

the class PseudoClockEventsTest method processStocks.

private int processStocks(int stockCount, AgendaEventListener agendaEventListener, String drlContentString) throws DroolsParserException, IOException, 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();
    Runnable fireUntilHaltRunnable = new Runnable() {

        public void run() {
            ksession.fireUntilHalt();
        }
    };
    Thread fireUntilHaltThread = new Thread(fireUntilHaltRunnable, "Engine's thread");
    fireUntilHaltThread.start();
    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);
    ksession.halt();
    fireUntilHaltThread.join(5000);
    return stockCount;
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) StockTickInterface(org.drools.compiler.StockTickInterface) StockTick(org.drools.compiler.StockTick) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) PseudoClockScheduler(org.drools.core.time.impl.PseudoClockScheduler)

Example 89 with KieBaseConfiguration

use of org.kie.api.KieBaseConfiguration in project drools by kiegroup.

the class TruthMaintenanceTest method testLogicalWithDeleteException.

@Test(timeout = 10000)
public void testLogicalWithDeleteException() {
    String droolsSource = "package org.drools.tms.test; \n" + "global java.util.List list; \n" + "rule Justify \n" + "when \n" + "    String( this == 'go1' ) " + "then \n" + "    insertLogical( 'f1' ); \n" + "end \n" + "";
    KieBaseConfiguration kieConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieConf.setOption(EqualityBehaviorOption.IDENTITY);
    KieBase kbase = loadKnowledgeBaseFromString(kieConf, droolsSource);
    KieSession session = kbase.newKieSession();
    List list = new ArrayList();
    session.setGlobal("list", list);
    session.insert("go1");
    session.fireAllRules();
    TruthMaintenanceSystem tms = ((StatefulKnowledgeSessionImpl) session).getTruthMaintenanceSystem();
    InternalFactHandle jfh1 = tms.get("f1").getLogicalFactHandle();
    assertSame(jfh1, session.getFactHandle("f1"));
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) TruthMaintenanceSystem(org.drools.core.common.TruthMaintenanceSystem) KieBase(org.kie.api.KieBase) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) InternalFactHandle(org.drools.core.common.InternalFactHandle) Test(org.junit.Test)

Example 90 with KieBaseConfiguration

use of org.kie.api.KieBaseConfiguration in project drools by kiegroup.

the class TruthMaintenanceTest method testUpdate.

@Test(timeout = 10000)
public void testUpdate() {
    String droolsSource = "package org.drools.tms.test; \n" + " declare Feat1\n" + "   context : String @key\n" + "   value : double @key\n" + "   missing : boolean  = false\n" + " \n" + " end\n" + " \n" + " \n" + "rule \"InitAsMissing_Test_MLP_Feat1\"\n" + "when\n" + "    not Feat1( context == null )\n" + "then\n" + "    insertLogical( new Feat1( \"Test_MLP\", 0.0, true ) );\n" + "end\n" + " \n" + "rule \"miningFieldMissing_Test_MLP_Feat1\"\n" + "when\n" + "     $x : Feat1( $m : missing == true, context == \"Test_MLP\" )\n" + "then\n" + "    modify ( $x ) {\n" + "        setValue( 3.95 ),\n" + "        setMissing( false );\n" + "    }\n" + "end\n" + " \n" + "rule \"OverrideInput_Feat1\"\n" + "when\n" + "    $old: Feat1( value != 4.33 )\n" + "then\n" + "    retract( $old );\n" + "end\n" + " \n" + " \n" + "rule \"Input_Feat1\"\n" + "when\n" + "    not Feat1(  context == null )\n" + "then\n" + "    insert( new Feat1( null, 4.33 ) );\n" + "end";
    KieBaseConfiguration kieConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieConf.setOption(EqualityBehaviorOption.IDENTITY);
    KieBase kbase = loadKnowledgeBaseFromString(kieConf, droolsSource);
    KieSession session = kbase.newKieSession();
    List list = new ArrayList();
    try {
        session.fireAllRules();
        fail("Currently we cannot handle updates for a belief set that is mixed stated and justified");
    } catch (ConsequenceException e) {
        assertEquals(IllegalStateException.class, e.getCause().getClass());
    }
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) List(java.util.List) ArrayList(java.util.ArrayList) ConsequenceException(org.kie.api.runtime.rule.ConsequenceException) Test(org.junit.Test)

Aggregations

KieBaseConfiguration (org.kie.api.KieBaseConfiguration)124 Test (org.junit.Test)94 KieSession (org.kie.api.runtime.KieSession)77 KieBase (org.kie.api.KieBase)69 ArrayList (java.util.ArrayList)54 List (java.util.List)38 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)25 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)23 FactHandle (org.kie.api.runtime.rule.FactHandle)21 EntryPoint (org.kie.api.runtime.rule.EntryPoint)18 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)16 StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)16 InternalFactHandle (org.drools.core.common.InternalFactHandle)15 StockTick (org.drools.compiler.StockTick)11 KieContainer (org.kie.api.runtime.KieContainer)11 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)11 Match (org.kie.api.runtime.rule.Match)10 StatelessKieSession (org.kie.api.runtime.StatelessKieSession)9 InternalKnowledgeBase (org.drools.kiesession.rulebase.InternalKnowledgeBase)8 BuildContext (org.drools.core.reteoo.builder.BuildContext)7