下面列出了org.junit.jupiter.api.function.ThrowingSupplier#org.kie.api.runtime.KieSession 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
@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;
}
@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));
}
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();
}
@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();
}
@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();
}
}
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();
}
}
@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();
}
@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);
}
@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();
}
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;
}
@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");
}
}
@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() );
}
@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" ) );
}
@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);
}
@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() ) );
}
}
@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 );
}
@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);
}
@Test
public void testPrimeJustificationWithEqualityMode() {
String droolsSource =
"package org.drools.tms.test; \n" +
"declare Bar end \n" +
"" +
"declare Holder x : Bar end \n" +
"" +
"" +
"rule Init \n" +
"when \n" +
"then \n" +
" insert( new Holder( new Bar() ) ); \n" +
"end \n" +
"rule Justify \n" +
"when \n" +
" $s : Integer() \n" +
" $h : Holder( $b : x ) \n" +
"then \n" +
" insertLogical( $b ); \n" +
"end \n" +
"rule React \n" +
"when \n" +
" $b : Bar( ) \n" +
"then \n" +
" System.out.println( $b ); \n" +
"end \n" ;
KieSession session = getSessionFromString( droolsSource );
FactHandle handle1 = session.insert( 10 );
FactHandle handle2 = session.insert( 20 );
assertEquals( 4, session.fireAllRules() );
session.delete( handle1 );
assertEquals( 0, session.fireAllRules() );
}
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();
}
@Test
public void testNotReactivePeer() {
// DROOLS-1727
String drl1 =
"import org.drools.compiler.oopath.model.*;\n" +
"global java.util.List list\n\n" +
"rule R1 when\n" +
" not String()\n" +
" $a : Man( name == \"Mario\" )\n" +
"then\n" +
" list.add(\"Found\");\n" +
" insert($a.getName());\n" +
"end\n\n" +
"rule R2 when\n" +
" not String()\n" +
" $a : Man( $c: /children[age == 6], name == \"Mario\" )\n" +
"then\n" +
" list.add(\"Found\");\n" +
" insert($a.getName());\n" +
"end\n\n";
KieSession ksession = new KieHelper().addContent( drl1, ResourceType.DRL ).build().newKieSession();
List<String> list = new ArrayList<>();
ksession.setGlobal( "list", list );
Man mario = new Man("Mario", 40);
mario.addChild( new Child("Sofia", 6) );
ksession.insert( mario );
ksession.fireAllRules();
assertEquals( 1, list.size() );
}
public static ReadSessionResult getSerialisedStatefulKnowledgeSessionWithMessage(final KieSession ksession,
final KieBase kbase,
final boolean dispose) throws Exception {
final ProtobufMarshaller marshaller = (ProtobufMarshaller) MarshallerFactory.newMarshaller(kbase,
(ObjectMarshallingStrategy[]) ksession.getEnvironment().get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES));
final long time = ksession.getSessionClock().getCurrentTime();
// make sure globas are in the environment of the session
ksession.getEnvironment().set(EnvironmentName.GLOBALS, ksession.getGlobals());
// Serialize object
final byte[] serializedObject;
try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
marshaller.marshall(bos, ksession, time);
serializedObject = bos.toByteArray();
}
// Deserialize object
final ReadSessionResult readSessionResult;
try (final ByteArrayInputStream bais = new ByteArrayInputStream(serializedObject)) {
readSessionResult = marshaller.unmarshallWithMessage(bais,
ksession.getSessionConfiguration(),
ksession.getEnvironment());
}
if (dispose) {
ksession.dispose();
}
return readSessionResult;
}
@Test
public void compensationInvokingSubProcess() throws Exception {
KieSession ksession = createKnowledgeSession("compensation/BPMN2-UserTaskCompensation.bpmn2");
ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler());
Map<String, Object> params = new HashMap<String, Object>();
params.put("compensation", "True");
ProcessInstance processInstance = ksession.startProcess("UserTaskCompensation", params);
assertProcessInstanceCompleted(processInstance.getId(), ksession);
assertProcessVarValue(processInstance, "compensation", "compensation");
}
/**
* 测试规则的触发
*/
@Test
public void testRule(){
KieSession kieSession = kieBase.newKieSession();
kieSession.fireAllRules(new RuleNameStartsWithAgendaFilter("rule_rhs_"));
kieSession.dispose();
}
public Object execute(Context context ) {
KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
if (processInstanceId == null) {
return null;
}
ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId);
if ( processInstance == null ) {
throw new IllegalArgumentException( "Could not find process instance for id " + processInstanceId );
}
if ( processInstance.getState() != ProcessInstance.STATE_ACTIVE ) {
throw new IllegalArgumentException( "Process instance with id " + processInstanceId + " in state " + processInstance.getState());
}
((org.jbpm.process.instance.ProcessInstance) processInstance).setState( ProcessInstance.STATE_SUSPENDED );
return null;
}
/**
* 测试规则的触发
*/
@Test
public void helloTest(){
KieSession kieSession = kieBase.newKieSession();
//指定组获得焦点
kieSession.getAgenda().getAgendaGroup("agenda_group_1").setFocus();
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
kieSession.fireAllRules(new RuleNameStartsWithAgendaFilter("rule_agendagroup_"));
kieSession.dispose();
}
public Void execute(Context context) {
KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
if ( !( (InternalWorkingMemory) ksession ).getAgenda().isFiring() ) {
new Thread( () -> ksession.fireUntilHalt( agendaFilter ) ).start();
}
return null;
}
@Test
@Disabled("The checkReachability method is not totally reliable and can fall in an endless loop." +
"We need to find a better way to check this.")
public void testLeakAfterSessionDispose() {
// DROOLS-1655
String drl =
"import " + Person.class.getCanonicalName() + "\n" +
"rule R when\n" +
" $p : Person()\n" +
"then\n" +
"end\n";
KieContainer kContainer = new KieHelper().addContent( drl, ResourceType.DRL ).getKieContainer();
KieSession ksession = kContainer.newKieSession();
KieBase kBase = ksession.getKieBase();
ksession.insert( new Person("Mario", 40) );
ksession.fireAllRules();
checkReachability( ksession, Person.class::isInstance, true );
checkReachability( kBase, ksession::equals, true );
checkReachability( kContainer, ksession::equals, true );
ksession.dispose();
checkReachability( kContainer, Person.class::isInstance, false );
checkReachability( kBase, ksession::equals, false );
checkReachability( kContainer, ksession::equals, false );
}
/**
* Test to demonstrate that Compensation Events work with Reusable
* Subprocesses
*
* @throws Exception
*/
@Test
public void compensationWithReusableSubprocess() throws Exception {
KieSession ksession = createKnowledgeSession("compensation/BPMN2-Booking.bpmn2",
"compensation/BPMN2-BookResource.bpmn2", "compensation/BPMN2-CancelResource.bpmn2");
ProcessInstance processInstance = ksession.startProcess("Booking");
assertProcessInstanceCompleted(processInstance.getId(), ksession);
}
@Test()
public void testAbis_Working() {
// DROOLS-644
String drl =
"import " + Person.class.getCanonicalName() + ";\n" +
"global java.util.List list;\n" +
"rule R when\n" +
" $p1 : Person( name == \"Mario\", $a1: age) \n" +
" $p2 : Person( age > $a1 ) \n" +
"then\n" +
" list.add(\"t0\");\n" +
"end\n" +
"rule Z when\n" +
" $p1 : Person( name == \"Mario\" ) \n" +
"then\n" +
" modify($p1) { setAge(35); } \n" +
"end\n"
;
// making the default explicit:
KieSession ksession = new KieHelper(PropertySpecificOption.ALWAYS).addContent(drl, ResourceType.DRL)
.build()
.newKieSession();
System.out.println(drl);
ReteDumper.dumpRete(ksession);
List<String> list = new ArrayList<String>();
ksession.setGlobal("list", list);
Person mario = new Person("Mario", 40);
Person mark = new Person("Mark", 37);
FactHandle fh_mario = ksession.insert(mario);
ksession.insert(mark);
int x = ksession.fireAllRules();
assertEquals(1, list.size());
assertEquals("t0", list.get(0));
}