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

The following examples show how to use org.kie.api.runtime.StatelessKieSession#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: 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 2
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 3
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 4
Source File: KieLoggersTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testKieConsoleLoggerStateless() throws Exception {
    String drl = "package org.drools.integrationtests\n" + 
            "import org.drools.compiler.Message;\n" +
            "rule \"Hello World\"\n" + 
            "    when\n" + 
            "        m : Message( myMessage : message )\n" + 
            "    then\n" + 
            "end";
    // get the resource
    Resource dt = ResourceFactory.newByteArrayResource( drl.getBytes() ).setTargetPath("org/drools/integrationtests/hello.drl");
    
    // create the builder
    StatelessKieSession ksession = getStatelessKieSession(dt);
    KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newConsoleLogger( ksession );

    AgendaEventListener ael = mock( AgendaEventListener.class );
    ksession.addEventListener( ael );
    
    ksession.execute( new Message("Hello World") );
    
    verify( ael ).afterMatchFired( any(AfterMatchFiredEvent.class) );
    
    logger.close();
}
 
Example 5
Source File: FoodRecommendationServiceImpl.java    From drools-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public Meal recommendMeal(Person person) throws BusinessException {
    StatelessKieSession kieSession = kContainer.newStatelessKieSession();

    InsertObjectCommand insertObjectCommand = new InsertObjectCommand(person);
    FireAllRulesCommand fireAllRulesCommand = new FireAllRulesCommand();
    QueryCommand queryCommand = new QueryCommand("results", "getMeal", (Object[]) null);
    List<GenericCommand<?>> commands = new ArrayList<GenericCommand<?>>();
    commands.add(insertObjectCommand);
    commands.add(fireAllRulesCommand);
    commands.add(queryCommand);
    BatchExecutionCommand batch = new BatchExecutionCommandImpl(commands);

    ExecutionResults results = kieSession.execute(batch);
    QueryResults queryResults = (QueryResults) results.getValue("results");
    Iterator<QueryResultsRow> iterator = queryResults.iterator();
    while (iterator.hasNext()) {
        Meal meal = (Meal) iterator.next().get("$m");
        if (meal != null) {
            System.out.println("Meal : " + meal);
            return meal;
        }
    }

    return null;
}
 
Example 6
Source File: SessionsPoolTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatelessKieSessionsPool() {
    KieContainerSessionsPool pool = getKieContainer().newKieSessionsPool( 1 );
    StatelessKieSession session = pool.newStatelessKieSession();

    List<String> list = new ArrayList<>();
    session.setGlobal( "list", list );
    session.execute( "test" );
    assertEquals(1, list.size());

    list.clear();
    session.execute( "test" );
    assertEquals(1, list.size());
}
 
Example 7
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 8
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 9
Source File: SequentialTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSequentialWithRulebaseUpdate() throws Exception {
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) loadKnowledgeBase(kconf, "simpleSalience.drl");
    StatelessKieSession ksession = createStatelessKnowledgeSession( kbase );

    final List list = new ArrayList();
    ksession.setGlobal( "list", list );

    ksession.execute(new Person("pob"));

    kbase.addPackages(loadKnowledgePackagesFromString( new String( IoUtils.readBytesFromInputStream( DynamicRulesTest.class.getResource("test_Dynamic3.drl").openStream() ) ) ) );

    ksession = kbase.newStatelessKieSession();
    ksession.setGlobal( "list", list );
    Person person  = new Person("bop");
    ksession.execute(person);

    assertEquals( 7, list.size() );

    assertEquals( "rule 3", list.get( 0 ));
    assertEquals( "rule 2", list.get( 1 ));
    assertEquals( "rule 1", list.get( 2 ));
    assertEquals( "rule 3", list.get( 3 ) );
    assertEquals( "rule 2", list.get( 4 ) );
    assertEquals( "rule 1", list.get( 5 ) );
    assertEquals( person, list.get( 6 ));
}
 
Example 10
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrays() {
    String text = "package test_mvel;\n";
    text += "import " + TestObject.class.getCanonicalName() + ";\n";
    text += "import function " + TestObject.class.getCanonicalName() + ".array;\n";
    text += "no-loop true\n";
    text += "dialect \"mvel\"\n";
    text += "rule \"1\"\n";
    text += "salience 1\n";
    text += "when\n";
    text += "    $fact: TestObject()\n";
    text += "    eval($fact.checkHighestPriority(\"mvel\", 2))\n";
    text += "    eval($fact.stayHasDaysOfWeek(\"mvel\", false, new String[][]{{\"2008-04-01\", \"2008-04-10\"}}))\n";
    text += "then\n";
    text += "    $fact.applyValueAddPromo(1,2,3,4,\"mvel\");\n";
    text += "end";

    final KieBase kieBase = loadKnowledgeBaseFromString(text.replaceAll("mvel", "java"), text);
    final StatelessKieSession statelessKieSession = kieBase.newStatelessKieSession();

    final List<String> list = new ArrayList<String>();
    statelessKieSession.execute(new TestObject(list));

    assertEquals(6, list.size());
    assertTrue(list.containsAll( Arrays.asList("TestObject.checkHighestPriority: java|2",
                                               "TestObject.stayHasDaysOfWeek: java|false|[2008-04-01, 2008-04-10]",
                                               "TestObject.checkHighestPriority: mvel|2",
                                               "TestObject.stayHasDaysOfWeek: mvel|false|[2008-04-01, 2008-04-10]",
                                               "TestObject.applyValueAddPromo: 1|2|3|4|mvel",
                                               "TestObject.applyValueAddPromo: 1|2|3|4|java") ));
}
 
Example 11
Source File: KieLoggersTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclarativeKieConsoleLoggerStateless() throws Exception {
    String drl = "package org.drools.integrationtests\n" +
                 "import org.drools.compiler.Message;\n" +
                 "rule \"Hello World\"\n" +
                 "    when\n" +
                 "        m : Message( myMessage : message )\n" +
                 "    then\n" +
                 "end";

    KieServices ks = KieServices.Factory.get();
    KieModuleModel kproj = ks.newKieModuleModel();

    kproj.newKieBaseModel("KBase1")
         .newKieSessionModel("KSession1")
         .setType(KieSessionModel.KieSessionType.STATELESS)
         .setConsoleLogger("logger");

    KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(kproj.toXML());
    kfs.write("src/main/resources/KBase1/rule.drl", drl);

    KieModule kieModule = ks.newKieBuilder(kfs).buildAll().getKieModule();
    KieContainer kieContainer = ks.newKieContainer(kieModule.getReleaseId());

    StatelessKieSession ksession = kieContainer.newStatelessKieSession("KSession1");
    ksession.execute( new Message("Hello World") );

    KieRuntimeLogger logger = ksession.getLogger();
    assertNotNull(logger);
    logger.close();
}
 
Example 12
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testChannels() 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 += "    channels[\"x\"].send( $c ); \n";
    str += "end\n";

    final Cheese stilton = new Cheese("stilton", 5);
    final Channel channel = Mockito.mock(Channel.class);

    final StatelessKieSession ksession = getSession2(ResourceFactory.newByteArrayResource(str.getBytes()));
    ksession.registerChannel("x", channel);

    assertEquals(1, ksession.getChannels().size());
    assertEquals(channel, ksession.getChannels().get("x"));

    ksession.execute(stilton);

    Mockito.verify(channel).send(stilton);

    ksession.unregisterChannel("x");

    assertEquals(0, ksession.getChannels().size());
    assertNull(ksession.getChannels().get("x"));
}
 
Example 13
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotInStatelessSession() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(SequentialOption.YES);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc, "test_NotInStatelessSession.drl"));
    final StatelessKieSession session = kbase.newStatelessKieSession();

    final List list = new ArrayList();
    session.setGlobal("list", list);
    session.execute("not integer");
    assertEquals("not integer", list.get(0));
}
 
Example 14
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testCollectionObjectAssert() throws Exception {
    final StatelessKieSession session = getSession2( "statelessSessionTest.drl" );

    final Cheese stilton = new Cheese( "stilton",
                                       5 );

    final List collection = new ArrayList();
    collection.add( stilton );
    session.execute( collection );

    assertEquals( "stilton",
                  list.get( 0 ) );
}
 
Example 15
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleObjectAssert() throws Exception {
    final StatelessKieSession session = getSession2( "statelessSessionTest.drl" );

    final Cheese stilton = new Cheese( "stilton",
                                       5 );

    session.execute( stilton );

    assertEquals( "stilton", list.get( 0 ) );
}
 
Example 16
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 17
Source File: SequentialTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSequentialPlusPhreakRevisitOriginallyEmptyGroup() throws Exception {
    String str = "";
    str += "package org.drools.compiler.test\n";
    str +="import " + A.class.getCanonicalName() + "\n";
    str +="global  " + List.class.getCanonicalName() + " list\n";

    // Focus is done as g1, g2, g1 to demonstrate that groups will not re-activate
    str +="rule r0 when\n";
    str +="then\n";
    str +="    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup( 'g1' ).setFocus();\n";
    str +="    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup( 'g2' ).setFocus();\n";
    str +="    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup( 'g1' ).setFocus();\n";
    str +="end\n";

    // r1_x is here to show they do not react when g2.r9 changes A o=2,
    // i.e. checking that re-activating g1 won't cause it to pick up previous non evaluated rules.
    // this is mostly checking that the none linking doesn't interfere with the expected results.
    // additional checks this works if g1 never had any Matches on the first visit
    str +="rule r1_x agenda-group 'g1' when\n";
    str +="    a : A( object == 2 )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    // This changes A o=2 to check if g1.r1_x incorrect reacts when g1 is re-entered
    str +="rule r9 agenda-group 'g2' when\n";
    str +="    a : A(object >= 5  )\n";
    str +="then\n";
    str +="    modify(a) { setObject( 2 ) };\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    KieBase kbase = loadKnowledgeBaseFromString(kconf, str);
    StatelessKieSession ksession = createStatelessKnowledgeSession( kbase );
    final List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );

    ksession.execute( CommandFactory.newInsertElements(Arrays.asList( new Object[]{new A(5)} )) );

    assertEquals( 1, list.size() );
    assertEquals( "r9", list.get(0));
}
 
Example 18
Source File: SequentialTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSequentialPlusPhreakOperationComplex() throws Exception {
    String str = "";
    str += "package org.drools.compiler.test\n";
    str +="import " + A.class.getCanonicalName() + "\n";
    str +="global  " + List.class.getCanonicalName() + " list\n";


    // Focus is done as g1, g2, g1 to demonstrate that groups will not re-activate
    str +="rule r0 when\n";
    str +="then\n";
    str +="    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup( 'g1' ).setFocus();\n";
    str +="    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup( 'g2' ).setFocus();\n";
    str +="    drools.getKnowledgeRuntime().getAgenda().getAgendaGroup( 'g1' ).setFocus();\n";
    str +="end\n";
    str +="rule r1 agenda-group 'g1' when\n";
    str +="    a : A( object > 0 )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="    modify(a) { setObject( 3 ) };\n";
    str +="end\n";

    // r1_x is here to show they do not react when g2.r9 changes A o=2,
    // i.e. checking that re-activating g1 won't cause it to pick up previous non evaluated rules.
    // this is mostly checking that the no linking doesn't interfere with the expected results.
    str +="rule r1_x agenda-group 'g1' when\n";
    str +="    a : A( object == 2 )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    // r1_y is here to show it does not react when A is changed to o=5 in r3
    str +="rule r1_y agenda-group 'g1' when\n";
    str +="    a : A( object == 5 )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    str +="rule r2 agenda-group 'g1' when\n";
    str +="    a : A( object < 3 )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";
    str +="rule r3 agenda-group 'g1' when\n";
    str +="    a : A(object >= 3  )\n";
    str +="then\n";
    str +="    modify(a) { setObject( 5 ) };\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    // Checks that itself, f3 and r1_y do not react as they are higher up
    str +="rule r4 agenda-group 'g1' when\n";
    str +="    a : A(object >= 2  )\n";
    str +="then\n";
    str +="    modify(a) { setObject( 5 ) };\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    // Checks that while this at one point matches, it does not match by the time g2 is entered
    // nor does it react when r9 changes a o=2
    str +="rule r6 agenda-group 'g2' when\n";
    str +="    a : A(object < 5  )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    str +="rule r7 agenda-group 'g2' when\n";
    str +="    a : A(object >= 3  )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";
    str +="rule r8 agenda-group 'g2' when\n";
    str +="    a : A(object >= 5  )\n";
    str +="then\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    // This changes A o=2 to check if g1.r1_x incorrect reacts when g1 is re-entered
    str +="rule r9 agenda-group 'g2' when\n";
    str +="    a : A(object >= 5  )\n";
    str +="then\n";
    str +="    modify(a) { setObject( 2 ) };\n";
    str +="    list.add( drools.getRule().getName() );\n";
    str +="end\n";

    KieBase kbase = loadKnowledgeBaseFromString(kconf, str);
    StatelessKieSession ksession = createStatelessKnowledgeSession( kbase );
    final List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );

    ksession.execute( CommandFactory.newInsertElements(Arrays.asList( new Object[]{new A(1)} )) );

    assertEquals( 6, list.size() );
    assertEquals( "r1", list.get(0));
    assertEquals( "r3", list.get(1));
    assertEquals( "r4", list.get(2));
    assertEquals( "r7", list.get(3));
    assertEquals( "r8", list.get(4));
    assertEquals( "r9", list.get(5));
}
 
Example 19
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 20
Source File: StatelessStressTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Disabled
@Test
public void testLotsOfStateless() throws Exception {
    final KieBase kbase = loadKnowledgeBase("thread_class_test.drl");

    int numThreads = 100;
    Thread[] ts = new Thread[numThreads];
    
    
        for (int i=0; i<numThreads; i++) {
            Runnable run = () -> {

                long start = 0;
                long previous = 0;

                while (true) {
                    start = System.currentTimeMillis();
                    StatelessKieSession sess = kbase.newStatelessKieSession();
                    try {
                        sess    = SerializationHelper.serializeObject(sess);
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                    Person p = new Person();
                    p.setName( "Michael" );
                    Address add1 = new Address();
                    add1.setStreet( "High" );
                    Address add2 = new Address();
                    add2.setStreet( "Low" );
                    List l = new ArrayList();
                    l.add( add1 ); l.add( add2 );
                    p.setAddresses( l );
                    sess.execute( p );

                    long current = System.currentTimeMillis() - start;
                    if (previous != 0) {
                        float f = current/previous;
                        if (f > 1) {
                            System.err.println("SLOWDOWN");
                        }
                    }

                    previous = current;
                }
            };
            
            Thread t = new Thread(run);
            t.start();
            ts[i] = t;
        }
        
        for ( int i = 0; i < ts.length; i++ ) {
            ts[i].join();
        }
    
    
    
    
}