public static final void main(String[] args) { try { // load up the knowledge base KnowledgeBase kbase = readKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(ksession, "test", 1000); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new WSHumanTaskHandler()); // start a new process instance by setup of a Person and Request. Person person = new Person("erics", "Eric D. Schabell"); person.setAge(43); Request request = new Request("1"); request.setPersonId("erics"); request.setAmount(1999); ksession.insert(person); // put them in the Map to be passed to the startProcess. Map<String, Object> params = new HashMap<String, Object>(); params.put("person", person); params.put("request", request); // Fire it up! WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess("org.jbpm.demo.rulenode", params); ksession.insert(processInstance); ksession.fireAllRules(); // Finished, clean up the logger. System.out.println("Process Ended."); logger.close(); } catch (Throwable t) { t.printStackTrace(); } }
/** * Initialize the Drools Engine and fetch the rules from Guvnor * * @param URL - The URL String to the guvnor rules * @throws TransformerException * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public static void Init(String URL) throws TransformerException, ParserConfigurationException, IOException, SAXException, Exception { setRemoteAddress(URL); // readKnowledgeBase() for reading a local drl file kbase = readRemoteKnowledgeBase(); ksession = kbase.newStatefulKnowledgeSession(); logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test"); }
private void initializeSession() { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(new ClassPathResource("InsuranceProcessV1.bpmn"), ResourceType.BPMN2); if (kbuilder.hasErrors()) { KnowledgeBuilderErrors errors = kbuilder.getErrors(); for (KnowledgeBuilderError error : errors) { System.out.println(">>> Error:" + error.getMessage()); } throw new IllegalStateException(">>> Knowledge couldn't be parsed! "); } KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); session = kbase.newStatefulKnowledgeSession(); KnowledgeRuntimeLoggerFactory.newConsoleLogger(session); session.addEventListener( new DefaultAgendaEventListener() { @Override public void afterRuleFlowGroupActivated( org.drools.event.rule.RuleFlowGroupActivatedEvent event) { session.fireAllRules(); } }); // Registers an independent mocked work item handler for each task present // in the process. PatientDataServiceWorkItemHandler patientDataHandler = new PatientDataServiceWorkItemHandler(); session.getWorkItemManager().registerWorkItemHandler("Gather Patient Data", patientDataHandler); InsuranceServiceWorkItemHandler insuranceServiceHandler = new InsuranceServiceWorkItemHandler(); session .getWorkItemManager() .registerWorkItemHandler("Insurance Service", insuranceServiceHandler); CompanyGatewayWorkItemHandler companyGatewayHandler = new CompanyGatewayWorkItemHandler(); session .getWorkItemManager() .registerWorkItemHandler("External Insurance Company Service", companyGatewayHandler); RatesServiceWorkItemHandler ratesServiceHandler = new RatesServiceWorkItemHandler(); session.getWorkItemManager().registerWorkItemHandler("Rates Service", ratesServiceHandler); InvoiceServiceWorkItemHandler invoiceServiceHandler = new InvoiceServiceWorkItemHandler(); session.getWorkItemManager().registerWorkItemHandler("Invoice Service", invoiceServiceHandler); }
private static ComputerComparison drlComparison( ArrayList<Computer> computerList, String[] drlFiles, int log) { // Comparison obj ComputerComparison comparR = null; // knowlegesession StatefulKnowledgeSession ksession; // log KnowledgeRuntimeLogger logger; int logSub = 0; // fire all the rules, give no sympathy for (String s : drlFiles) { comparR = ComputerComparison.makeComparisonObj(s, computerList); ksession = comparR.getSession(); logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "log" + log + "_" + logSub); ksession.fireAllRules(); logger.close(); logSub++; } return comparR; }
public static final void main(String[] args) { try { // load up the knowledge base KnowledgeBase kbase = readKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(ksession, "test", 1000); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new WSHumanTaskHandler()); // start a new process instance Map<String, Object> params = new HashMap<String, Object>(); List<String> list = new ArrayList<String>(); list.add("krisv"); list.add("john doe"); list.add("superman"); params.put("list", list); ksession.startProcess("com.sample.multipleinstance", params); logger.close(); } catch (Throwable t) { t.printStackTrace(); } }
public void initKsession() { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("base.drl", getClass()), ResourceType.DRL); kbuilder.add( ResourceFactory.newClassPathResource("key-handlers.drl", getClass()), ResourceType.DRL); kbuilder.add(ResourceFactory.newClassPathResource("pacman.drl", getClass()), ResourceType.DRL); kbuilder.add(ResourceFactory.newClassPathResource("monster.drl", getClass()), ResourceType.DRL); if (kbuilder.hasErrors()) { System.out.println(kbuilder.getErrors()); } KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(kbuilder.getKnowledgePackages()); this.ksession = kbase.newStatefulKnowledgeSession(); this.pacMan = new PacMan(); this.pacMan.setSpeed(3); this.ksession.insert(this.pacMan); Monster monster = new Monster(); monster.setSpeed(5); this.ksession.insert(monster); this.ksession.insert(new Score()); KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(this.ksession, "pacman.log", 3000); Location pacLocation = new Location(this.pacMan, 1, 5); Location monLocation = new Location(monster, 10, 5); this.ksession.insert(pacLocation); this.ksession.insert(monLocation); Tick tick = new Tick(0); this.ksession.insert(tick); }
public static final void main(String[] args) { try { setupTaskServer(); // load up the knowledge base KnowledgeBase kbase = readKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession); ksession .getWorkItemManager() .registerWorkItemHandler("Human Task", new CommandBasedWSHumanTaskHandler(ksession)); // start a new process instance Map<String, Object> params = new HashMap<String, Object>(); params.put("userId", "krisv"); params.put("s", "Need a new laptop computer"); ksession.startProcess("UserTask", params); SystemEventListenerFactory.setSystemEventListener(new SystemEventListener()); TaskClient taskClient = new TaskClient( new MinaTaskClientConnector( "MinaConnector", new MinaTaskClientHandler(SystemEventListenerFactory.getSystemEventListener()))); taskClient.connect("127.0.0.1", 9123); Thread.sleep(1000); // sleep to allow notification to be sent for deadline start Thread.sleep(6000); // Assert.assertEquals(4, wiser.getMessages().size()); // Assert.assertEquals("*****@*****.**", // wiser.getMessages().get(0).getEnvelopeReceiver()); // Assert.assertEquals("*****@*****.**", // wiser.getMessages().get(1).getEnvelopeReceiver()); // Assert.assertEquals("Task is ready for mike", // wiser.getMessages().get(0).getMimeMessage().getSubject()); // wait another few seconds to trigger complete deadline Thread.sleep(4000); // Assert.assertEquals(6, wiser.getMessages().size()); // Assert.assertEquals("*****@*****.**", // wiser.getMessages().get(2).getEnvelopeReceiver()); // Assert.assertEquals("*****@*****.**", // wiser.getMessages().get(3).getEnvelopeReceiver()); // Assert.assertEquals("Not completedTask is ready for mike", // wiser.getMessages().get(4).getMimeMessage().getSubject()); BlockingTaskSummaryResponseHandler taskSummaryHandler = new BlockingTaskSummaryResponseHandler(); taskClient.getTasksAssignedAsPotentialOwner("mike", "en-UK", taskSummaryHandler); TaskSummary task1 = taskSummaryHandler.getResults().get(0); BlockingTaskOperationResponseHandler taskOperationHandler = new BlockingTaskOperationResponseHandler(); taskClient.start(task1.getId(), "mike", taskOperationHandler); taskOperationHandler.waitTillDone(1000); taskOperationHandler = new BlockingTaskOperationResponseHandler(); Map<String, Object> results = new HashMap<String, Object>(); results.put("comment", "Agreed, existing laptop needs replacing"); results.put("outcome", "Accept"); ContentData contentData = new ContentData(); contentData.setAccessType(AccessType.Inline); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out; try { out = new ObjectOutputStream(bos); out.writeObject(results); out.close(); contentData = new ContentData(); contentData.setContent(bos.toByteArray()); contentData.setAccessType(AccessType.Inline); } catch (IOException e) { e.printStackTrace(); } taskClient.complete(task1.getId(), "mike", contentData, taskOperationHandler); taskOperationHandler.waitTillDone(1000); Thread.sleep(1000); logger.close(); } catch (Throwable t) { t.printStackTrace(); } wiser.stop(); System.exit(0); }
public static final void main(String[] args) { try { // Carrega as regras KnowledgeBase kbase = readKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test"); // Cria os dados Paciente pacienteNormoglicemico = new Paciente("Renato", 80.0, new ArrayList<Fato>()); Paciente pacienteHipoglicemiaGrave = new Paciente(); pacienteHipoglicemiaGrave.setNome("Maria"); pacienteHipoglicemiaGrave.setGlicemia(35.0); pacienteHipoglicemiaGrave.adicionaFato(Fato.CONSCIENTE); pacienteHipoglicemiaGrave.adicionaFato(Fato.CONFUSO); Paciente pacienteHipoglicemiaGrave2 = new Paciente(); pacienteHipoglicemiaGrave2.setNome("Jose"); pacienteHipoglicemiaGrave2.setGlicemia(20.0); pacienteHipoglicemiaGrave2.adicionaFato(Fato.CONSCIENTE); Paciente pacienteHipoglicemiaGrave3 = new Paciente(); pacienteHipoglicemiaGrave3.setNome("Roberta"); pacienteHipoglicemiaGrave3.setGlicemia(30.0); pacienteHipoglicemiaGrave3.adicionaFato(Fato.CONVULSAO); Paciente pacienteHipoglicemiaGrave4 = new Paciente(); pacienteHipoglicemiaGrave4.setNome("Diogo"); pacienteHipoglicemiaGrave4.setGlicemia(30.0); Paciente pacienteHipoglicemiaModerado1 = new Paciente(); pacienteHipoglicemiaModerado1.setNome("Adriana"); pacienteHipoglicemiaModerado1.setGlicemia(50.0); pacienteHipoglicemiaModerado1.adicionaFato(Fato.CONSCIENTE); pacienteHipoglicemiaModerado1.adicionaFato(Fato.CONFUSO); Paciente pacienteHipoglicemiaModerado2 = new Paciente(); pacienteHipoglicemiaModerado2.setNome("Tiago"); pacienteHipoglicemiaModerado2.setGlicemia(50.0); Paciente pacienteHipoglicemiaLeve1 = new Paciente(); pacienteHipoglicemiaLeve1.setNome("Agnaldo"); pacienteHipoglicemiaLeve1.setGlicemia(50.0); pacienteHipoglicemiaLeve1.adicionaFato(Fato.CONSCIENTE); Paciente pacienteHiperglicemiaEIntercorrencia1 = new Paciente(); pacienteHiperglicemiaEIntercorrencia1.setNome("Joao"); pacienteHiperglicemiaEIntercorrencia1.setGlicemia(150.0); pacienteHiperglicemiaEIntercorrencia1.adicionaFato(Fato.CONSCIENTE); pacienteHiperglicemiaEIntercorrencia1.adicionaFato(Fato.INFECCAO); Paciente pacienteHiperglicemiaEIntercorrencia2 = new Paciente(); pacienteHiperglicemiaEIntercorrencia2.setNome("Katia"); pacienteHiperglicemiaEIntercorrencia2.setGlicemia(150.0); Paciente pacienteHiperglicemiaEIntercorrencia3 = new Paciente(); pacienteHiperglicemiaEIntercorrencia3.setNome("Samuel"); pacienteHiperglicemiaEIntercorrencia3.setGlicemia(230.0); Paciente pacienteHiperglicemiaSemIntercorrencia1 = new Paciente(); pacienteHiperglicemiaSemIntercorrencia1.setNome("Gabriela"); pacienteHiperglicemiaSemIntercorrencia1.setGlicemia(150.0); pacienteHiperglicemiaSemIntercorrencia1.adicionaFato(Fato.CONSCIENTE); Paciente pacienteHiperglicemiaSemIntercorrencia2 = new Paciente(); pacienteHiperglicemiaSemIntercorrencia2.setNome("Julio"); pacienteHiperglicemiaSemIntercorrencia2.setGlicemia(230.0); pacienteHiperglicemiaSemIntercorrencia2.adicionaFato(Fato.CONSCIENTE); ksession.insert(pacienteNormoglicemico); ksession.insert(pacienteHipoglicemiaGrave); ksession.insert(pacienteHipoglicemiaGrave2); ksession.insert(pacienteHipoglicemiaGrave3); ksession.insert(pacienteHipoglicemiaGrave4); ksession.insert(pacienteHipoglicemiaModerado1); ksession.insert(pacienteHipoglicemiaModerado2); ksession.insert(pacienteHipoglicemiaLeve1); ksession.insert(pacienteHiperglicemiaEIntercorrencia1); ksession.insert(pacienteHiperglicemiaEIntercorrencia2); ksession.insert(pacienteHiperglicemiaEIntercorrencia3); ksession.insert(pacienteHiperglicemiaSemIntercorrencia1); ksession.insert(pacienteHiperglicemiaSemIntercorrencia2); // Executa as regras ksession.fireAllRules(); logger.close(); } catch (Throwable t) { t.printStackTrace(); } }
@Test public void testRepetitiveUpdatesOnSameFacts() throws Exception { // JBRULES-3320 // Using the concept of shift assignments covering interval requirements (staffing required for // a given interval) List notCovered = new ArrayList(); // Interval requirements not covered by any shift assignments List partiallyCovered = new ArrayList(); // Interval requirements partially covered by shift assignments (staffing // requirement partially met) List totallyCovered = new ArrayList(); // Interval requirements totally covered by shift assignments (staffing // requirement met or exceeded) // load up the knowledge base KnowledgeBase kbase = loadKnowledgeBase("test_RepetitiveUpdatesOnSameFacts.drl"); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); ksession.setGlobal("totallyCovered", totallyCovered); ksession.setGlobal("partiallyCovered", partiallyCovered); ksession.setGlobal("notCovered", notCovered); KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test"); // Using 4 IntervalRequirement objects that never change during the execution of the test // Staffing required at interval 100 IntervalRequirement ir100 = new IntervalRequirement(100, 2); ksession.insert(ir100); // Staffing required at interval 101 IntervalRequirement ir101 = new IntervalRequirement(101, 2); ksession.insert(ir101); // Staffing required at interval 102 IntervalRequirement ir102 = new IntervalRequirement(102, 2); ksession.insert(ir102); // Staffing required at interval 103 IntervalRequirement ir103 = new IntervalRequirement(103, 2); ksession.insert(ir103); // Using a single ShiftAssignment object that will get updated multiple times during the // execution of the test ShiftAssignment sa = new ShiftAssignment(); sa.setShiftStartTime(100); FactHandle saHandle = null; // Intersects 1 interval totallyCovered.clear(); partiallyCovered.clear(); notCovered.clear(); sa.setShiftEndTime(101); System.out.println( "ShiftAssignment set from " + sa.getShiftStartTime() + " to " + sa.getShiftEndTime()); saHandle = ksession.insert(sa); ksession.fireAllRules(); assertEquals("notCovered with " + sa, 3, notCovered.size()); assertEquals("totallyCovered with " + sa, 0, totallyCovered.size()); assertEquals("partiallyCovered with " + sa, 1, partiallyCovered.size()); // Intersects 3 intervals totallyCovered.clear(); partiallyCovered.clear(); notCovered.clear(); sa.setShiftEndTime(103); System.out.println( "ShiftAssignment set from " + sa.getShiftStartTime() + " to " + sa.getShiftEndTime()); ksession.update(saHandle, sa); ksession.fireAllRules(); assertEquals( "notCovered with " + sa, 0, notCovered.size()); // this was fired in the previous scenario assertEquals("totallyCovered with " + sa, 0, totallyCovered.size()); assertEquals("partiallyCovered with " + sa, 3, partiallyCovered.size()); // Intersects 2 intervals totallyCovered.clear(); partiallyCovered.clear(); notCovered.clear(); sa.setShiftEndTime(102); System.out.println( "ShiftAssignment set from " + sa.getShiftStartTime() + " to " + sa.getShiftEndTime()); ksession.update(saHandle, sa); ksession.fireAllRules(); assertEquals("notCovered with " + sa, 1, notCovered.size()); // new uncovered scenario assertEquals("totallyCovered with " + sa, 0, totallyCovered.size()); assertEquals("partiallyCovered with " + sa, 2, partiallyCovered.size()); // Intersects 4 intervals totallyCovered.clear(); partiallyCovered.clear(); notCovered.clear(); sa.setShiftEndTime(104); System.out.println( "ShiftAssignment set from " + sa.getShiftStartTime() + " to " + sa.getShiftEndTime()); ksession.update(saHandle, sa); ksession.fireAllRules(); assertEquals("notCovered with " + sa, 0, notCovered.size()); assertEquals("totallyCovered with " + sa, 0, totallyCovered.size()); assertEquals("partiallyCovered with " + sa, 4, partiallyCovered.size()); // Intersects 1 interval totallyCovered.clear(); partiallyCovered.clear(); notCovered.clear(); sa.setShiftEndTime(101); System.out.println( "ShiftAssignment set from " + sa.getShiftStartTime() + " to " + sa.getShiftEndTime()); ksession.update(saHandle, sa); ksession.fireAllRules(); assertEquals("notCovered with " + sa, 3, notCovered.size()); assertEquals("totallyCovered with " + sa, 0, totallyCovered.size()); assertEquals("partiallyCovered with " + sa, 1, partiallyCovered.size()); ksession.dispose(); logger.close(); }
/** * Executes the rules to the service periods to calculate their deductions. This methods also * merges the service period to extended service period. * * @param request that contains the service periods to calculate. * @return the response of the extended service periods with calculated deductions (and also * earnings, mid-point etc.). * @throws IllegalArgumentException if the request is null. * @throws RuleServiceException if any error occurs when executing the rule. */ @Override public DeductionCalculationResponse execute(DeductionCalculationRequest request) throws RuleServiceException { // log the entrance String signature = CLASS_NAME + "#execute(DeductionCalculationRequest request)"; LoggingHelper.logEntrance( getLogger(), signature, new String[] {"request"}, new Object[] {request}); // validate the parameters ServiceHelper.checkNull(request, "request"); StatefulKnowledgeSession ksession = null; KnowledgeRuntimeLogger logger = null; try { // start new session and the file logger ksession = getKnowledgeBase().newStatefulKnowledgeSession(); logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, getKnowledgeLogFileName()); // Set global variables List<ExtendedServicePeriod> esps = new ArrayList<ExtendedServicePeriod>(); ksession.setGlobal(EXTENDED_SERVICE_PERIODS, esps); ksession.setGlobal( SERVICE_PERIOD_SPLIT_DATES, servicePeriodSplitDates == null ? Collections.EMPTY_LIST : servicePeriodSplitDates); // Populate facts for (ServicePeriod sp : request.getServicePeriods()) { ksession.insert(sp); } // Start deduction process ksession.startProcess("Deduction"); // Fire all rules ksession.fireAllRules(); // populate the final result DeductionCalculationResponse response = new DeductionCalculationResponse(); response.setExtendedServicePeriods(esps); ksession.dispose(); // log and return LoggingHelper.logExit(getLogger(), signature, new Object[] {response}); return response; } catch (RuntimeException e) { // log the exception and wrap it to RuleServiceException throw LoggingHelper.logException( getLogger(), signature, new RuleServiceException("Unable to complete rule execution.", e)); } finally { // closes the resources if (logger != null) { logger.close(); } if (ksession != null) { ksession.dispose(); } } }