Java Code Examples for org.kie.api.runtime.KieSession#execute()

The following examples show how to use org.kie.api.runtime.KieSession#execute() . 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: 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 2
Source File: ExecuteCommand.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public ExecutionResults execute(Context context) {
    KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );
    ExecutionResults kresults = ksession.execute(this.command);
    if ( this.outIdentifier != null ) {
        ((RegistryContext) context).lookup( ExecutionResultImpl.class ).setResult( this.outIdentifier, kresults );
    }
    if (disconnected) {
        ExecutionResultImpl disconnectedResults = new ExecutionResultImpl();
        HashMap<String, Object> disconnectedHandles = new HashMap<String, Object>();
        for (String key : kresults.getIdentifiers()) {
            FactHandle handle = (FactHandle) kresults.getFactHandle(key);
            if (handle != null) {
                DefaultFactHandle disconnectedHandle = ((DefaultFactHandle) handle).clone();
                disconnectedHandle.disconnect();
                disconnectedHandles.put(key, disconnectedHandle);
            }
        }
        disconnectedResults.setFactHandles(disconnectedHandles);
        disconnectedResults.setResults((HashMap)((ExecutionResultImpl)kresults).getResults());
        return disconnectedResults;
    }
    
    return kresults;
}
 
Example 3
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 4
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 5
Source File: DisposeCommandPublicAPITest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDisposeCommand() {

    InternalKnowledgeBase kBase;
    RuleImpl rule;
    InternalKnowledgePackage pkg;
    kBase = KnowledgeBaseFactory.newKnowledgeBase();

    pkg = new KnowledgePackageImpl("org.droos.test");
    pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));

    JavaDialectRuntimeData data = new JavaDialectRuntimeData();
    data.onAdd(pkg.getDialectRuntimeRegistry(), kBase.getRootClassLoader());
    pkg.getDialectRuntimeRegistry().setDialectData("java", data);
    rule = new RuleImpl("Test");
    rule.setDialect("java");
    rule.setConsequence(new Consequence() {
        public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory) throws Exception {

        }

        public String getName() {
            return "default";
        }
    });
    pkg.addRule(rule);

    kBase.addPackage(pkg);
    KieSession session = kBase.newKieSession();
    Command dispose = KieServices.Factory.get().getCommands().newDispose();
    session.insert("whatever");
    session.fireAllRules();
    session.execute(dispose);
    try {
        session.insert("whatever");
    } catch (Exception e) {
        assertEquals(e.getMessage(), "Illegal method call. This session was previously disposed.");

    }

}
 
Example 6
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));
}