@Test(timeout = 10000) public void testCalendarsWithIntervalsAndStartAndLimit() throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; str += "rule xxx \n"; str += " calendars \"cal1\"\n"; str += " timer (0d 1d start=3-JAN-2010 repeat-limit=4) "; // int: protocol is assumed str += "when \n"; str += "then \n"; str += " list.add(\"fired\"); \n"; str += "end \n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.UK); Date date = df.parse("1-JAN-2010"); Calendar cal1 = new Calendar() { public boolean isTimeIncluded(long timestamp) { return true; } }; long oneDay = 60 * 60 * 24; ksession.getCalendars().set("cal1", cal1); ksession.setGlobal("list", list); timeService.advanceTime(date.getTime(), TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); // day 3 ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); // day 5 ksession.fireAllRules(); assertEquals(3, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(3, list.size()); }
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; }
@Test(timeout = 10000) public void testIntervalTimer() throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; str += "rule xxx \n"; str += " timer (int:30s 10s) "; str += "when \n"; str += "then \n"; str += " list.add(\"fired\"); \n"; str += "end \n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); timeService.advanceTime(new Date().getTime(), TimeUnit.MILLISECONDS); ksession.setGlobal("list", list); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(20, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(15, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(3, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(2, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); timeService.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(3, list.size()); }
@Test(timeout = 10000) public void testCronTimer() throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; str += "rule xxx \n"; str += " timer (cron:15 * * * * ?) "; str += "when \n"; str += "then \n"; str += " list.add(\"fired\"); \n"; str += "end \n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Date date = df.parse("2009-01-01T00:00:00.000-0000"); timeService.advanceTime(date.getTime(), TimeUnit.MILLISECONDS); ksession.setGlobal("list", list); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(30, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(30, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); }
protected KieFileSystem createKieFileSystemWithKProject(KieServices ks) { KieModuleModel kproj = ks.newKieModuleModel(); KieBaseModel kieBaseModel1 = kproj .newKieBaseModel("defaultKieBase") .setDefault(true) .addPackage("*") .setEqualsBehavior(EqualityBehaviorOption.EQUALITY) .setEventProcessingMode(EventProcessingOption.STREAM); kieBaseModel1 .newKieSessionModel("defaultKieSession") .setDefault(true) .setType(KieSessionModel.KieSessionType.STATEFUL) .setClockType(ClockTypeOption.get("realtime")) .newWorkItemHandlerModel( "Log", "new org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler()"); KieFileSystem kfs = ks.newKieFileSystem(); kfs.writeKModuleXML(kproj.toXML()); return kfs; }
@Test(timeout = 10000) public void testDurationMemoryLeakonRepeatedUpdate() throws Exception { String str = ""; str += "package org.drools.compiler.test\n"; str += "import org.drools.compiler.Alarm\n"; str += "global java.util.List list;"; str += "rule \"COMPTEUR\"\n"; str += " timer 50\n"; str += " when\n"; str += " $alarm : Alarm( number < 5 )\n"; str += " then\n"; str += " $alarm.incrementNumber();\n"; str += " list.add( $alarm );\n"; str += " update($alarm);\n"; str += "end\n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); timeService.advanceTime(new Date().getTime(), TimeUnit.MILLISECONDS); List list = new ArrayList(); ksession.setGlobal("list", list); ksession.insert(new Alarm()); ksession.fireAllRules(); for (int i = 0; i < 6; i++) { timeService.advanceTime(55, TimeUnit.MILLISECONDS); ksession.fireAllRules(); } assertEquals(5, list.size()); }
private void addKieSessionModels( ConfigurableListableBeanFactory beanFactory, KieBaseModelImpl kBase) { for (String beanDef : beanFactory.getBeanDefinitionNames()) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDef); if (beanDefinition.getBeanClassName().equalsIgnoreCase(KSessionFactoryBean.class.getName())) { String kBaseName = getPropertyValue(beanDefinition, "kBaseName"); if (kBase.getName().equalsIgnoreCase(kBaseName)) { String name = getPropertyValue(beanDefinition, "name"); String type = getPropertyValue(beanDefinition, "type"); KieSessionModelImpl kSession = new KieSessionModelImpl(kBase, name); kSession.setType( !type.isEmpty() ? KieSessionModel.KieSessionType.valueOf(type.toUpperCase()) : KieSessionModel.KieSessionType.STATEFUL); Map<String, KieSessionModel> rawKieSessionModels = kBase.getRawKieSessionModels(); rawKieSessionModels.put(kSession.getName(), kSession); beanDefinition .getPropertyValues() .addPropertyValue(new PropertyValue("releaseId", releaseId)); kSession.setDefault("true".equals(getPropertyValue(beanDefinition, "def"))); String clockType = getPropertyValue(beanDefinition, "clockType"); if (!clockType.isEmpty()) { kSession.setClockType(ClockTypeOption.get(clockType)); } String scope = getPropertyValue(beanDefinition, "scope"); if (!scope.isEmpty()) { kSession.setScope(scope.trim()); } } } } }
@Test public void testEventTimestamp() { // DROOLS-268 String drl = "\n" + "import org.drools.reteoo.integrationtests.CepEspTest.Event; \n" + "global java.util.List list; \n" + "global org.drools.core.time.SessionPseudoClock clock; \n" + "" + "declare Event \n" + " @role( event )\n" + " @timestamp( time ) \n" + " @expires( 10000000 ) \n" + "end \n" + "" + "" + "rule \"inform about E1\"\n" + "when\n" + " $event1 : Event( type == 1 )\n" + " //there is an event (T2) with value 0 between 0,2m after doorClosed\n" + " $event2: Event( type == 2, value == 1, this after [0, 1200ms] $event1, $timestamp : time )\n" + " //there is no newer event (T2) within the timeframe\n" + " not Event( type == 2, this after [0, 1200ms] $event1, time > $timestamp ) \n" + "then\n" + " list.add( clock.getCurrentTime() ); \n " + "end\n" + "\n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { fail(kbuilder.getErrors().toString()); } KieBaseConfiguration baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); baseConfig.setOption(EventProcessingOption.STREAM); baseConfig.setOption(RuleEngineOption.RETEOO); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); sessionConfig.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId())); // init stateful knowledge session StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(sessionConfig, null); ArrayList list = new ArrayList(); ksession.setGlobal("list", list); SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); ksession.setGlobal("clock", clock); ksession.insert(new Event(1, -1, clock.getCurrentTime())); // 0 clock.advanceTime(600, TimeUnit.MILLISECONDS); ksession.fireAllRules(); ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 600 clock.advanceTime(100, TimeUnit.MILLISECONDS); ksession.fireAllRules(); ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 700 clock.advanceTime(300, TimeUnit.MILLISECONDS); ksession.fireAllRules(); ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 1000 clock.advanceTime(100, TimeUnit.MILLISECONDS); ksession.fireAllRules(); ksession.insert(new Event(2, 1, clock.getCurrentTime())); // 1100 clock.advanceTime(100, TimeUnit.MILLISECONDS); ksession.fireAllRules(); clock.advanceTime(100, TimeUnit.MILLISECONDS); ksession.fireAllRules(); ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 1300 clock.advanceTime(1000, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertFalse(list.isEmpty()); assertEquals(1, list.size()); Long time = (Long) list.get(0); assertTrue(time > 1000 && time < 1500); ksession.dispose(); }
public class KieSessionModelImpl implements KieSessionModel { private String name; private KieSessionType type = KieSessionType.STATEFUL; private ClockTypeOption clockType = ClockTypeOption.get("realtime"); private BeliefSystemTypeOption beliefSystem = BeliefSystemTypeOption.get(BeliefSystemType.SIMPLE.toString()); private String scope; private KieBaseModelImpl kBase; private final List<ListenerModel> listeners = new ArrayList<ListenerModel>(); private final List<WorkItemHandlerModel> wihs = new ArrayList<WorkItemHandlerModel>(); private boolean isDefault = false; private String consoleLogger; private FileLoggerModel fileLogger; private KieSessionModelImpl() {} public KieSessionModelImpl(KieBaseModelImpl kBase, String name) { this.kBase = kBase; this.name = name; } public KieBaseModelImpl getKieBaseModel() { return kBase; } public boolean isDefault() { return isDefault; } public void setKBase(KieBaseModel kieBaseModel) { this.kBase = (KieBaseModelImpl) kieBaseModel; } public KieSessionModel setDefault(boolean isDefault) { this.isDefault = isDefault; return this; } /* (non-Javadoc) * @see org.kie.kproject.KieSessionModel#getName() */ public String getName() { return name; } public KieSessionModel setName(String name) { kBase.changeKSessionName(this, this.name, name); this.name = name; return this; } /* (non-Javadoc) * @see org.kie.kproject.KieSessionModel#getType() */ public KieSessionType getType() { return type; } /* (non-Javadoc) * @see org.kie.kproject.KieSessionModel#setType(java.lang.String) */ public KieSessionModel setType(KieSessionType type) { this.type = type; return this; } /* (non-Javadoc) * @see org.kie.kproject.KieSessionModel#getClockType() */ public ClockTypeOption getClockType() { return clockType; } /* (non-Javadoc) * @see org.kie.kproject.KieSessionModel#setClockType(org.kie.api.runtime.conf.ClockTypeOption) */ public KieSessionModel setClockType(ClockTypeOption clockType) { this.clockType = clockType; return this; } public BeliefSystemTypeOption getBeliefSystem() { return beliefSystem; } public KieSessionModel setBeliefSystem(BeliefSystemTypeOption beliefSystem) { this.beliefSystem = beliefSystem; return this; } @Override public KieSessionModel setScope(String scope) { this.scope = scope; return this; } @Override public String getScope() { return this.scope; } public ListenerModel newListenerModel(String type, ListenerModel.Kind kind) { ListenerModelImpl listenerModel = new ListenerModelImpl(this, type, kind); listeners.add(listenerModel); return listenerModel; } public List<ListenerModel> getListenerModels() { return listeners; } private List<ListenerModel> getListenerModels(ListenerModel.Kind kind) { List<ListenerModel> listeners = new ArrayList<ListenerModel>(); for (ListenerModel listener : getListenerModels()) { if (listener.getKind() == kind) { listeners.add(listener); } } return listeners; } private void addListenerModel(ListenerModel listener) { listeners.add(listener); } public WorkItemHandlerModel newWorkItemHandlerModel(String name, String type) { WorkItemHandlerModelImpl wihModel = new WorkItemHandlerModelImpl(this, name, type); wihs.add(wihModel); return wihModel; } public List<WorkItemHandlerModel> getWorkItemHandlerModels() { return wihs; } private void addWorkItemHandelerModel(WorkItemHandlerModel wih) { wihs.add(wih); } public String getConsoleLogger() { return consoleLogger; } public KieSessionModel setConsoleLogger(String consoleLogger) { this.consoleLogger = consoleLogger; return this; } public FileLoggerModel getFileLogger() { return fileLogger; } public KieSessionModel setFileLogger(String fileName) { this.fileLogger = new FileLoggerModelImpl(fileName); return this; } public KieSessionModel setFileLogger(String fileName, int interval, boolean threaded) { this.fileLogger = new FileLoggerModelImpl(fileName, interval, threaded); return this; } @Override public String toString() { return "KieSessionModel [name=" + name + ", clockType=" + clockType + "]"; } public static class KSessionConverter extends AbstractXStreamConverter { public KSessionConverter() { super(KieSessionModelImpl.class); } public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { KieSessionModelImpl kSession = (KieSessionModelImpl) value; writer.addAttribute("name", kSession.getName()); writer.addAttribute("type", kSession.getType().toString().toLowerCase()); writer.addAttribute("default", Boolean.toString(kSession.isDefault())); if (kSession.getClockType() != null) { writer.addAttribute("clockType", kSession.getClockType().getClockType()); } if (kSession.getBeliefSystem() != null) { writer.addAttribute( "beliefSystem", kSession.getBeliefSystem().getBeliefSystemType().toLowerCase()); } if (kSession.getScope() != null) { writer.addAttribute("scope", kSession.getScope()); } if (kSession.getConsoleLogger() != null) { writer.startNode("consoleLogger"); if (kSession.getConsoleLogger().length() > 0) { writer.addAttribute("name", kSession.getConsoleLogger()); } writer.endNode(); } if (kSession.getFileLogger() != null) { writer.startNode("fileLogger"); writer.addAttribute("file", kSession.getFileLogger().getFile()); writer.addAttribute("threaded", "" + kSession.getFileLogger().isThreaded()); writer.addAttribute("interval", "" + kSession.getFileLogger().getInterval()); writer.endNode(); } writeObjectList( writer, context, "workItemHandlers", "workItemHandler", kSession.getWorkItemHandlerModels()); if (!kSession.getListenerModels().isEmpty()) { writer.startNode("listeners"); for (ListenerModel listener : kSession.getListenerModels(ListenerModel.Kind.RULE_RUNTIME_EVENT_LISTENER)) { writeObject(writer, context, listener.getKind().toString(), listener); } for (ListenerModel listener : kSession.getListenerModels(ListenerModel.Kind.AGENDA_EVENT_LISTENER)) { writeObject(writer, context, listener.getKind().toString(), listener); } for (ListenerModel listener : kSession.getListenerModels(ListenerModel.Kind.PROCESS_EVENT_LISTENER)) { writeObject(writer, context, listener.getKind().toString(), listener); } writer.endNode(); } } public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { final KieSessionModelImpl kSession = new KieSessionModelImpl(); kSession.name = reader.getAttribute("name"); kSession.setDefault("true".equals(reader.getAttribute("default"))); String kSessionType = reader.getAttribute("type"); kSession.setType( kSessionType != null ? KieSessionType.valueOf(kSessionType.toUpperCase()) : KieSessionType.STATEFUL); String clockType = reader.getAttribute("clockType"); if (clockType != null) { kSession.setClockType(ClockTypeOption.get(clockType)); } String beliefSystem = reader.getAttribute("beliefSystem"); if (beliefSystem != null) { kSession.setBeliefSystem(BeliefSystemTypeOption.get(beliefSystem)); } String scope = reader.getAttribute("scope"); if (scope != null) { kSession.setScope(scope); } readNodes( reader, new AbstractXStreamConverter.NodeReader() { public void onNode(HierarchicalStreamReader reader, String name, String value) { if ("listeners".equals(name)) { while (reader.hasMoreChildren()) { reader.moveDown(); String nodeName = reader.getNodeName(); ListenerModelImpl listener = readObject(reader, context, ListenerModelImpl.class); listener.setKSession(kSession); listener.setKind(ListenerModel.Kind.fromString(nodeName)); kSession.addListenerModel(listener); reader.moveUp(); } } else if ("workItemHandlers".equals(name)) { List<WorkItemHandlerModelImpl> wihs = readObjectList(reader, context, WorkItemHandlerModelImpl.class); for (WorkItemHandlerModelImpl wih : wihs) { wih.setKSession(kSession); kSession.addWorkItemHandelerModel(wih); } } else if ("consoleLogger".equals(name)) { String consoleLogger = reader.getAttribute("name"); kSession.setConsoleLogger(consoleLogger == null ? "" : consoleLogger); } else if ("fileLogger".equals(name)) { FileLoggerModelImpl fileLoggerModel = new FileLoggerModelImpl(reader.getAttribute("file")); try { fileLoggerModel.setInterval(Integer.parseInt(reader.getAttribute("interval"))); } catch (Exception e) { } try { fileLoggerModel.setThreaded( Boolean.parseBoolean(reader.getAttribute("threaded"))); } catch (Exception e) { } kSession.fileLogger = fileLoggerModel; } } }); return kSession; } } }
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { final KieSessionModelImpl kSession = new KieSessionModelImpl(); kSession.name = reader.getAttribute("name"); kSession.setDefault("true".equals(reader.getAttribute("default"))); String kSessionType = reader.getAttribute("type"); kSession.setType( kSessionType != null ? KieSessionType.valueOf(kSessionType.toUpperCase()) : KieSessionType.STATEFUL); String clockType = reader.getAttribute("clockType"); if (clockType != null) { kSession.setClockType(ClockTypeOption.get(clockType)); } String beliefSystem = reader.getAttribute("beliefSystem"); if (beliefSystem != null) { kSession.setBeliefSystem(BeliefSystemTypeOption.get(beliefSystem)); } String scope = reader.getAttribute("scope"); if (scope != null) { kSession.setScope(scope); } readNodes( reader, new AbstractXStreamConverter.NodeReader() { public void onNode(HierarchicalStreamReader reader, String name, String value) { if ("listeners".equals(name)) { while (reader.hasMoreChildren()) { reader.moveDown(); String nodeName = reader.getNodeName(); ListenerModelImpl listener = readObject(reader, context, ListenerModelImpl.class); listener.setKSession(kSession); listener.setKind(ListenerModel.Kind.fromString(nodeName)); kSession.addListenerModel(listener); reader.moveUp(); } } else if ("workItemHandlers".equals(name)) { List<WorkItemHandlerModelImpl> wihs = readObjectList(reader, context, WorkItemHandlerModelImpl.class); for (WorkItemHandlerModelImpl wih : wihs) { wih.setKSession(kSession); kSession.addWorkItemHandelerModel(wih); } } else if ("consoleLogger".equals(name)) { String consoleLogger = reader.getAttribute("name"); kSession.setConsoleLogger(consoleLogger == null ? "" : consoleLogger); } else if ("fileLogger".equals(name)) { FileLoggerModelImpl fileLoggerModel = new FileLoggerModelImpl(reader.getAttribute("file")); try { fileLoggerModel.setInterval(Integer.parseInt(reader.getAttribute("interval"))); } catch (Exception e) { } try { fileLoggerModel.setThreaded( Boolean.parseBoolean(reader.getAttribute("threaded"))); } catch (Exception e) { } kSession.fileLogger = fileLoggerModel; } } }); return kSession; }
@Test @Ignore("This test requires us to fix the propagation order") public void testForallWithSlidingWindow() throws Exception { final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newInputStreamResource( getClass().getResourceAsStream("test_ForallSlidingWindow.drl")), ResourceType.DRL); assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors()); final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId())); final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(conf, null); final SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); List<String> results = new ArrayList<String>(); ksession.setGlobal("results", results); // advance time... no events, so forall should fire clock.advanceTime(60, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, results.size()); int seq = 1; // advance time... there are matching events now, but forall still not fire ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 60 clock.advanceTime(5, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, results.size()); ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 65 clock.advanceTime(5, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, results.size()); // advance time... there are non-matching events now, so forall de-activates ksession.insert(new StockTick(seq++, "IBM", 10, clock.getCurrentTime())); // 70 clock.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, results.size()); // advance time... there are non-matching events now, so forall is still deactivated ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 80 clock.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, results.size()); // advance time... non-matching event expires now, so forall should fire ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 90 clock.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, results.size()); // advance time... forall still matches and should not fire ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 100 clock.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, results.size()); // advance time... forall still matches and should not fire clock.advanceTime(60, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, results.size()); }
@Test(timeout = 10000) public void testCalendarsWithCronAndStartAndEnd() throws Exception { Locale defaultLoc = Locale.getDefault(); try { Locale.setDefault( Locale.UK); // Because of the date strings in the DRL, fixable with JBRULES-3444 String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; str += "rule xxx \n"; str += " calendars \"cal1\"\n"; str += " timer (cron: 0 0 0 * * ? start=3-JAN-2010 end=5-JAN-2010) "; str += "when \n"; str += "then \n"; str += " list.add(\"fired\"); \n"; str += "end \n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); DateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.UK); Date date = df.parse("1-JAN-2010"); Calendar cal1 = new Calendar() { public boolean isTimeIncluded(long timestamp) { return true; } }; long oneDay = 60 * 60 * 24; ksession.getCalendars().set("cal1", cal1); ksession.setGlobal("list", list); timeService.advanceTime(date.getTime(), TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); // day 3 ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); // day 5 ksession.fireAllRules(); assertEquals(3, list.size()); timeService.advanceTime(oneDay, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(3, list.size()); } finally { Locale.setDefault(defaultLoc); } }
@Test(timeout = 10000) public void testIntervalTimerWithStringExpressions() throws Exception { if (CommonTestMethodBase.phreak == RuleEngineOption.PHREAK) { return; // phreak does not yet support dynamic salience } String str = "package org.simple;\n" + "global java.util.List list;\n" + "\n" + "declare Bean\n" + " delay : String = \"30s\"\n" + " period : long = 10000\n" + "end\n" + "\n" + "rule init \n" + "when \n" + "then \n" + " insert( new Bean() );\n" + "end \n" + "\n" + "rule xxx\n" + " salience ($d) \n" + " timer( expr: $d, $p; start=3-JAN-2010 )\n" + "when\n" + " Bean( $d : delay, $p : period )\n" + "then\n" + " list.add( \"fired\" );\n" + "end"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); timeService.advanceTime(new Date().getTime(), TimeUnit.MILLISECONDS); ksession.setGlobal("list", list); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(20, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(15, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(3, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(2, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); timeService.advanceTime(10, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(3, list.size()); }
@Test(timeout = 10000) public void testCalendarsWithIntervals() throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; str += "rule xxx \n"; str += " calendars \"cal1\", \"cal2\"\n"; str += " timer (15s 60s) "; // int: protocol is assumed str += "when \n"; str += "then \n"; str += " list.add(\"fired\"); \n"; str += "end \n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Date date = df.parse("2009-01-01T00:00:00.000-0000"); timeService.advanceTime(date.getTime(), TimeUnit.MILLISECONDS); final Date date1 = new Date(date.getTime() + (15 * 1000)); final Date date2 = new Date(date1.getTime() + (60 * 1000)); final Date date3 = new Date(date2.getTime() + (60 * 1000)); final Date date4 = new Date(date3.getTime() + (60 * 1000)); Calendar cal1 = new Calendar() { public boolean isTimeIncluded(long timestamp) { if (timestamp == date1.getTime()) { return true; } else if (timestamp == date4.getTime()) { return false; } else { return true; } } }; Calendar cal2 = new Calendar() { public boolean isTimeIncluded(long timestamp) { if (timestamp == date2.getTime()) { return false; } else if (timestamp == date3.getTime()) { return true; } else { return true; } } }; ksession.getCalendars().set("cal1", cal1); ksession.getCalendars().set("cal2", cal2); ksession.setGlobal("list", list); ksession.fireAllRules(); timeService.advanceTime(20, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(60, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); timeService.advanceTime(60, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); timeService.advanceTime(60, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); timeService.advanceTime(60, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(3, list.size()); timeService.advanceTime(60, TimeUnit.SECONDS); ksession.fireAllRules(); assertEquals(4, list.size()); }
@Test(timeout = 10000) public void testCalendarNormalRuleMultipleCalendars() throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; str += "rule xxx \n"; str += " calendars \"cal1\", \"cal2\"\n"; str += "when \n"; str += " String()\n"; str += "then \n"; str += " list.add(\"fired\"); \n"; str += "end \n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); Calendar calFalse = new Calendar() { public boolean isTimeIncluded(long timestamp) { return false; } }; Calendar calTrue = new Calendar() { public boolean isTimeIncluded(long timestamp) { return true; } }; List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Date date = df.parse("2009-01-01T00:00:00.000-0000"); ksession.getCalendars().set("cal1", calTrue); ksession.getCalendars().set("cal2", calTrue); timeService.advanceTime(date.getTime(), TimeUnit.MILLISECONDS); ksession.setGlobal("list", list); ksession.insert("o1"); ksession.fireAllRules(); assertEquals(1, list.size()); ksession.getCalendars().set("cal2", calFalse); timeService.advanceTime(10, TimeUnit.SECONDS); ksession.insert("o2"); ksession.fireAllRules(); assertEquals(1, list.size()); ksession.getCalendars().set("cal1", calFalse); timeService.advanceTime(10, TimeUnit.SECONDS); ksession.insert("o3"); ksession.fireAllRules(); assertEquals(1, list.size()); ksession.getCalendars().set("cal1", calTrue); ksession.getCalendars().set("cal2", calTrue); timeService.advanceTime(30, TimeUnit.SECONDS); ksession.insert("o4"); ksession.fireAllRules(); assertEquals(2, list.size()); }
@Test(timeout = 10000) public void testIntervalTimerWithoutFire() throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; str += "rule xxx \n"; str += " timer (int:30s 10s) "; str += "when \n"; str += "then \n"; str += " list.add(\"fired\"); \n"; str += "end \n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = createKnowledgeSession(kbase, conf); final BlockingQueue<TimedRuleExecution> queue = new LinkedBlockingQueue<TimedRuleExecution>(); ((StatefulKnowledgeSessionImpl) ksession).session.setTimedExecutionsQueue(queue); final CyclicBarrier barrier = new CyclicBarrier(2); final AtomicBoolean run = new AtomicBoolean(true); Thread t = new Thread( new Runnable() { public void run() { try { while (run.get()) { queue.take().evauateAndFireRule(); try { barrier.await(); } catch (BrokenBarrierException e) { throw new RuntimeException(e); } } } catch (InterruptedException e) { throw new RuntimeException(e); } } }); t.setDaemon(true); t.start(); List list = new ArrayList(); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); timeService.advanceTime(new Date().getTime(), TimeUnit.MILLISECONDS); ksession.setGlobal("list", list); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(35, TimeUnit.SECONDS); barrier.await(); barrier.reset(); assertEquals(1, list.size()); timeService.advanceTime(10, TimeUnit.SECONDS); barrier.await(); barrier.reset(); assertEquals(2, list.size()); timeService.advanceTime(10, TimeUnit.SECONDS); barrier.await(); barrier.reset(); assertEquals(3, list.size()); run.set(false); barrier.reset(); }
@Test(timeout = 10000) public void testExprTimeRescheduled() throws Exception { String text = "package org.kie.test\n" + "global java.util.List list\n" + "import " + FactA.class.getCanonicalName() + "\n" + "rule r1 timer (expr: f1.field2, f1.field4)\n" + "when\n" + " f1 : FactA() \n" + "then\n" + " list.add( f1 );\n" + "end\n" + "\n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(text); KieSession ksession = createKnowledgeSession(kbase, conf); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); timeService.advanceTime(new Date().getTime(), TimeUnit.MILLISECONDS); List list = new ArrayList(); ksession.setGlobal("list", list); FactA fact1 = new FactA(); fact1.setField1("f1"); fact1.setField2(500); fact1.setField4(1000); FactHandle fh = (FactHandle) ksession.insert(fact1); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(1100, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); assertEquals(fact1, list.get(0)); timeService.advanceTime(1100, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); assertEquals(fact1, list.get(1)); timeService.advanceTime(400, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(3, list.size()); assertEquals(fact1, list.get(2)); list.clear(); fact1.setField2(300); fact1.setField4(2000); ksession.update(fh, fact1); // 100 has passed of the 1000, from the previous schedule // so that should be deducted from the 300 delay above, meaning // we only need to increment another 250 timeService.advanceTime(250, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); assertEquals(fact1, list.get(0)); list.clear(); timeService.advanceTime(1000, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(700, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(300, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); }
@Test(timeout = 10000) public void testIntervalTimerExpressionWithOr() throws Exception { String text = "package org.kie.test\n" + "global java.util.List list\n" + "import " + FactA.class.getCanonicalName() + "\n" + "import " + Foo.class.getCanonicalName() + "\n" + "import " + Pet.class.getCanonicalName() + "\n" + "rule r1 timer (expr: f1.field2, f1.field2; repeat-limit=3)\n" + "when\n" + " foo: Foo()\n" + " ( Pet() and f1 : FactA( field1 == 'f1') ) or \n" + " f1 : FactA(field1 == 'f2') \n" + "then\n" + " list.add( f1 );\n" + " foo.setId( 'xxx' );\n" + "end\n" + "\n"; KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption(ClockTypeOption.get("pseudo")); KnowledgeBase kbase = loadKnowledgeBaseFromString(text); KieSession ksession = createKnowledgeSession(kbase, conf); PseudoClockScheduler timeService = (PseudoClockScheduler) ksession.<SessionClock>getSessionClock(); timeService.advanceTime(new Date().getTime(), TimeUnit.MILLISECONDS); List list = new ArrayList(); ksession.setGlobal("list", list); ksession.insert(new Foo(null, null)); ksession.insert(new Pet(null)); FactA fact1 = new FactA(); fact1.setField1("f1"); fact1.setField2(250); FactA fact3 = new FactA(); fact3.setField1("f2"); fact3.setField2(1000); ksession.insert(fact1); ksession.insert(fact3); ksession.fireAllRules(); assertEquals(0, list.size()); timeService.advanceTime(300, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(1, list.size()); assertEquals(fact1, list.get(0)); timeService.advanceTime(300, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); assertEquals(fact1, list.get(1)); timeService.advanceTime(300, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(2, list.size()); // did not change, repeat-limit kicked in timeService.advanceTime(300, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(3, list.size()); assertEquals(fact3, list.get(2)); timeService.advanceTime(1000, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(4, list.size()); assertEquals(fact3, list.get(3)); timeService.advanceTime(1000, TimeUnit.MILLISECONDS); ksession.fireAllRules(); assertEquals(4, list.size()); // did not change, repeat-limit kicked in }