org.kie.internal.command.CommandFactory Java Examples

The following examples show how to use org.kie.internal.command.CommandFactory. 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: MoreBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 7 votes vote down vote up
@Test
public void testQuery() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("org/drools/compiler/integrationtests/simple_query_test.drl"), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ksession = createKnowledgeSession(kbase);
    
    ksession.insert( new Cheese( "stinky", 5 ) );
    ksession.insert( new Cheese( "smelly", 7 ) );
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newQuery("numStinkyCheeses", "simple query"));
    Command<?> cmds = CommandFactory.newBatchExecution(commands);
    ExecutionResults result = (ExecutionResults) ksession.execute(cmds);
    assertNotNull(result, "Batch execution result is null!");

    Object queryResultsObject = result.getValue("numStinkyCheeses");
    assertTrue(queryResultsObject != null && queryResultsObject instanceof QueryResults, "Retrieved object is null or incorrect!");
    
    assertEquals( 1, ((QueryResults) queryResultsObject).size() );
}
 
Example #2
Source File: FireAllRulesCommandTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void zeroRulesFiredTest() {
    String str = "";
    str += "package org.drools.compiler.integrationtests \n";
    str += "import " + Cheese.class.getCanonicalName() + " \n";
    str += "rule StringRule \n";
    str += " when \n";
    str += " $c : Cheese() \n";
    str += " then \n";
    str += " System.out.println($c); \n";
    str += "end \n";

    StatelessKieSession ksession = getSession(str);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsert("not cheese"));
    commands.add(CommandFactory.newFireAllRules("num-rules-fired"));

    ExecutionResults results = ksession.execute(CommandFactory.newBatchExecution(commands));
    int fired = Integer.parseInt(results.getValue("num-rules-fired").toString());

    assertEquals(0, fired);
}
 
Example #3
Source File: SimpleBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test 
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testGetGlobalCommand() throws Exception {
    
    ksession.insert(new Integer(5));
    ksession.insert(new Integer(7));
    ksession.fireAllRules();
    ksession.setGlobal("globalCheeseCountry", "France");
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newGetGlobal( "globalCheeseCountry", "cheeseCountry" ));
    Command cmds = CommandFactory.newBatchExecution( commands );

    ExecutionResults result = (ExecutionResults) ksession.execute( cmds );
    assertNotNull(result, "GetGlobalCommand result is null!");
    Object global = result.getValue("cheeseCountry");
    assertNotNull(global, "Retrieved global fact is null!");
    assertEquals("France", global, "Retrieved global is not equal to 'France'.");
}
 
Example #4
Source File: SimpleBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test 
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testSetGlobalCommand() throws Exception {
    
    ksession.insert(new Integer(5));
    ksession.insert(new Integer(7));
    ksession.fireAllRules();
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newSetGlobal( "globalCheeseCountry", "France", true ));

    Command cmds = CommandFactory.newBatchExecution( commands );

    ExecutionResults result = (ExecutionResults) ksession.execute( cmds );
    assertNotNull(result);
    Object global = result.getValue("globalCheeseCountry");
    assertNotNull(global);
    assertEquals("France", global);
}
 
Example #5
Source File: SimpleBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testGetObjectCommand() throws Exception {
    
    String expected_1 = "expected_1";
    String expected_2 = "expected_2";
    FactHandle handle_1 = ksession.insert( expected_1 );
    FactHandle handle_2 = ksession.insert( expected_2 );
    ksession.fireAllRules();
    
    Object fact = ksession.getObject(handle_1);
    assertNotNull(fact);
    assertEquals(expected_1, fact);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newGetObject(handle_1, "out_1"));
    commands.add(CommandFactory.newGetObject(handle_2, "out_2"));
    Command cmds = CommandFactory.newBatchExecution( commands );
    
    ExecutionResults result = (ExecutionResults) ksession.execute( cmds );
    assertNotNull(result, "GetObjectCommand result is null!");

    assertEquals(expected_1, result.getValue("out_1"));
    assertEquals(expected_2, result.getValue("out_2"));
}
 
Example #6
Source File: RulesBasedRoutingStrategy.java    From mdw with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<String> determineWorkgroups(TaskTemplate taskTemplate, TaskInstance taskInstance) throws StrategyException {
    KieBase knowledgeBase = getKnowledgeBase();

    StatelessKieSession knowledgeSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<Object>();
    facts.add(getParameters());
    knowledgeSession.setGlobal("taskTemplate", taskTemplate);
    knowledgeSession.setGlobal("taskInstance", taskInstance);
    knowledgeSession.setGlobal("now", new Date());

    knowledgeSession.execute(CommandFactory.newInsertElements(facts));

    return taskInstance.getWorkgroups();
}
 
Example #7
Source File: FireAllRulesCommandTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void infiniteLoopTerminatesAtMaxTest() {
    String str = "";
    str += "package org.drools.compiler.integrationtests \n";
    str += "import " + Cheese.class.getCanonicalName() + " \n";
    str += "rule StringRule \n";
    str += " when \n";
    str += " $c : Cheese() \n";
    str += " then \n";
    str += " update($c); \n";
    str += "end \n";

    StatelessKieSession ksession = getSession(str);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsert(new Cheese("stilton")));
    FireAllRulesCommand farc = (FireAllRulesCommand) CommandFactory.newFireAllRules(10);
    farc.setOutIdentifier("num-rules-fired");
    commands.add(farc);

    ExecutionResults results = ksession.execute(CommandFactory.newBatchExecution(commands));
    int fired = Integer.parseInt(results.getValue("num-rules-fired").toString());

    assertEquals(10, fired);
}
 
Example #8
Source File: FireAllRulesCommandTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void oneRuleFiredWithDefinedMaxTest() {
    String str = "";
    str += "package org.drools.compiler.integrationtests \n";
    str += "import " + Cheese.class.getCanonicalName() + " \n";
    str += "rule StringRule \n";
    str += " when \n";
    str += " $c : Cheese() \n";
    str += " then \n";
    str += " System.out.println($c); \n";
    str += "end \n";

    StatelessKieSession ksession = getSession(str);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsert(new Cheese("stilton")));
    FireAllRulesCommand farc = (FireAllRulesCommand) CommandFactory.newFireAllRules(10);
    farc.setOutIdentifier("num-rules-fired");
    commands.add(farc);

    ExecutionResults results = ksession.execute(CommandFactory.newBatchExecution(commands));
    int fired = Integer.parseInt(results.getValue("num-rules-fired").toString());

    assertEquals(1, fired);
}
 
Example #9
Source File: RulesBasedPrioritizationStrategy.java    From mdw with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Date determineDueDate(TaskTemplate taskTemplate) throws StrategyException {

    TaskInstance taskInstance = new TaskInstance();  // for holding values

    // execute rules only once (results are stored in taskInstance)
    KieBase knowledgeBase = getKnowledgeBase();
    StatelessKieSession knowledgeSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<>();
    facts.add(getParameters());
    knowledgeSession.setGlobal("taskTemplate", taskTemplate);
    knowledgeSession.setGlobal("taskInstance", taskInstance);

    knowledgeSession.execute(CommandFactory.newInsertElements(facts));

    return Date.from(taskInstance.getDue());
}
 
Example #10
Source File: FireAllRulesCommandTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void oneRuleFiredTest() {
    String str = "";
    str += "package org.drools.compiler.integrationtests \n";
    str += "import " + Cheese.class.getCanonicalName() + " \n";
    str += "rule StringRule \n";
    str += " when \n";
    str += " $c : Cheese() \n";
    str += " then \n";
    str += " System.out.println($c); \n";
    str += "end \n";

    StatelessKieSession ksession = getSession(str);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsert(new Cheese("stilton")));
    commands.add(CommandFactory.newFireAllRules("num-rules-fired"));

    ExecutionResults results = ksession.execute(CommandFactory.newBatchExecution(commands));
    int fired = Integer.parseInt(results.getValue("num-rules-fired").toString());

    assertEquals(1, fired);
}
 
Example #11
Source File: SequentialTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicOperation() throws Exception {
    KieBase kbase = loadKnowledgeBase(kconf, "simpleSequential.drl");
    StatelessKieSession ksession = createStatelessKnowledgeSession( kbase );
    final List list = new ArrayList();
    ksession.setGlobal( "list",
                       list );

    final Person p1 = new Person( "p1",
                                  "stilton" );
    final Person p2 = new Person( "p2",
                                  "cheddar" );
    final Person p3 = new Person( "p3",
                                  "stilton" );

    final Cheese stilton = new Cheese( "stilton",
                                       15 );
    final Cheese cheddar = new Cheese( "cheddar",
                                       15 );


    ksession.execute( CommandFactory.newInsertElements( Arrays.asList( new Object[]{p1, stilton, p2, cheddar, p3} ) ) );

    assertEquals( 3,
                  list.size() );
}
 
Example #12
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertObject() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "import org.drools.compiler.Cheese \n";
    str += "rule rule1 \n";
    str += "  when \n";
    str += "    $c : Cheese() \n";
    str += " \n";
    str += "  then \n";
    str += "    $c.setPrice( 30 ); \n";
    str += "end\n";
    
    Cheese stilton = new Cheese( "stilton", 5 );
    
    final StatelessKieSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
    final ExecutableCommand cmd = (ExecutableCommand) CommandFactory.newInsert( stilton, "outStilton" );
    final BatchExecutionCommandImpl batch = new BatchExecutionCommandImpl(  Arrays.asList( new ExecutableCommand<?>[] { cmd } ) );
    
    final ExecutionResults result = ( ExecutionResults ) ksession.execute( batch );
    stilton = ( Cheese ) result.getValue( "outStilton" );
    assertEquals( 30,
                  stilton.getPrice() );
}
 
Example #13
Source File: UpdateTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testModifyCommand() {
    final String str =
            "rule \"sample rule\"\n" +
                    "   when\n" +
                    "   then\n" +
                    "       System.out.println(\"\\\"Hello world!\\\"\");\n" +
                    "end";

    final KieBase kbase = loadKnowledgeBaseFromString(str);
    final KieSession ksession = kbase.newKieSession();

    final Person p1 = new Person("John", "nobody", 25);
    ksession.execute(CommandFactory.newInsert(p1));
    final FactHandle fh = ksession.getFactHandle(p1);

    final Person p = new Person("Frank", "nobody", 30);
    final List<Setter> setterList = new ArrayList<Setter>();
    setterList.add(CommandFactory.newSetter("age", String.valueOf(p.getAge())));
    setterList.add(CommandFactory.newSetter("name", p.getName()));
    setterList.add(CommandFactory.newSetter("likes", p.getLikes()));

    ksession.execute(CommandFactory.newModify(fh, setterList));
}
 
Example #14
Source File: SimpleRuleBean.java    From servicemix with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
public void start() throws Exception {

    for (int i = 0; i < 10; i++) {
        Customer customer = customer();
        logger.info("------------------- START ------------------\n"
                + " KieSession fireAllRules. {}", customer);

        List<Command<?>> commands = new ArrayList<Command<?>>();

        commands.add(CommandFactory.newInsert(customer, "customer"));
        commands.add(CommandFactory.newFireAllRules("num-rules-fired"));

        ExecutionResults results = ksession.execute(CommandFactory
                .newBatchExecution(commands));

        int fired = Integer.parseInt(results.getValue("num-rules-fired")
                .toString());

        customer = (Customer)results.getValue("customer");

        logger.info("After rule rules-fired={} {} \n"
                        + "------------------- STOP ---------------------", fired,
                customer);
    }
}
 
Example #15
Source File: SimpleBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test 
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testInsertObjectCommand() throws Exception {
    
    String expected_1 = "expected_1";
    String expected_2 = "expected_2";
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsert(expected_1, "out_1"));
    commands.add(CommandFactory.newInsert(expected_2, "out_2"));
    Command cmds = CommandFactory.newBatchExecution( commands );
    
    ExecutionResults result = (ExecutionResults) ksession.execute( cmds );
    
    Object fact_1 = result.getValue("out_1");
    assertNotNull(fact_1);
    Object fact_2 = result.getValue("out_2");
    assertNotNull(fact_2);
    ksession.fireAllRules();

    Object [] expectedArr = {expected_1, expected_2};
    List<Object> expectedList = new ArrayList<Object>(Arrays.asList(expectedArr));
    
    Collection<? extends Object> factList = ksession.getObjects();
    assertTrue(factList.size() == expectedList.size(),
                          "Expected " + expectedList.size() + " objects but retrieved " + factList.size());
    for( Object fact : factList ) {
       if( expectedList.contains(fact) ) { 
           expectedList.remove(fact);
       }
    }
    assertTrue(expectedList.isEmpty(), "Retrieved object list did not contain expected objects.");
}
 
Example #16
Source File: BusinessRulesBean.java    From iot-ocp with Apache License 2.0 5 votes vote down vote up
public Measure processRules(@Body Measure measure) {
	
	KieServicesConfiguration config = KieServicesFactory.newRestConfiguration(
			kieHost, kieUser,
			kiePassword);
	
	Set<Class<?>> jaxBClasses = new HashSet<Class<?>>();
	jaxBClasses.add(Measure.class);
	
	config.addJaxbClasses(jaxBClasses);
	config.setMarshallingFormat(MarshallingFormat.JAXB);
	RuleServicesClient client = KieServicesFactory.newKieServicesClient(config)
			.getServicesClient(RuleServicesClient.class);

       List<Command<?>> cmds = new ArrayList<Command<?>>();
	KieCommands commands = KieServices.Factory.get().getCommands();
	cmds.add(commands.newInsert(measure));
	
    GetObjectsCommand getObjectsCommand = new GetObjectsCommand();
    getObjectsCommand.setOutIdentifier("objects");

	
	cmds.add(commands.newFireAllRules());
	cmds.add(getObjectsCommand);
	BatchExecutionCommand myCommands = CommandFactory.newBatchExecution(cmds,
			"DecisionTableKS");
	ServiceResponse<ExecutionResults> response = client.executeCommandsWithResults("iot-ocp-businessrules-service", myCommands);
			
	List responseList = (List) response.getResult().getValue("objects");
	
	Measure responseMeasure = (Measure) responseList.get(0);
	
	return responseMeasure;

}
 
Example #17
Source File: Utils.java    From servicemix with Apache License 2.0 5 votes vote down vote up
public void insertAndFireAll(Exchange exchange) {
    final Message in = exchange.getIn();
    final Object body = in.getBody();

    final List<Command<?>> commands = new ArrayList<Command<?>>(2);
    commands.add(CommandFactory.newInsert(body));
    commands.add(CommandFactory.newFireAllRules());

    Command<?> batch = CommandFactory.newBatchExecution(commands);
    in.setBody(batch);
}
 
Example #18
Source File: DroolsExecutor.java    From mdw with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object execute(Asset rulesAsset, Operand input) throws ExecutionException {

    ClassLoader packageClassLoader = null;
    if (input.getContext() != null && input.getContext().getPackage() != null)
        packageClassLoader = input.getContext().getPackage().getClassLoader();
    if (packageClassLoader == null) // fall back to rules asset pkg classloader
        packageClassLoader = PackageCache.getPackage(rulesAsset.getPackageName()).getClassLoader();

    KnowledgeBaseAsset kbAsset = DroolsKnowledgeBaseCache
            .getKnowledgeBaseAsset(rulesAsset.getName(), null, packageClassLoader);
    if (kbAsset == null) {
        throw new ExecutionException("Cannot load KnowledgeBase asset: "
                + rulesAsset.getPackageName() + "/" + rulesAsset.getLabel());
    }

    KieBase knowledgeBase = kbAsset.getKnowledgeBase();

    StatelessKieSession kSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<Object>();
    if (input.getInput() != null) {
        facts.add(input.getInput()); // direct access
        if (input.getInput() instanceof Jsonable)
            facts.add(((Jsonable)input.getInput()).getJson());
    }

    kSession.setGlobal("operand", input);
    kSession.execute(CommandFactory.newInsertElements(facts));
    return input.getResult();
}
 
Example #19
Source File: Utils.java    From servicemix with Apache License 2.0 5 votes vote down vote up
/**
 * Create commands for Drools engine.
 *
 * @param body {@link org.apache.camel.Exchange}
 */
public Command<ExecutionResults> insertAndFireAll(final Customer body) {

    Command<?> insert = CommandFactory.newInsert(body, "customer");

    @SuppressWarnings("unchecked")
    Command<ExecutionResults> batch = CommandFactory
            .newBatchExecution(Arrays.asList(insert));

    return batch;
}
 
Example #20
Source File: SimpleBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test 
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testGetObjectsCommand() throws Exception {
    
    String expected_1 = "expected_1";
    String expected_2 = "expected_2";
    FactHandle handle_1 = ksession.insert( expected_1 );
    FactHandle handle_2 = ksession.insert( expected_2 );
    ksession.fireAllRules();
    
    Object object = ksession.getObject(handle_1);
    assertNotNull(object);
    assertEquals(expected_1, object);
    object = ksession.getObject(handle_2);
    assertNotNull(object);
    assertEquals(expected_2, object);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newGetObjects("out_list"));
    Command cmds = CommandFactory.newBatchExecution( commands );
    
    ExecutionResults result = (ExecutionResults) ksession.execute( cmds );
    assertNotNull(result, "GetObjectsCommand result is null!");

    List<Object> objectList = (List) result.getValue("out_list");
    boolean b = objectList != null && ! objectList.isEmpty();
    assertTrue(b, "Retrieved object list is null or empty!");

    Collection<? extends Object> factList = ksession.getObjects();
    Object [] expectedArr = {expected_1, expected_2};
    List<Object> expectedList = new ArrayList<Object>(Arrays.asList(expectedArr));
    assertTrue(factList.size() == expectedList.size(),
                          "Expected " + expectedList.size() + " objects but retrieved " + factList.size());
    for( Object fact : factList ) {
       if( expectedList.contains(fact) ) { 
           expectedList.remove(fact);
       }
    }
    assertTrue(expectedList.isEmpty(), "Retrieved object list did not contain expected objects.");
}
 
Example #21
Source File: SimpleBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test 
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testInsertElementsCommand() throws Exception {
    
    String expected_1 = "expected_1";
    String expected_2 = "expected_2";
    Object [] expectedArr = {expected_1, expected_2};
    Collection<Object> factCollection = Arrays.asList(expectedArr);
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsertElements(factCollection, "out_list", true, null));
    Command cmds = CommandFactory.newBatchExecution( commands );
    
    ExecutionResults result = (ExecutionResults) ksession.execute( cmds );
    
    Collection<? extends Object> outList = (Collection<? extends Object>) result.getValue("out_list");
    assertNotNull(outList);
    ksession.fireAllRules();

    List<Object> expectedList = new ArrayList<Object>(Arrays.asList(expectedArr));
    
    Collection<? extends Object> factList = ksession.getObjects();
    assertTrue(factList.size() == expectedList.size(),
                          "Expected " + expectedList.size() + " objects but retrieved " + factList.size());
    for( Object fact : factList ) {
       if( expectedList.contains(fact) ) { 
           expectedList.remove(fact);
       }
    }
    assertTrue(expectedList.isEmpty(), "Retrieved object list did not contain expected objects.");
}
 
Example #22
Source File: EnableAuditLogCommandTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnableAuditLogCommand() throws Exception {

    String str = "";
    str += "package org.drools.compiler.integrationtests \n";
    str += "import " + Cheese.class.getCanonicalName() + " \n";
    str += "rule StringRule \n";
    str += " when \n";
    str += " $c : Cheese() \n";
    str += " then \n";
    str += " System.out.println($c); \n";
    str += "end \n";

    KieSession kSession = new KieHelper().addContent( str, ResourceType.DRL )
                                         .build().newKieSession();

    List<Command> commands = new ArrayList<Command>();
    commands.add( CommandFactory.newEnableAuditLog( auditFileDir, auditFileName ) );
    commands.add( CommandFactory.newInsert( new Cheese() ) );
    commands.add( CommandFactory.newFireAllRules() );
    kSession.execute( CommandFactory.newBatchExecution( commands ) );
    kSession.dispose();

    File file = new File( auditFileDir + File.separator + auditFileName + ".log" );

    assertTrue( file.exists() );

}
 
Example #23
Source File: MoreBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testFireAllRules() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("org/drools/compiler/integrationtests/drl/test_ImportFunctions.drl"), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ksession = createKnowledgeSession(kbase);

    final Cheese cheese = new Cheese("stilton", 15);
    ksession.insert(cheese);
    List<?> list = new ArrayList();
    ksession.setGlobal("list", list);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newFireAllRules("fired"));
    Command<?> cmds = CommandFactory.newBatchExecution(commands);
    ExecutionResults result = (ExecutionResults) ksession.execute(cmds);
    assertNotNull(result, "Batch execution result is null!");

    Object firedObject = result.getValue("fired");
    assertTrue( firedObject != null && firedObject instanceof Integer, "Retrieved object is null or incorrect!");
    assertEquals(4, firedObject);

    list = (List<?>) ksession.getGlobal("list");
    assertEquals(4, list.size());

    assertEquals("rule1", list.get(0));
    assertEquals("rule2", list.get(1));
    assertEquals("rule3", list.get(2));
    assertEquals("rule4", list.get(3));
}
 
Example #24
Source File: DynamicRulesChangesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public List<String> call() throws Exception {
    final List<String> events = new ArrayList<String>();

    try {
        KieSession ksession = createKnowledgeSession(kbase);
        ksession.setGlobal("events", events);

        Room room1 = new Room("Room 1");
        Fire fire1 = new Fire(room1);

        // phase 1
        List<Command> cmds = new ArrayList<Command>();
        cmds.add(CommandFactory.newInsert(room1, "room1"));
        cmds.add(CommandFactory.newInsert(fire1, "fire1"));
        cmds.add(CommandFactory.newFireAllRules());
        ksession.execute(CommandFactory.newBatchExecution(cmds));
        assertEquals(1, events.size());

        // phase 2
        cmds = new ArrayList<Command>();
        cmds.add(CommandFactory.newInsert(new Sprinkler(room1), "sprinkler1"));
        cmds.add(CommandFactory.newFireAllRules());
        ksession.execute(CommandFactory.newBatchExecution(cmds));
        assertEquals(2, events.size());

        // phase 3
        cmds = new ArrayList<Command>();
        cmds.add(CommandFactory.newDelete(ksession.getFactHandle(fire1)));
        cmds.add(CommandFactory.newFireAllRules());
        ksession.execute(CommandFactory.newBatchExecution(cmds));
    } catch (Exception e) {
        System.err.println("Exception in thread " + Thread.currentThread().getName() + ": " + e.getLocalizedMessage());
        throw e;
    }

    return events;
}
 
Example #25
Source File: FireAllRulesCommandTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void fiveRulesFiredTest() {
    String str = "";
    str += "package org.drools.compiler.integrationtests \n";
    str += "import " + Cheese.class.getCanonicalName() + " \n";
    str += "rule StringRule \n";
    str += " when \n";
    str += " $c : Cheese() \n";
    str += " then \n";
    str += " System.out.println($c); \n";
    str += "end \n";

    StatelessKieSession ksession = getSession(str);

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsert(new Cheese("stilton")));
    commands.add(CommandFactory.newInsert(new Cheese("gruyere")));
    commands.add(CommandFactory.newInsert(new Cheese("cheddar")));
    commands.add(CommandFactory.newInsert(new Cheese("stinky")));
    commands.add(CommandFactory.newInsert(new Cheese("limburger")));
    commands.add(CommandFactory.newFireAllRules("num-rules-fired"));

    ExecutionResults results = ksession.execute(CommandFactory.newBatchExecution(commands));
    int fired = Integer.parseInt(results.getValue("num-rules-fired").toString());

    assertEquals(5, fired);
}
 
Example #26
Source File: SequentialTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedSegment() throws Exception {
    // BZ-1228313
    String str =
            "package org.drools.compiler.test\n" +
            "import \n" + Message.class.getCanonicalName() + ";" +
            "rule R1 when\n" +
            "    $s : String()\n" +
            "    $m : Message()\n" +
            "    $i : Integer( this < $s.length )\n" +
            "then\n" +
            "    modify($m) { setMessage($s) };\n" +
            "end\n" +
            "\n" +
            "rule R2 when\n" +
            "    $s : String()\n" +
            "    $m : Message()\n" +
            "    $i : Integer( this > $s.length )\n" +
            "then\n" +
            "end\n";

    StatelessKieSession ksession = new KieHelper().addContent( str, ResourceType.DRL )
                                                  .build( SequentialOption.YES )
                                                  .newStatelessKieSession();

    ksession.execute( CommandFactory.newInsertElements(Arrays.asList("test", new Message(), 3, 5)));
}
 
Example #27
Source File: SessionsPoolTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatelessSequential() {
    // DROOLS-3228
    String drl =
            "import " + AtomicInteger.class.getCanonicalName() + ";\n" +
            "global java.util.List list\n" +
            "rule R1 when\n" +
            "  String()\n" +
            "  Integer()\n" +
            "then\n" +
            "  list.add(\"OK\");\n" +
            "end";

    KieBase kbase = new KieHelper().addContent( drl, ResourceType.DRL ).build( SequentialOption.YES );
    KieSessionsPool pool = kbase.newKieSessionsPool( 1 );

    StatelessKieSession ksession = pool.newStatelessKieSession();

    List<String> list = new ArrayList<>();

    List<Command> commands = new ArrayList<>(5);
    commands.add(CommandFactory.newSetGlobal("list", list));
    commands.add(CommandFactory.newInsert("test"));
    commands.add(CommandFactory.newInsert(1));
    commands.add(CommandFactory.newFireAllRules());
    ksession.execute(CommandFactory.newBatchExecution(commands));

    assertEquals(1, list.size());

    list.clear();

    ksession.execute(CommandFactory.newBatchExecution(commands));

    assertEquals(1, list.size());

    pool.shutdown();
}
 
Example #28
Source File: AgendaFilterTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testActivationCancelled() {
    // JBRULES-3376
    String drl = "package org.jboss.qa.brms.agendafilter\n" +
            "declare CancelFact\n" +
            "   cancel : boolean = true\n" +
            "end\n" +
            "rule NoCancel\n" +
            "   ruleflow-group \"rfg\"\n" +
            "   when\n" +
            "       $fact : CancelFact ( cancel == false )\n" +
            "   then\n" +
            "       System.out.println(\"No cancel...\");\n" +
            "       modify ($fact) {\n" +
            "           setCancel(true);\n" +
            "       }\n" +
            "end\n" +
            "rule PresenceOfBothFacts\n" +
            "   ruleflow-group \"rfg\"\n" +
            "   salience -1\n" +
            "   when\n" +
            "       $fact1 : CancelFact( cancel == false )\n" +
            "       $fact2 : CancelFact( cancel == true )\n" +
            "   then\n" +
            "       System.out.println(\"Both facts!\");\n" +
            "end\n" +
            "rule PresenceOfFact\n" +
            "   ruleflow-group \"rfg\"\n" +
            "   when\n" +
            "       $fact : CancelFact( )\n" +
            "   then\n" +
            "       System.out.println(\"We have a \" + ($fact.isCancel() ? \"\" : \"non-\") + \"cancelling fact!\");\n" +
            "end\n" +
            "rule Cancel\n" +
            "   ruleflow-group \"rfg\"\n" +
            "   when\n" +
            "       $fact : CancelFact ( cancel == true )\n" +
            "   then\n" +
            "       System.out.println(\"Cancel!\");\n" +
            "end";

    String rf = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" +
            "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" +
            "         xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
            "         xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" +
            "         type=\"RuleFlow\" name=\"flow\" id=\"bz761715\" package-name=\"org.jboss.qa.brms.agendafilter\" >\n" +
            "  <header>\n" +
            "  </header>\n" +
            "  <nodes>\n" +
            "    <start id=\"1\" name=\"Start\" x=\"16\" y=\"16\" width=\"48\" height=\"48\" />\n" +
            "    <ruleSet id=\"2\" name=\"Rule\" x=\"208\" y=\"16\" width=\"80\" height=\"48\" ruleFlowGroup=\"rfg\" />\n" +
            "    <actionNode id=\"3\" name=\"Script\" x=\"320\" y=\"16\" width=\"80\" height=\"48\" >\n" +
            "        <action type=\"expression\" dialect=\"java\" >System.out.println(\"Finishing process...\");</action>\n" +
            "    </actionNode>\n" +
            "    <end id=\"4\" name=\"End\" x=\"432\" y=\"16\" width=\"48\" height=\"48\" />\n" +
            "    <actionNode id=\"5\" name=\"Script\" x=\"96\" y=\"16\" width=\"80\" height=\"48\" >\n" +
            "        <action type=\"expression\" dialect=\"java\" >System.out.println(\"Starting process...\");</action>\n" +
            "    </actionNode>\n" +
            "  </nodes>\n" +
            "  <connections>\n" +
            "    <connection from=\"5\" to=\"2\" />\n" +
            "    <connection from=\"2\" to=\"3\" />\n" +
            "    <connection from=\"3\" to=\"4\" />\n" +
            "    <connection from=\"1\" to=\"5\" />\n" +
            "  </connections>\n" +
            "</process>";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL );
    kbuilder.add( ResourceFactory.newByteArrayResource(rf.getBytes()), ResourceType.DRF );

    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = kbase.newKieSession();

    ksession.addEventListener(new DebugAgendaEventListener());
    ksession.addEventListener(new DebugProcessEventListener());

    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newInsert(newCancelFact(ksession, false)));
    commands.add(CommandFactory.newInsert(newCancelFact(ksession, true)));
    commands.add(CommandFactory.newStartProcess("bz761715"));
    commands.add(new FireAllRulesCommand(new CancelAgendaFilter()));
    commands.add(new FireAllRulesCommand(new CancelAgendaFilter()));
    commands.add(new FireAllRulesCommand(new CancelAgendaFilter()));

    ksession.execute(CommandFactory.newBatchExecution(commands));
}
 
Example #29
Source File: DroolsActivity.java    From mdw with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void execute() throws ActivityException {

    String knowledgeBaseName = null;
    String knowledgeBaseVersion = null;
    try {
        knowledgeBaseName = getAttributeValueSmart(KNOWLEDGE_BASE);
        knowledgeBaseVersion = getAttributeValueSmart(KNOWLEDGE_BASE_ASSET_VERSION);
    }
    catch (PropertyException ex) {
        throw new ActivityException(ex.getMessage(), ex);
    }

    if (StringUtils.isBlank(knowledgeBaseName))
        throw new ActivityException("Missing attribute: " + KNOWLEDGE_BASE);

    KieBase knowledgeBase = getKnowledgeBase(knowledgeBaseName, knowledgeBaseVersion);
    if (knowledgeBase == null)
        throw new ActivityException("Cannot load KnowledgeBase: " + knowledgeBaseName);

    // TODO stateful session option
    StatelessKieSession kSession = knowledgeBase.newStatelessKieSession();

    List<Object> facts = new ArrayList<>();
    Map<String,Object> values = new HashMap<>();

    for (VariableInstance variableInstance : getParameters()) {
        Object value = getVariableValue(variableInstance.getName());
        values.put(variableInstance.getName(), value);
    }
    logDebug("Drools values: " + values);

    facts.add(values);
    logDebug("Drools facts: " + facts);

    setGlobalValues(kSession);

    kSession.execute(CommandFactory.newInsertElements(facts));

    String temp = getAttributeValue(OUTPUTDOCS);
    setOutputDocuments(getAttributes().containsKey(OUTPUTDOCS) ? getAttributes().getList(OUTPUTDOCS).toArray(new String[0]) : new String[0]);

    // TODO handle document variables
    Process processVO = getProcessDefinition();
    for (Variable variable : processVO.getVariables()) {
        Object newValue = values.get(variable.getName());
        if (newValue != null)
            setVariableValue(variable.getName(), variable.getType(), newValue);
    }
}
 
Example #30
Source File: DroolsStatelessSession.java    From Decision with Apache License 2.0 4 votes vote down vote up
public Results fireRules(List data) {
    Results res = new Results();

    KieCommands commands = kServices.getCommands();

    List<Command> cmds = new ArrayList<Command>();

    cmds.add(commands.newInsertElements(data));
    cmds.add(CommandFactory.newFireAllRules());
    cmds.add(CommandFactory.newQuery(QUERY_RESULT, QUERY_NAME));

    ExecutionResults er = session.execute(commands.newBatchExecution(cmds));

    this.addResults(res.getResults(), er, QUERY_RESULT);

    return res;
}