Search in sources :

Example 61 with KieSession

use of org.kie.api.runtime.KieSession in project drools by kiegroup.

the class WorkingMemoryLoggerTest method testLogAllBoundVariables.

@Test
public void testLogAllBoundVariables() throws Exception {
    // BZ-1271909
    final String drl = "import " + Message.class.getCanonicalName() + "\n" + "rule \"Hello World\" no-loop\n" + "    when\n" + "        $messageInstance : Message( $myMessage : message )\n" + "    then\n" + "        update($messageInstance);\n" + "end\n";
    final KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession();
    final WorkingMemoryInMemoryLogger logger = new WorkingMemoryInMemoryLogger((WorkingMemory) ksession);
    final Message message = new Message();
    message.setMessage("Hello World");
    ksession.insert(message);
    ksession.fireAllRules();
    for (final LogEvent logEvent : logger.getLogEvents()) {
        if (logEvent instanceof ActivationLogEvent) {
            assertTrue(((ActivationLogEvent) logEvent).getDeclarations().contains("$messageInstance"));
            assertTrue(((ActivationLogEvent) logEvent).getDeclarations().contains("$myMessage"));
        }
    }
}
Also used : WorkingMemoryInMemoryLogger(org.drools.core.audit.WorkingMemoryInMemoryLogger) Message(org.drools.compiler.Message) LogEvent(org.drools.core.audit.event.LogEvent) ActivationLogEvent(org.drools.core.audit.event.ActivationLogEvent) KieHelper(org.kie.internal.utils.KieHelper) KieSession(org.kie.api.runtime.KieSession) ActivationLogEvent(org.drools.core.audit.event.ActivationLogEvent) Test(org.junit.Test)

Example 62 with KieSession

use of org.kie.api.runtime.KieSession in project drools by kiegroup.

the class MultithreadTest method testConcurrentFireAndDispose.

@Test(timeout = 10000)
public void testConcurrentFireAndDispose() throws InterruptedException {
    // DROOLS-1103
    final String drl = "rule R no-loop timer( int: 1s )\n" + "when\n" + "    String()\n" + "then\n" + "end";
    final KieHelper helper = new KieHelper();
    helper.addContent(drl, ResourceType.DRL);
    final KieBase kbase = helper.build(EventProcessingOption.STREAM);
    final KieSessionConfiguration ksconf = KieServices.Factory.get().newKieSessionConfiguration();
    ksconf.setOption(TimedRuleExecutionOption.YES);
    final KieSession ksession = kbase.newKieSession(ksconf, null);
    final Thread t1 = new Thread() {

        @Override
        public void run() {
            LOG.info("before: sleep, dispose().");
            try {
                Thread.sleep(100);
            } catch (final InterruptedException _e) {
            }
            LOG.info("before: dispose().");
            ksession.dispose();
            LOG.info("after: dispose().");
        }
    };
    t1.setDaemon(true);
    t1.start();
    try {
        int i = 0;
        LOG.info("before: while.");
        while (true) {
            ksession.insert("" + i++);
            ksession.fireAllRules();
        }
    } catch (final IllegalStateException e) {
        // java.lang.IllegalStateException: Illegal method call. This session was previously disposed.
        // ignore and exit
        LOG.info("after: while.");
    } catch (final java.util.concurrent.RejectedExecutionException e) {
        e.printStackTrace();
        Assertions.fail("java.util.concurrent.RejectedExecutionException should not happen");
    }
    LOG.info("last line of test.");
}
Also used : KieBase(org.kie.api.KieBase) KieHelper(org.kie.internal.utils.KieHelper) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) EntryPoint(org.kie.api.runtime.rule.EntryPoint) Test(org.junit.Test)

Example 63 with KieSession

use of org.kie.api.runtime.KieSession in project drools by kiegroup.

the class MultithreadTest method testClassLoaderRace.

@Test(timeout = 10000)
public void testClassLoaderRace() throws InterruptedException {
    final String drl = "package org.drools.integrationtests;\n" + "" + "rule \"average temperature\"\n" + "when\n" + " $avg := Number( ) from accumulate ( " + "      $x : Integer ( ); " + "      average ($x) )\n" + "then\n" + "  System.out.println( $avg );\n" + "end\n" + "\n";
    final KieBase kbase = loadKnowledgeBaseFromString(drl);
    final KieSession session = kbase.newKieSession();
    final Thread t = new Thread() {

        public void run() {
            session.fireUntilHalt();
        }
    };
    t.start();
    session.fireAllRules();
    for (int j = 0; j < 100; j++) {
        session.insert(j);
    }
    try {
        Thread.sleep(1000);
        System.out.println("Halting ..");
        session.halt();
    } catch (final Exception e) {
        Assertions.fail(e.getMessage());
    }
}
Also used : KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) EntryPoint(org.kie.api.runtime.rule.EntryPoint) Test(org.junit.Test)

Example 64 with KieSession

use of org.kie.api.runtime.KieSession in project drools by kiegroup.

the class MultithreadTest method testConcurrentQueries.

@Test(timeout = 5000)
public void testConcurrentQueries() {
    // DROOLS-175
    final StringBuilder drl = new StringBuilder();
    drl.append("package org.drools.test;\n" + "" + "query foo( ) \n" + "   Object() from new Object() \n" + "end\n" + "" + "rule XYZ when then end \n");
    final KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.toString().getBytes()), ResourceType.DRL);
    final InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(knowledgeBuilder.getKnowledgePackages());
    final KieSession ksession = kbase.newKieSession();
    final Executor executor = Executors.newCachedThreadPool(new ThreadFactory() {

        public Thread newThread(final Runnable r) {
            final Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        }
    });
    final int THREAD_NR = 5;
    final CompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(executor);
    for (int i = 0; i < THREAD_NR; i++) {
        ecs.submit(new Callable<Boolean>() {

            public Boolean call() throws Exception {
                boolean succ = false;
                try {
                    final QueryResults res = ksession.getQueryResults("foo", Variable.v);
                    succ = (res.size() == 1);
                    return succ;
                } catch (final Exception e) {
                    e.printStackTrace();
                    return succ;
                }
            }
        });
    }
    boolean success = true;
    for (int i = 0; i < THREAD_NR; i++) {
        try {
            success = ecs.take().get() && success;
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }
    Assertions.assertThat(success).isTrue();
    ksession.dispose();
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) EntryPoint(org.kie.api.runtime.rule.EntryPoint) QueryResults(org.kie.api.runtime.rule.QueryResults) KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) Executor(java.util.concurrent.Executor) KieSession(org.kie.api.runtime.KieSession) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 65 with KieSession

use of org.kie.api.runtime.KieSession in project drools by kiegroup.

the class MultithreadTest method testConcurrencyWithChronThreads.

@Test
@Ignore
public void testConcurrencyWithChronThreads() throws InterruptedException {
    final String drl = "package it.intext.drools.fusion.bug;\n" + "\n" + "import " + MyFact.class.getCanonicalName() + ";\n " + " global java.util.List list; \n" + "\n" + "declare MyFact\n" + "\t@role( event )\n" + "\t@expires( 1s )\n" + "end\n" + "\n" + "rule \"Dummy\"\n" + "timer( cron: 0/1 * * * * ? )\n" + "when\n" + "  Number( $count : intValue ) from accumulate( MyFact( ) over window:time(1s); sum(1) )\n" + "then\n" + "    System.out.println($count+\" myfact(s) seen in the last 1 seconds\");\n" + "    list.add( $count ); \n" + "end";
    final KieBaseConfiguration kbconfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconfig.setOption(EventProcessingOption.STREAM);
    final KieBase kbase = loadKnowledgeBaseFromString(kbconfig, drl);
    final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get("REALTIME"));
    final KieSession ksession = kbase.newKieSession(conf, null);
    final List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.fireAllRules();
    final Runner t = new Runner(ksession);
    t.start();
    final int FACTS_PER_POLL = 1000;
    final int POLL_INTERVAL = 500;
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new Runnable() {

        public void run() {
            for (int j = 0; j < FACTS_PER_POLL; j++) {
                ksession.insert(new MyFact());
            }
        }
    }, 0, POLL_INTERVAL, TimeUnit.MILLISECONDS);
    Thread.sleep(10200);
    executor.shutdownNow();
    ksession.halt();
    t.join();
    if (t.getError() != null) {
        Assertions.fail(t.getError().getMessage());
    }
    System.out.println("Final size " + ksession.getObjects().size());
    // assertEquals( 2000, ksession.getObjects().size() );
    ksession.dispose();
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) KieBase(org.kie.api.KieBase) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) EntryPoint(org.kie.api.runtime.rule.EntryPoint) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

KieSession (org.kie.api.runtime.KieSession)5328 Test (org.junit.Test)4824 KieBase (org.kie.api.KieBase)2414 ArrayList (java.util.ArrayList)2317 List (java.util.List)1105 StatelessKieSession (org.kie.api.runtime.StatelessKieSession)769 FactHandle (org.kie.api.runtime.rule.FactHandle)598 Person (org.drools.modelcompiler.domain.Person)519 HashMap (java.util.HashMap)416 ProcessInstance (org.kie.api.runtime.process.ProcessInstance)415 KieServices (org.kie.api.KieServices)382 KieHelper (org.kie.internal.utils.KieHelper)355 KieContainer (org.kie.api.runtime.KieContainer)298 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)265 InternalFactHandle (org.drools.core.common.InternalFactHandle)259 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)234 AbstractBaseTest (org.jbpm.test.util.AbstractBaseTest)234 ReleaseId (org.kie.api.builder.ReleaseId)232 KieSessionConfiguration (org.kie.api.runtime.KieSessionConfiguration)229 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)207