org.kie.api.runtime.KieSession Java Examples
The following examples show how to use
org.kie.api.runtime.KieSession.
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: NullSafeDereferencingTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testNullSafeMemberOf() { // DROOLS-50 String str = "declare A\n" + " list : java.util.List\n" + "end\n" + "\n" + "rule Init when\n" + "then\n" + " insert( new A( java.util.Arrays.asList( \"test\" ) ) );" + " insert( \"test\" );" + "end\n" + "rule R when\n" + " $a : A()\n" + " $s : String( this memberOf $a!.list )\n" + "then\n" + "end"; KieBase kbase = loadKnowledgeBaseFromString(str); KieSession ksession = kbase.newKieSession(); assertEquals(2, ksession.fireAllRules()); ksession.dispose(); }
Example #2
Source File: WrongServiceRulesJUnitTest.java From drools-workshop with Apache License 2.0 | 6 votes |
@Test public void testServiceCallInRHS() { Assert.assertNotNull(kBase); KieSession kSession = kBase.newKieSession(); kSession.setGlobal("myConditionsProviderService", new MyConditionsProviderServiceImpl()); System.out.println(" ---- Starting testServiceCallInRHS() Test ---"); Patient patient = (Patient) new Patient().setId("Patient/1"); FactHandle patientHandle = kSession.insert(patient); Assert.assertEquals(50, kSession.fireAllRules()); //A modification of the patient will execute the service patient.addName(new HumanNameDt().addFamily("Richards")); kSession.update(patientHandle, patient); Assert.assertEquals(50, kSession.fireAllRules()); System.out.println(" ---- Finished testServiceCallInRHS() Test ---"); kSession.dispose(); }
Example #3
Source File: DeclarativeAgendaTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testApplyBlockerFirst() { KieSession ksession = getStatefulKnowledgeSession(); List list = new ArrayList(); ksession.setGlobal( "list", list ); FactHandle go2 = ksession.insert( "go2" ); //((InternalWorkingMemory) ksession).flushPropagations(); FactHandle go1 = ksession.insert( "go1" ); ksession.fireAllRules(); assertEquals( 1, list.size() ); assertTrue( list.contains( "rule1:go2" ) ); list.clear(); ksession.retract( go2 ); ksession.fireAllRules(); assertEquals( 1, list.size() ); assertTrue( list.contains( "rule1:go1" ) ); }
Example #4
Source File: DroolsScoreExample.java From drools-examples with Apache License 2.0 | 6 votes |
public static void execute( KieContainer kc ) throws Exception{ // From the container, a session is created based on // its definition and configuration in the META-INF/kmodule.xml file KieSession ksession = kc.newKieSession("point-rulesKS"); List<Order> orderList = getInitData(); for (int i = 0; i < orderList.size(); i++) { Order o = orderList.get(i); ksession.insert(o); ksession.fireAllRules(); // 执行完规则后, 执行相关的逻辑 addScore(o); } ksession.dispose(); }
Example #5
Source File: MapConstraintTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testMapAccessWithVariable() throws Exception { final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_MapAccessWithVariable.drl")); final KieSession ksession = createKnowledgeSession(kbase); final List list = new ArrayList(); ksession.setGlobal("results", list); final Map map = new HashMap(); map.put("name", "Edson"); map.put("surname", "Tirelli"); map.put("age", "28"); ksession.insert(map); ksession.insert("name"); ksession.fireAllRules(); assertEquals(1, list.size()); assertTrue(list.contains(map)); }
Example #6
Source File: TruthMaintenanceTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testLogicalInsertionsNoLoop() throws Exception { KieBase kbase = loadKnowledgeBase("test_LogicalInsertionsNoLoop.drl"); KieSession ksession = kbase.newKieSession(); try { final List l = new ArrayList(); final Person a = new Person( "a" ); ksession.setGlobal( "a", a ); ksession.setGlobal( "l", l ); ksession.fireAllRules(); assertEquals(0, ksession.getObjects(new ClassObjectFilter(a.getClass())).size(), "a still in WM"); assertEquals(1, l.size(), "Rule should not loop"); } finally { ksession.dispose(); } }
Example #7
Source File: AlphaNodeTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testSharedAlphaWithBeta() { String str = "import org.drools.compiler.Person\n" + "rule R1 when\n" + " $p : Person(name == \"Mario\")\n" + "then\n" + "end\n" + "rule R2 when\n" + " $p : Person(name == \"Mario\")\n" + " $s : String(this == $p.name)\n" + "then\n" + "end\n"; KieBase kbase = loadKnowledgeBaseFromString( str ); KieSession ksession = kbase.newKieSession(); ksession.insert( new Person( "Mario" ) ); ksession.insert( "Mario" ); assertEquals( 2, ksession.fireAllRules() ); }
Example #8
Source File: MVELTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testLocalVariableMVELConsequence() { final KieBase kbase = loadKnowledgeBase("test_LocalVariableMVELConsequence.drl"); final KieSession ksession = kbase.newKieSession(); final List list = new ArrayList(); ksession.setGlobal("results", list); ksession.insert(new Person("bob", "stilton")); ksession.insert(new Person("mark", "brie")); try { ksession.fireAllRules(); assertEquals(2, list.size(), "should have fired twice"); } catch (final Exception e) { e.printStackTrace(); fail("Should not raise any exception"); } }
Example #9
Source File: JavaInvokerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
@Test public void testMyFirstMethod3() throws Exception { KieBase kbase = readKnowledgeBase(); KieSession ksession = createSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler("Java", new JavaInvocationWorkItemHandler()); Map<String, Object> params = new HashMap<String, Object>(); params.put("Class", "org.jbpm.process.workitem.java.MyJavaClass"); params.put("Method", "myFirstMethod"); params.put("Object", new MyJavaClass()); List<Object> parameters = new ArrayList<Object>(); parameters.add("krisv"); parameters.add(32); parameters.add("male"); params.put("Parameters", parameters); ksession.startProcess("com.sample.bpmn.java", params); }
Example #10
Source File: LibraryClient.java From rhpam-7-openshift-image with Apache License 2.0 | 6 votes |
Loan attemptLoan(String isbn) { Map<String, Object> parameters = new HashMap<String, Object>(); LoanRequest loanRequest = new LoanRequest(); loanRequest.setIsbn(isbn); parameters.put("loanRequest", loanRequest); LoanResponse loanResponse; if (appcfg.getKieSession() != null) { KieSession kieSession = appcfg.getKieSession(); WorkflowProcessInstance procinst = (WorkflowProcessInstance) kieSession.startProcess("LibraryProcess", parameters); loanResponse = (LoanResponse) procinst.getVariable("loanResponse"); } else { ProcessServicesClient procserv = appcfg.getProcessServicesClient(); Long pid = procserv.startProcess("rhpam-kieserver-library", "LibraryProcess", parameters); loanResponse = (LoanResponse) procserv.getProcessInstanceVariable("rhpam-kieserver-library", pid, "loanResponse"); } return loanResponse != null ? loanResponse.getLoan() : null; }
Example #11
Source File: ShoppingCartServiceImpl.java From drools-workshop with Apache License 2.0 | 6 votes |
@Override public String newShoppingCart() throws BusinessException { String cartId = UUID.randomUUID().toString(); RuleBaseConfiguration conf = new RuleBaseConfiguration(); conf.setAssertBehaviour(RuleBaseConfiguration.AssertBehaviour.EQUALITY); KieBase kBase = kContainer.newKieBase(conf); KieSession kSession = kBase.newKieSession(); kSession.registerChannel("outboundChannel", new Channel() { @Override public void send(Object o) { System.out.println(o); } }); shoppingCarts.put(cartId, kSession); return cartId; }
Example #12
Source File: JavaInvokerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
@Test public void testStaticMethod1() throws Exception { KieBase kbase = readKnowledgeBase(); KieSession ksession = createSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler("Java", new JavaInvocationWorkItemHandler()); Map<String, Object> params = new HashMap<String, Object>(); params.put("Class", "org.jbpm.process.workitem.java.MyJavaClass"); params.put("Method", "staticMethod1"); params.put("Object", new MyJavaClass()); ksession.startProcess("com.sample.bpmn.java", params); }
Example #13
Source File: PropertyReactivityTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testUpdateOnNonExistingProperty() { // DROOLS-2170 final String str1 = "import " + Klass.class.getCanonicalName() + "\n" + "rule R when\n" + " Klass( b == 2 )\n" + "then\n" + "end\n"; final KieSession ksession = new KieHelper().addContent( str1, ResourceType.DRL ) .build() .newKieSession(); final Klass bean = new Klass( 1, 2, 3, 4, 5, 6 ); final FactHandle fh = ksession.insert( bean ); ksession.fireAllRules(); try { ksession.update( fh, bean, "z" ); fail("Trying to update not existing property must fail"); } catch (Exception e) { assertTrue( e.getMessage().contains( Klass.class.getName() ) ); } }
Example #14
Source File: DescrBuilderTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testRuleRHSComment() throws InstantiationException, IllegalAccessException { PackageDescr pkg = DescrFactory.newPackage() .name( "org.drools.compiler" ) .newRule().name( "r1" ) .lhs() .pattern("StockTick").constraint( "company == \"RHT\"" ).end() .end() .rhs( "// some comment" ) .end() .getDescr(); KiePackage kpkg = compilePkgDescr( pkg ); assertEquals( "org.drools.compiler", kpkg.getName() ); InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addPackages( Collections.singletonList( kpkg ) ); KieSession ksession = kbase.newKieSession(); ksession.insert( new StockTick(1, "RHT", 80, 1 ) ); int rules = ksession.fireAllRules(); assertEquals( 1, rules ); }
Example #15
Source File: EnumTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test public void testInnerEnum() throws Exception { final StringBuilder rule = new StringBuilder(); rule.append( "package org.drools.compiler\n" ); rule.append( "rule X\n" ); rule.append( "when\n" ); rule.append( " Triangle( type == Triangle.Type.UNCLASSIFIED )\n" ); rule.append( "then\n" ); rule.append( "end\n" ); final KieBase kbase = loadKnowledgeBaseFromString(rule.toString()); final KieSession ksession = createKnowledgeSession(kbase); ksession.insert(new Triangle()); final int rules = ksession.fireAllRules(); assertEquals(1, rules); ksession.dispose(); }
Example #16
Source File: KnowledgeBaseImpl.java From kogito-runtimes with Apache License 2.0 | 6 votes |
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 #17
Source File: JavaInvokerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
@Test public void failingtestHello() throws Exception { KieBase kbase = readKnowledgeBase(); KieSession ksession = createSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler("Java", new JavaInvocationWorkItemHandler()); Map<String, Object> params = new HashMap<String, Object>(); params.put("Class", "org.jbpm.process.workitem.java.MyJavaClass"); params.put("Method", "writeHello"); List<Object> parameters = new ArrayList<Object>(); parameters.add("krisv"); params.put("Parameters", parameters); ksession.startProcess("com.sample.bpmn.java", params); }
Example #18
Source File: InterpretedRuleUnit.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Override public RuleUnitInstance<T> internalCreateInstance(T data) { KnowledgeBuilder kBuilder = new KnowledgeBuilderImpl(); Class<? extends RuleUnitData> wmClass = data.getClass(); String canonicalName = wmClass.getCanonicalName(); // transform foo.bar.Baz to /foo/bar/Baz.drl // this currently only works for single files InputStream resourceAsStream = wmClass.getResourceAsStream( String.format("/%s.drl", canonicalName.replace('.', '/'))); kBuilder.add(new InputStreamResource(resourceAsStream), ResourceType.DRL); InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase(); kBase.addPackages(kBuilder.getKnowledgePackages()); KieSession kSession = kBase.newKieSession(); return new InterpretedRuleUnitInstance<>(this, data, kSession); }
Example #19
Source File: StartCorrelatedProcessCommand.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public ProcessInstance execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup( KieSession.class ); if (data != null) { for (Object o: data) { ksession.insert(o); } } ProcessInstance processInstance = ((CorrelationAwareProcessRuntime)ksession).startProcess(processId, correlationKey, parameters); if ( this.outIdentifier != null ) { ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult(this.outIdentifier, processInstance.getId()); } return processInstance; }
Example #20
Source File: LogicalTraitTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@ParameterizedLogicalTraitTest public void testShadowAlias(VirtualPropertyMode mode) { KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilderImpl.add( ResourceFactory.newClassPathResource("org/drools/compiler/factmodel/traits/testTraitedAliasing.drl"), ResourceType.DRL); if (kbuilderImpl.hasErrors()) { fail(kbuilderImpl.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addPackages(kbuilderImpl.getKnowledgePackages()); TraitFactory.setMode(mode, kbase); KieSession ks = kbase.newKieSession(); ArrayList list = new ArrayList(); ks.setGlobal("list", list); ks.fireAllRules(); for (Object o : ks.getObjects()) { System.out.println(o); } try { ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } System.out.println(list); assertFalse(list.contains(false)); assertEquals(8, list.size()); }
Example #21
Source File: ReteOOWaltzTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testWaltz() { assertTimeoutPreemptively(Duration.ofSeconds(20), () -> { try { //load up the rulebase final KieBase kBase = readKnowledegBase(); for (int i = 0; i < 50; i++) { KieSession kSession = kBase.newKieSession(); // workingMemory.setGlobal( "sysout", // System.out ); // DebugWorkingMemoryEventListener wmListener = new DebugWorkingMemoryEventListener(); // DebugAgendaEventListener agendaListener = new DebugAgendaEventListener(); // workingMemory.addEventListener( wmListener ); // workingMemory.addEventListener( agendaListener ); //go ! this.loadLines(kSession, "waltz50.dat"); //final Stage stage = new Stage( Stage.START ); //workingMemory.assertObject( stage ); final long start = System.currentTimeMillis(); final Stage stage = new Stage(Stage.DUPLICATE); kSession.insert(stage); kSession.fireAllRules(); kSession.dispose(); final long end = System.currentTimeMillis(); System.out.println(end - start); } } catch (final Throwable t) { t.printStackTrace(); fail(t.getMessage()); } }); }
Example #22
Source File: KieSessionUtils.java From fw-spring-cloud with Apache License 2.0 | 5 votes |
public static KieSession createKieSessionFromDRL(String drl) throws Exception{ KieHelper kieHelper = new KieHelper(); kieHelper.addContent(drl, ResourceType.DRL); Results results = kieHelper.verify(); if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)) { List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR); for (Message message : messages) { System.out.println("Error: "+message.getText()); } // throw new IllegalStateException("Compilation errors were found. Check the logs."); } return kieHelper.build().newKieSession(); }
Example #23
Source File: BasicConcurrentInsertionsTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
protected Callable<Boolean> getTask( final int objectCount, final KieSession ksession, final boolean disposeSession, final boolean updateFacts) { return () -> { try { for (int j = 0; j < 10; j++) { FactHandle[] facts = new FactHandle[objectCount]; for (int i = 0; i < objectCount; i++) { facts[i] = ksession.insert(new Bean(i)); } if (updateFacts) { for (int i = 0; i < objectCount; i++) { ksession.update(facts[i], new Bean(-i)); } } for (FactHandle fact : facts) { ksession.delete(fact); } ksession.fireAllRules(); } return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { if (disposeSession) { ksession.dispose(); } } }; }
Example #24
Source File: EventAccessorRestoreTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public void saveSession( FileOutputStream output, KieSession ksession ) throws IOException { DroolsObjectOutputStream droolsOut = new DroolsObjectOutputStream( output ); droolsOut.writeObject( ksession.getKieBase() ); Marshaller mas = createMarshaller( ksession.getKieBase() ); mas.marshall( droolsOut, ksession ); droolsOut.flush(); droolsOut.close(); }
Example #25
Source File: GetWorkItemIdsCommand.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public List<String> execute(Context context) { KieSession ksession = ((RegistryContext) context).lookup( KieSession.class ); Set<WorkItem> workItems = ((WorkItemManager) ksession.getWorkItemManager()).getWorkItems(); List<String> workItemIds = new ArrayList<String>(workItems.size()); for(WorkItem workItem : workItems ) { workItemIds.add(workItem.getId()); } if ( this.outIdentifier != null ) { ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult(this.outIdentifier, workItemIds); } return workItemIds; }
Example #26
Source File: SessionsPoolTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private void checkKieSession( KieSession ksession ) { List<String> list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.insert( "test" ); ksession.fireAllRules(); assertEquals(1, list.size()); }
Example #27
Source File: DefeasibilityTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testStrictEntailment() { KieSession kSession = getSession( "org/drools/compiler/beliefsystem/defeasible/strict.drl" ); kSession.fireAllRules(); TruthMaintenanceSystem tms = ((NamedEntryPoint) kSession.getEntryPoint( "DEFAULT" )).getTruthMaintenanceSystem(); FactType Ctype = kSession.getKieBase().getFactType( "org.drools.defeasible", "C" ); FactType Dtype = kSession.getKieBase().getFactType( "org.drools.defeasible", "D" ); ObjectHashMap keys = tms.getEqualityKeyMap(); Iterator iter = keys.iterator(); ObjectHashMap.ObjectEntry entry; while ( ( entry = ( ObjectHashMap.ObjectEntry) iter.next() ) != null ) { EqualityKey key = (EqualityKey) entry.getValue(); Class factClass = key.getFactHandle().getObject().getClass(); if ( factClass == Ctype.getFactClass() ) { checkStatus( key, 2, DefeasibilityStatus.DEFINITELY ); } else if ( factClass == Dtype.getFactClass() ) { checkStatus( key, 1, DefeasibilityStatus.DEFINITELY ); } else { fail( "Unrecognized object has been logically justified : " + factClass ); } } assertEquals( 5, kSession.getObjects().size() ); }
Example #28
Source File: PropertyReactivityTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test public void testComment() { // DROOLS-3583 final String str1 = "package com.example\n" + "\n" + "declare Counter\n" + " value: int\n" + "end\n" + "\n" + "rule \"Init\" when\n" + " not Counter()\n" + "then\n" + " drools.insert(new Counter(0));\n" + "end\n" + "\n" + "rule \"Loop\"\n" + "when\n" + " $c: Counter()\n" + "then\n" + "// removing this comment line removes the loop\n" + " $c.setValue(1);\n" + " update($c);\n" + "end\n\n"; final KieSession ksession = new KieHelper().addContent( str1, ResourceType.DRL ) .build() .newKieSession(); assertEquals( 2, ksession.fireAllRules() ); }
Example #29
Source File: ActivationIteratorTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@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 #30
Source File: DslTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Test @Disabled("antlr cannot parse correctly if the file ends with a comment without a further line break") public void testEmptyDSL() throws Exception { // FIXME etirelli / mic_hat not sure what to do with this? final String DSL = "# This is an empty dsl file."; // gives antlr <EOF> error KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newClassPathResource( "test_expander.dsl", getClass() ), ResourceType.DSL ); kbuilder.add( ResourceFactory.newReaderResource( new StringReader( DSL) ) , ResourceType.DSLR ); assertFalse( kbuilder.hasErrors() ); // trying to expand Cheese() pattern // Check errors final String err = kbuilder.getErrors().toString(); assertEquals( "", err ); assertEquals( 0, kbuilder.getErrors().size() ); // the compiled package Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages(); assertEquals( 0, pkgs.size() ); InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addPackages( pkgs ); kbase = SerializationHelper.serializeObject(kbase); KieSession session = createKnowledgeSession(kbase); pkgs = SerializationHelper.serializeObject(pkgs); assertNull( pkgs ); }