Java Code Examples for org.kie.api.runtime.KieSession#halt()
The following examples show how to use
org.kie.api.runtime.KieSession#halt() .
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: TimerTest.java From fw-spring-cloud with Apache License 2.0 | 6 votes |
/** * 测试规则的触发 */ @Test public void testRule() throws InterruptedException { KieSession kieSession = kieBase.newKieSession(); new Thread(new Runnable() { public void run() { //启动规则引擎进行规则匹配,直到调用halt方法才结束规则引擎 kieSession.fireUntilHalt(); } }).start(); Thread.sleep(20000); //结束规则引擎 kieSession.halt(); kieSession.dispose(); }
Example 2
Source File: FireUntilHaltTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testFireAllWhenFiringUntilHalt() throws InterruptedException { final KieBase kbase = getKnowledgeBase(); final KieSession ksession = createKnowledgeSession(kbase); final Thread t1 = new Thread(ksession::fireUntilHalt); final Thread t2 = new Thread(ksession::fireAllRules); t1.start(); Thread.sleep(500); t2.start(); // give the chance for t2 to finish Thread.sleep(1000); final boolean aliveT2 = t2.isAlive(); ksession.halt(); Thread.sleep(1000); final boolean aliveT1 = t1.isAlive(); if (t2.isAlive()) { t2.interrupt(); } if (t1.isAlive()) { t1.interrupt(); } assertFalse(aliveT2, "T2 should have finished"); assertFalse(aliveT1, "T1 should have finished"); }
Example 3
Source File: MultithreadTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test 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(session::fireUntilHalt); t.start(); try { session.fireAllRules(); for (int j = 0; j < 100; j++) { session.insert(j); } Thread.sleep(1000); } finally { session.halt(); session.dispose(); } }
Example 4
Source File: PseudoClockEventsTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
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 5
Source File: FireUntilHaltTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testFireUntilHaltFailingAcrossEntryPoints() throws Exception { String rule1 = "package org.drools.compiler\n"; rule1 += "global java.util.List list\n"; rule1 += "rule testFireUntilHalt\n"; rule1 += "when\n"; rule1 += " Cheese()\n"; rule1 += " $p : Person() from entry-point \"testep2\"\n"; rule1 += "then \n"; rule1 += " list.add( $p ) ;\n"; rule1 += "end\n"; final KieBase kbase = loadKnowledgeBaseFromString(rule1); final KieSession ksession = createKnowledgeSession(kbase); final EntryPoint ep = ksession.getEntryPoint("testep2"); final List list = new ArrayList(); ksession.setGlobal("list", list); ksession.insert(new Cheese("cheddar")); ksession.fireAllRules(); final Thread t1 = new Thread(ksession::fireUntilHalt); t1.start(); Thread.sleep(500); ep.insert(new Person("darth")); Thread.sleep(500); ksession.halt(); t1.join(5000); final boolean alive = t1.isAlive(); if (alive) { t1.interrupt(); } assertFalse(alive, "Thread should have died!"); assertEquals(1, list.size()); }
Example 6
Source File: ParallelEvaluationTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private Callable<Void> getMultipleParallelKieSessionsFireUntilHaltCallable(KieBase kBase, boolean asyncInsert) { return () -> { KieSession ksession = kBase.newKieSession(); assertThat(((InternalWorkingMemory) ksession).getAgenda().isParallelAgenda()).isTrue(); CountDownLatch done = new CountDownLatch(1); DebugList<Integer> list = new DebugList<Integer>(); list.onItemAdded = (l -> { if (l.size() == 10) { ksession.halt(); done.countDown(); } }); ksession.setGlobal("list", list); new Thread(ksession::fireUntilHalt).start(); if (asyncInsert) { StatefulKnowledgeSessionImpl session = (StatefulKnowledgeSessionImpl) ksession; for (int i = 0; i < 10; i++) { session.insertAsync(i); session.insertAsync("" + String.valueOf(i)); } } else { insertFacts(ksession, 10); } try { done.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } assertThat(list.size()).isEqualTo(10); return null; }; }
Example 7
Source File: ParallelEvaluationTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testFireUntilHaltWithAsyncInsert() { StringBuilder sb = new StringBuilder( 400 ); sb.append( "global java.util.List list;\n" ); for (int i = 0; i < 10; i++) { sb.append( getRule( i, "" ) ); } KieSession ksession = new KieHelper().addContent( sb.toString(), ResourceType.DRL ) .build( MultithreadEvaluationOption.YES ) .newKieSession(); assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() ); StatefulKnowledgeSessionImpl session = (StatefulKnowledgeSessionImpl) ksession; CountDownLatch done = new CountDownLatch(1); DebugList<Integer> list = new DebugList<Integer>(); list.onItemAdded = ( l -> { if (l.size() == 10) { ksession.halt(); done.countDown(); }} ); ksession.setGlobal( "list", list ); new Thread(ksession::fireUntilHalt).start(); try { for (int i = 0; i < 10; i++) { session.insertAsync( i ); session.insertAsync( "" + i ); } try { done.await(); } catch (InterruptedException e) { throw new RuntimeException( e ); } assertEquals(10, list.size()); } finally { ksession.halt(); ksession.dispose(); } }
Example 8
Source File: ParallelEvaluationTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testFireUntilHaltWithExpiration2() throws InterruptedException { 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" + "global java.util.concurrent.CountDownLatch fireLatch;\n" + "rule R0 when\n" + " $A: A( $Aid : value > 0 )\n" + " $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" + "then\n" + " counter.incrementAndGet();\n" + " fireLatch.countDown();" + "end\n" + "rule R1 when\n" + " $A: A( $Aid: value > 1 )\n" + " $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" + "then\n" + " counter.incrementAndGet();\n" + " fireLatch.countDown();" + "end\n" + "rule R2 when\n" + " $A: A( $Aid: value > 2 )\n" + " $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" + "then\n" + " counter.incrementAndGet();\n" + " fireLatch.countDown();" + "end\n" + "rule R3 when\n" + " $A: A( $Aid: value > 3 )\n" + " $B: B( ($Bid: value <= $Aid) && (value > ($Aid - 1 )))\n" + "then\n" + " counter.incrementAndGet();\n" + " fireLatch.countDown();" + "end"; KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sessionConfig.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL ) .build( EventProcessingOption.STREAM, MultithreadEvaluationOption.YES ) .newKieSession( sessionConfig, null ); try { assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() ); PseudoClockScheduler sessionClock = ksession.getSessionClock(); sessionClock.setStartupTime( 0 ); AtomicInteger counter = new AtomicInteger( 0 ); ksession.setGlobal( "counter", counter ); new Thread( () -> ksession.fireUntilHalt() ).start(); int eventsNr = 5; final CountDownLatch fireLatch = new CountDownLatch(eventsNr * 4); ksession.setGlobal("fireLatch", fireLatch); for ( int i = 0; i < eventsNr; i++ ) { ksession.insert( new A( i + 4 ) ); ksession.insert( new B( i + 4 ) ); sessionClock.advanceTime( 10, TimeUnit.MILLISECONDS ); } fireLatch.await(); assertEquals( eventsNr * 4, counter.get() ); } finally { ksession.halt(); ksession.dispose(); } }
Example 9
Source File: ParallelEvaluationTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testFireUntilHalt2() { int rulesNr = 4; int factsNr = 1; int fireNr = rulesNr * factsNr; String drl = "import " + A.class.getCanonicalName() + ";\n" + "import " + B.class.getCanonicalName() + ";\n" + "global java.util.concurrent.atomic.AtomicInteger counter\n" + "global java.util.concurrent.CountDownLatch done\n" + "global java.util.List list;\n"; for (int i = 0; i < rulesNr; i++) { drl += getFireUntilHaltRule(fireNr, i); } KieBase kbase = new KieHelper().addContent( drl, ResourceType.DRL ) .build( MultithreadEvaluationOption.YES ); for (int loop = 0; loop < 10; loop++) { System.out.println("Starting loop " + loop); KieSession ksession = kbase.newKieSession(); assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() ); CountDownLatch done = new CountDownLatch( 1 ); ksession.setGlobal( "done", done ); AtomicInteger counter = new AtomicInteger( 0 ); ksession.setGlobal( "counter", counter ); List<String> list = new DebugList<String>(); ksession.setGlobal( "list", list ); new Thread(ksession::fireUntilHalt).start(); try { A a = new A( rulesNr + 1 ); ksession.insert( a ); for ( int i = 0; i < factsNr; i++ ) { ksession.insert( new B( rulesNr + i + 3 ) ); } try { done.await(); } catch (InterruptedException e) { throw new RuntimeException( e ); } assertEquals( fireNr, counter.get() ); } finally { ksession.halt(); ksession.dispose(); } System.out.println("Loop " + loop + " terminated"); } }
Example 10
Source File: PhreakConcurrencyTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testMultipleConcurrentEPs4() { final KieSession ksession = getKieSessionWith3Segments(); List<String> results = new ArrayList<>(); ksession.setGlobal("results", results); EPManipulator4[] epManipulators = new EPManipulator4[9]; CyclicBarrier barrier = new CyclicBarrier(9, new SegmentChecker(epManipulators)); for (int i = 0; i < 9; i++) { epManipulators[i] = new EPManipulator4(ksession, i+1, barrier); } new Thread(ksession::fireUntilHalt).start(); try { for (int deleteIndex = 0; deleteIndex < 11; deleteIndex++) { boolean success = true; final ExecutorService executor = Executors.newFixedThreadPool(9, r -> { Thread t = new Thread(r); t.setDaemon(true); return t; }); try { CompletionService<Boolean> ecs = new ExecutorCompletionService<>(executor); for (int i = 0; i < 9; i++) { ecs.submit(epManipulators[i].setDeleteIndex(deleteIndex % 10)); } for (int i = 0; i < 9; i++) { try { success = ecs.take().get() && success; } catch (Exception e) { throw new RuntimeException(e); } } assertTrue(success); } finally { executor.shutdownNow(); } } } finally { ksession.halt(); ksession.dispose(); } }
Example 11
Source File: PhreakConcurrencyTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
public void doFactLeak() throws InterruptedException { //DROOLS-131 String drl = "package org.drools.test; \n" + "global " + ConcurrentLinkedQueue.class.getCanonicalName() + " list; \n" + //"global " + AtomicInteger.class.getCanonicalName() + "counter; \n" + "" + "rule Intx when\n" + " $x : Integer() from entry-point \"x\" \n" + "then\n" + " list.add( $x );" + "end"; int N = 1100; KieBase kb = loadKnowledgeBaseFromString( drl ); final KieSession ks = kb.newKieSession(); ConcurrentLinkedQueue list = new ConcurrentLinkedQueue<Integer>(); AtomicInteger counter = new AtomicInteger(0); ks.setGlobal( "list", list ); //ks.setGlobal( "counter", counter ); new Thread(ks::fireUntilHalt).start(); try { for ( int j = 0; j < N; j++ ) { ks.getEntryPoint( "x" ).insert( new Integer( j ) ); } int count = 0; while ( list.size() != N && count++ != 1000) { Thread.sleep( 200 ); } } finally { ks.halt(); if ( list.size() != N ) { for ( int j = 0; j < N; j++ ) { if ( !list.contains( new Integer( j ) ) ) { System.out.println( "missed: " + j ); } } } assertEquals( N, list.size() ); ks.dispose(); } }
Example 12
Source File: FireUntilHaltTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testSubmitOnFireUntilHalt() throws InterruptedException { final String drl = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list;" + "rule R when\n" + " Person( happy, age >= 18 )\n" + "then\n" + " list.add(\"happy adult\");" + "end"; final KieSession kSession = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession(); final List<String> list = new ArrayList<>(); kSession.setGlobal("list", list); new Thread(kSession::fireUntilHalt).start(); final Person p = new Person("me", 17, true); final FactHandle fh = kSession.insert(p); Thread.sleep(100L); assertEquals(0, list.size()); kSession.submit(kieSession -> { p.setAge(18); p.setHappy(false); kieSession.update(fh, p); }); Thread.sleep(100L); assertEquals(0, list.size()); kSession.submit(kieSession -> { p.setHappy(true); kieSession.update(fh, p); }); Thread.sleep(100L); assertEquals(1, list.size()); kSession.halt(); kSession.dispose(); }
Example 13
Source File: ParallelEvaluationTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test public void testFireUntilHalt() { StringBuilder sb = new StringBuilder( 400 ); sb.append( "global java.util.List list;\n" ); for (int i = 0; i < 10; i++) { sb.append( getRule( i, "" ) ); } KieSession ksession = new KieHelper().addContent( sb.toString(), ResourceType.DRL ) .build( MultithreadEvaluationOption.YES ) .newKieSession(); assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() ); CountDownLatch done = new CountDownLatch(1); DebugList<Integer> list = new DebugList<Integer>(); list.onItemAdded = ( l -> { if (l.size() == 10) { ksession.halt(); done.countDown(); }} ); ksession.setGlobal( "list", list ); new Thread(ksession::fireUntilHalt).start(); try { for (int i = 0; i < 10; i++) { ksession.insert( i ); ksession.insert( "" + i ); } try { done.await(); } catch (InterruptedException e) { throw new RuntimeException( e ); } assertEquals(10, list.size()); } finally { ksession.halt(); ksession.dispose(); } }
Example 14
Source File: MultithreadTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test @Disabled 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(); try { final int FACTS_PER_POLL = 1000; final int POLL_INTERVAL = 500; final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try { executor.scheduleAtFixedRate( () -> { for (int j = 0; j < FACTS_PER_POLL; j++) { ksession.insert(new MyFact()); } }, 0, POLL_INTERVAL, TimeUnit.MILLISECONDS); Thread.sleep(10200); } finally { executor.shutdownNow(); } } finally { ksession.halt(); ksession.dispose(); } t.join(); if (t.getError() != null) { Assertions.fail(t.getError().getMessage()); } System.out.println("Final size " + ksession.getObjects().size()); ksession.dispose(); }
Example 15
Source File: MultithreadTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test 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(); try { Thread.sleep(1000); final Server hiwaesdk = new Server("hiwaesdk"); session.insert(hiwaesdk); final long LIMIT = 20; for (long i = LIMIT; i > 0; i--) { ep01.insert(new IntEvent((int) i)); //Thread.sleep (0x1); } if (i % 1000 == 0) { System.out.println(i); } } Thread.sleep(1000); } finally { session.halt(); session.dispose(); } if (t.getError() != null) { Assertions.fail(t.getError().getMessage()); } }
Example 16
Source File: HaltCommand.java From kogito-runtimes with Apache License 2.0 | 4 votes |
public Void execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup( KieSession.class ); ksession.halt(); return null; }
Example 17
Source File: ProcessMarshallingTest.java From kogito-runtimes with Apache License 2.0 | 4 votes |
@Test @Disabled public void testMarshallingProcessInstanceWithTimer() throws Exception { String process = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" + " type=\"RuleFlow\" name=\"ruleflow\" id=\"com.sample.ruleflow\" package-name=\"com.sample\" >\n" + "\n" + " <header>\n" + " </header>\n" + "\n" + " <nodes>\n" + " <start id=\"1\" name=\"Start\" />\n" + " <timerNode id=\"4\" name=\"Timer\" delay=\"200\" />\n" + " <end id=\"3\" name=\"End\" />\n" + " </nodes>\n" + "\n" + " <connections>\n" + " <connection from=\"1\" to=\"4\" />\n" + " <connection from=\"4\" to=\"3\" />\n" + " </connections>\n" + "\n" + "</process>\n"; builder.addProcessFromXml( new StringReader( process )); final KieSession session = createKieSession(builder.getPackages()); session.startProcess("com.sample.ruleflow", null); assertEquals(1, session.getProcessInstances().size()); session.halt(); final StatefulKnowledgeSession session2 = getSerialisedStatefulKnowledgeSession(session); int sleeps = 3; int procInstsAlive = session2.getProcessInstances().size(); while( procInstsAlive > 0 && sleeps > 0 ) { Thread.sleep(1000); --sleeps; procInstsAlive = session2.getProcessInstances().size(); } assertEquals(0, session2.getProcessInstances().size()); session2.halt(); }