public void testNewSessionFailBefore() throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("sampleFailBefore.bpmn"), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); SessionManagerFactory factory = new NewSessionSessionManagerFactory(kbase); SessionManager sessionManager = factory.getSessionManager(); try { ProcessInstance processInstance = sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null); fail("Started process instance " + processInstance.getId()); } catch (RuntimeException e) { // do nothing } // TODO: whenever transaction fails, do we need to dispose? can we? // sessionManager.dispose(); List<Status> statusses = new ArrayList<Status>(); statusses.add(Status.Reserved); sessionManager = factory.getSessionManager(); List<TaskSummary> tasks = sessionManager.getTaskService().getTasksAssignedAsPotentialOwner("mary", "en-UK"); assertEquals(0, tasks.size()); sessionManager.dispose(); factory.dispose(); }
public void testNewSessionDispose() throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); SessionManagerFactory factory = new NewSessionSessionManagerFactory(kbase); final SessionManager sessionManager = factory.getSessionManager(); UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null); TransactionManagerServices.getTransactionManager() .getTransaction() .registerSynchronization( new Synchronization() { public void beforeCompletion() {} public void afterCompletion(int status) { try { sessionManager.dispose(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); ut.commit(); factory.dispose(); }
public void testProcessFactory() { RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process"); factory // header .name("My process") .packageName("org.jbpm") // nodes .startNode(1) .name("Start") .done() .actionNode(2) .name("Action") .action("java", "System.out.println(\"Action\");") .done() .endNode(3) .name("End") .done() // connections .connection(1, 2) .connection(2, 3); RuleFlowProcess process = factory.validate().getProcess(); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newByteArrayResource( XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes()), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); ksession.startProcess("org.jbpm.process"); }
private void runAgent(boolean stateful, boolean newInstance) throws Exception { String result; KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kagent = createKAgent(kbase, newInstance, true); createRuleResource(); ChangeSetHelperImpl cs = new ChangeSetHelperImpl(); FileSystemResource r = (FileSystemResource) ResourceFactory.newFileResource(res); r.setResourceType(ResourceType.DRL); cs.addNewResource(r); kagent.applyChangeSet(cs.getChangeSet()); result = insertMessageAndFire("test1", stateful); Assert.assertEquals("Echo:test1", result); if (newInstance) { modifyRuleResourceBrandNew(); } else { modifyRuleResourceIncremental(); } scan(kagent); result = insertMessageAndFire("test2", stateful); Assert.assertEquals("Echo:test2", result); kagent.dispose(); }
private KnowledgeBase buildKnowledgeBase(String... rules) { String str = ""; str += "package org.kie \n"; str += "import " + A.class.getCanonicalName() + "\n"; str += "import " + B.class.getCanonicalName() + "\n"; str += "import " + C.class.getCanonicalName() + "\n"; str += "global java.util.List list \n"; int i = 0; for (String lhs : rules) { str += "rule rule" + (i++) + " when \n"; str += lhs; str += "then \n"; str += "end \n"; } KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors()); KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kconf.setOption(LRUnlinkingOption.ENABLED); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); return kbase; }
@Test public void testUpdateWithNonEffectiveActivations() throws Exception { // JBRULES-3604 String str = "package inheritance\n" + "\n" + "import org.drools.Address\n" + "\n" + "rule \"Parent\"\n" + " enabled false\n" + " when \n" + " $a : Address(suburb == \"xyz\")\n" + " then \n" + " System.out.println( $a ); \n" + "end \n" + "rule \"Child\" extends \"Parent\" \n" + " when \n" + " $b : Address( this == $a, street == \"123\")\n" + " then \n" + " System.out.println( $b ); \n" + "end"; KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(); builder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); if (builder.hasErrors()) { throw new RuntimeException(builder.getErrors().toString()); } KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kconf.setOption(LRUnlinkingOption.ENABLED); KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase(kconf); knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages()); StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession(); Address address = new Address(); address.setSuburb("xyz"); org.kie.runtime.rule.FactHandle addressHandle = ksession.insert(address); int rulesFired = ksession.fireAllRules(); assertEquals(0, rulesFired); address.setStreet("123"); ksession.update(addressHandle, address); rulesFired = ksession.fireAllRules(); System.out.println(rulesFired); assertEquals(1, rulesFired); ksession.dispose(); }
public void testSingletonSessionMemory() throws Exception { for (int i = 0; i < 1000; i++) { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); SessionManagerFactory factory = new SingletonSessionManagerFactory(kbase); SessionManager sessionManager = factory.getSessionManager(); sessionManager.dispose(); factory.dispose(); System.gc(); Thread.sleep(100); System.gc(); System.out.println(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); } }
private void addRuleAssetToVerifier() { ContentHandler handler = ContentManager.getHandler(ruleAsset.getFormat()); if (!(handler instanceof IRuleAsset)) { throw new IllegalStateException("IRuleAsset Expected"); } RuleModel model = (RuleModel) ruleAsset.getContent(); String brl = BRXMLPersistence.getInstance().marshal(model); verifier.addResourcesToVerify( ResourceFactory.newByteArrayResource(brl.getBytes()), ResourceType.BRL); }
@Test public void testCompilationMustFailComparingAClassLiteral() { // DROOLS-20 String str = "import org.drools.integrationtests.MiscTest2.Answer\n" + "import org.drools.integrationtests.MiscTest2.AnswerGiver\n" + "rule \"Test Rule\"\n" + "when\n" + " AnswerGiver(Answer == Answer.YES)\n" + "then\n" + "end"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); assertTrue(kbuilder.hasErrors()); }
@Test public void testClassNotFoundAfterDeserialization() throws Exception { // JBRULES-3670 String drl = "package completely.other.deal;\n" + "\n" + "declare Person\n" + " firstName : String\n" + " lastName : String\n" + "end\n" + "\n" + "rule \"now use it B\"\n" + " when\n" + " Person( $christianName, $surname; )\n" + " then\n" + " insert( new Person( $christianName, null ) );\n" + "end"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { throw new RuntimeException("" + kbuilder.getErrors()); } FileManager fileManager = new FileManager().setUp(); try { File root = fileManager.getRootDirectory(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(root, "test.drl.compiled"))); out.writeObject(kbuilder.getKnowledgePackages()); out.close(); KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); kconf.setOption(LRUnlinkingOption.ENABLED); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf); ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File(root, "test.drl.compiled"))); kbase.addKnowledgePackages((Collection<KnowledgePackage>) in.readObject()); in.close(); } finally { fileManager.tearDown(); } }
public void testNewSessionFailAfter() throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("sampleFailAfter.bpmn"), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); SessionManagerFactory factory = new NewSessionSessionManagerFactory(kbase); SessionManager sessionManager = factory.getSessionManager(); ProcessInstance processInstance = sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null); long workItemId = ((HumanTaskNodeInstance) ((WorkflowProcessInstance) processInstance).getNodeInstances().iterator().next()) .getWorkItemId(); long taskId = sessionManager.getTaskService().getTaskByWorkItemId(workItemId).getId(); sessionManager.getTaskService().claim(taskId, "mary"); List<Status> statusses = new ArrayList<Status>(); statusses.add(Status.Reserved); List<TaskSummary> tasks = sessionManager.getTaskService().getTasksOwned("mary", statusses, "en-UK"); assertEquals(1, tasks.size()); taskId = tasks.get(0).getId(); UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); try { ut.begin(); sessionManager.getTaskService().start(taskId, "mary"); sessionManager.getTaskService().complete(taskId, "mary", null); fail("Task completed"); } catch (RuntimeException e) { // do nothing } ut.rollback(); // TODO: whenever transaction fails, do we need to dispose? can we? // sessionManager.dispose(); sessionManager = factory.getSessionManager(); tasks = sessionManager.getTaskService().getTasksOwned("mary", statusses, "en-UK"); assertEquals(1, tasks.size()); sessionManager.dispose(); factory.dispose(); }
public void testNewSession() throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); SessionManagerFactory factory = new NewSessionSessionManagerFactory(kbase); completedStart = 0; for (int i = 0; i < nbThreadsProcess; i++) { new StartProcessRunnable(factory, i).run(); } completedTask = 0; for (int i = 0; i < nbThreadsTask; i++) { new Thread(new CompleteTaskRunnable(factory, i)).start(); } while (completedStart < nbThreadsProcess || completedTask < nbThreadsTask) { Thread.sleep(100); } factory.dispose(); System.out.println("Done"); }
public static void main(final String[] args) { final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newClassPathResource( "WorkItemConsequence1.drl", WorkItemConsequenceExample1.class), ResourceType.DRL); final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); if (kbuilder.hasErrors()) { throw new RuntimeException("Compilation error.\n" + kbuilder.getErrors().toString()); } final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession .getWorkItemManager() .registerWorkItemHandler("EmailWorkItemHandler", new EmailWorkItemHandler()); // KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, // "log/WorkItemConsequence.log"); // Brains does not cause concern PersonLocation brains = new PersonLocation("Brains", 5); ksession.insert(brains); ksession.fireAllRules(); // Gargamel is too far away to care PersonLocation gargamel = new PersonLocation("Gargamel", 10); FactHandle gargamelFactHandle = ksession.insert(gargamel); ksession.fireAllRules(); // Uh oh, Gargamel moves closer gargamel.setDistance(5); ksession.update(gargamelFactHandle, gargamel); ksession.fireAllRules(); // logger.close(); ksession.dispose(); // Stateful rule session must always be disposed when finished }
@Test public void testSubruleSubsumption1() throws Exception { VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder(); Verifier verifier = vBuilder.newVerifier(); verifier.addResourcesToVerify( ResourceFactory.newClassPathResource("SubsumptantSubRules1.drl", getClass()), ResourceType.DRL); // for ( VerifierError error : verifier.getMissingClasses() ) { // System.out.println( error.getMessage() ); // } assertFalse(verifier.hasErrors()); boolean noProblems = verifier.fireAnalysis(); assertTrue(noProblems); Collection<Object> subsumptionList = ((VerifierImpl) verifier) .getKnowledgeSession() .getObjects(new ClassObjectFilter(Subsumption.class)); int count = 0; for (Object object : subsumptionList) { // System.out.println( " * " + ((Subsumption) object) ); if (((VerifierComponent) ((Subsumption) object).getLeft()) .getVerifierComponentType() .equals(VerifierComponentType.SUB_RULE)) { // System.out.println( " ** " + ((SubRule) ((Subsumption) // object).getLeft()).getItems() + " - " + ((SubRule) ((Subsumption) // object).getRight()).getItems() ); count++; } } assertEquals(2, count); verifier.dispose(); }
@Test public void testMVELForLoop() throws Exception { // JBRULES-3717 String str = "rule demo\n" + "dialect \"mvel\"\n" + "when\n" + "then\n" + " for ( int i = 1; i <= 3; i++ ) {\n" + " insert( \"foo\" + i );\n" + " }\n" + "end"; KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(); builder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); if (builder.hasErrors()) { throw new RuntimeException(builder.getErrors().toString()); } }
@Test public void testGlobal() throws Exception { Options xjcOpts = new Options(); xjcOpts.setSchemaLanguage(Language.XMLSCHEMA); KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); JaxbConfiguration jaxbConf = KnowledgeBuilderFactory.newJaxbConfiguration(xjcOpts, "xsd"); kbuilder.add( ResourceFactory.newClassPathResource("order.xsd", getClass()), ResourceType.XSD, jaxbConf); assertFalse(kbuilder.hasErrors()); kbuilder.add( ResourceFactory.newClassPathResource("test_Jaxb.drl", getClass()), ResourceType.DRL); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); assertFalse(kbuilder.hasErrors()); assertFalse(kbuilder.hasErrors()); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); KnowledgeRuntimeCommand setGlobalStage = PipelineFactory.newStatefulKnowledgeSessionSetGlobal("order"); JAXBContext jaxbCtx = KnowledgeBuilderHelper.newJAXBContext( jaxbConf.getClasses().toArray(new String[jaxbConf.getClasses().size()]), kbase); Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); Transformer transformer = PipelineFactory.newJaxbFromXmlTransformer(unmarshaller); transformer.setReceiver(setGlobalStage); Pipeline pipeline = PipelineFactory.newStatefulKnowledgeSessionPipeline(ksession); pipeline.setReceiver(transformer); String xml = StringUtils.readFileAsString( new InputStreamReader(getClass().getResourceAsStream("order.xml"))); ResultHandlerImpl resultHandler = new ResultHandlerImpl(); pipeline.insert(xml, resultHandler); // now round trip that global Action executeResult = PipelineFactory.newExecuteResultHandler(); Action assignAsResult = PipelineFactory.newAssignObjectAsResult(); assignAsResult.setReceiver(executeResult); // transformer = PipelineFactory.newXStreamToXmlTransformer( xstream ); Marshaller marshaller = jaxbCtx.createMarshaller(); transformer = PipelineFactory.newJaxbToXmlTransformer(marshaller); transformer.setReceiver(assignAsResult); KnowledgeRuntimeCommand getGlobalStage = PipelineFactory.newStatefulKnowledgeSessionGetGlobal(); getGlobalStage.setReceiver(transformer); pipeline = PipelineFactory.newStatefulKnowledgeSessionPipeline(ksession); pipeline.setReceiver(getGlobalStage); resultHandler = new ResultHandlerImpl(); pipeline.insert("order", resultHandler); assertEqualsIgnoreWhitespace(xml, (String) resultHandler.getObject()); }
@Test public void testDynamicAddRule() { // DROOLS-17 String str = "import org.drools.integrationtests.MiscTest2.A\n" + "rule r1 when\n" + " $a : A( f1 == 1 )\n" + "then\n" + "end\n" + "\n" + "rule r2 when\n" + " $a : A( f2 == 1 )\n" + "then\n" + "end\n" + "\n" + "rule r3 when\n" + " $a : A( f3 == 1 )" + "then\n" + "end"; String str2 = "import org.drools.integrationtests.MiscTest2.A\n" + "rule r4 when\n" + " $a : A( f2 == 1, f4 == 1 )" + "then\n" + "end"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { fail(kbuilder.getErrors().toString()); } KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); FactHandle fh = ksession.insert(new A(1, 1, 1, 1)); ksession.fireAllRules(); kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newByteArrayResource(str2.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { fail(kbuilder.getErrors().toString()); } kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); ksession.fireAllRules(); // this second insert forces the regeneration of the otnIds ksession.insert(new A(2, 2, 2, 2)); LeftTuple leftTuple = ((DefaultFactHandle) fh).getFirstLeftTuple(); ObjectTypeNode.Id letTupleOtnId = leftTuple.getLeftTupleSink().getLeftInputOtnId(); leftTuple = leftTuple.getLeftParentNext(); while (leftTuple != null) { assertTrue(letTupleOtnId.before(leftTuple.getLeftTupleSink().getLeftInputOtnId())); letTupleOtnId = leftTuple.getLeftTupleSink().getLeftInputOtnId(); leftTuple = leftTuple.getLeftParentNext(); } }