org.kie.api.runtime.StatelessKieSession Java Examples

The following examples show how to use org.kie.api.runtime.StatelessKieSession. 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: 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 #2
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 #3
Source File: SerializedPackageMergeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private StatelessKieSession getSession(boolean serialize) throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    for ( String drl : DRLs ) {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add( ResourceFactory.newInputStreamResource(getClass().getResourceAsStream(drl)),
                      ResourceType.DRL );
        
        assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());
        
        Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();

        Collection<KiePackage> newCollection = null;
        if ( serialize ) {
            newCollection = new ArrayList<KiePackage>();
            for( KiePackage kpkg : kpkgs) {
                kpkg = SerializationHelper.serializeObject(kpkg);
                newCollection.add( kpkg );
            }
        } else {
            newCollection = kpkgs;
        }
        kbase.addPackages( newCollection );
    }
    return kbase.newStatelessKieSession();
}
 
Example #4
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 #5
Source File: SequentialTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testSalience() throws Exception {
    KieBase kbase = loadKnowledgeBase(kconf, "simpleSalience.drl");
    StatelessKieSession ksession = createStatelessKnowledgeSession( kbase );

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

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

    assertEquals( 3,
                  list.size() );

    assertEquals( "rule 3", list.get( 0 ));
    assertEquals( "rule 2", list.get( 1 ) );
    assertEquals( "rule 1", list.get( 2 ) );
}
 
Example #6
Source File: SequentialTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testKnowledgeRuntimeAccess() throws Exception {
    String str = "";
    str += "package org.drools.compiler.test\n";
    str +="import org.drools.compiler.Message\n";
    str +="rule \"Hello World\"\n";
    str +="when\n";
    str +="    Message( )\n";
    str +="then\n";
    str +="    System.out.println( drools.getKieRuntime() );\n";
    str +="end\n";

    KieBase kbase = loadKnowledgeBaseFromString(kconf, str);
    StatelessKieSession ksession = createStatelessKnowledgeSession( kbase );

    ksession.execute( new Message( "help" ) );
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
Source File: InjectionHelper.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private static void wireSessionChannels(BeanCreator beanCreator, BeanCreator fallbackBeanCreator, ClassLoader cl, List<ChannelModel> channelModels, Object kSession) {
	for (ChannelModel channelModel : channelModels) {
        Channel channel;
        try {
            channel = beanCreator.createBean(cl, channelModel.getType(), channelModel.getQualifierModel());
        } catch (Exception e) {
            try {
                channel = fallbackBeanCreator.createBean(cl, channelModel.getType(), channelModel.getQualifierModel() );
            } catch (Exception ex) {
                throw new RuntimeException("Cannot instance Channel " + channelModel.getType(), e);
            }
        }
        if (kSession instanceof KieSession) {
        	((KieSession) kSession).registerChannel(channelModel.getName(), channel);
        } else if (kSession instanceof StatelessKieSession) {
        	((StatelessKieSession) kSession).registerChannel(channelModel.getName(), channel);
        } else {
        	throw new IllegalArgumentException("kSession not of correct type. Expected KieSession or StatelessKieSession but was: " + kSession.getClass().getCanonicalName());
        }
    }
}
 
Example #12
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 #13
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 #14
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 #15
Source File: KieContainerImpl.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public StatelessKieSession newStatelessKieSession(String kSessionName, KieSessionConfiguration conf) {
    KieSessionModelImpl kSessionModel = kSessionName != null ?
                                        (KieSessionModelImpl) getKieSessionModel(kSessionName) :
                                        (KieSessionModelImpl) findKieSessionModel(true);

    if ( kSessionModel == null ) {
        log.error("Unknown KieSession name: " + kSessionName);
        return null;
    }
    if (kSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
        throw new RuntimeException("Trying to create a stateless KieSession from a stateful KieSessionModel: " + kSessionModel.getName());
    }
    KieBase kBase = getKieBase( kSessionModel.getKieBaseModel().getName() );
    if ( kBase == null ) {
        log.error("Unknown KieBase name: " + kSessionModel.getKieBaseModel().getName());
        return null;
    }

    StatelessKieSession statelessKieSession = kBase.newStatelessKieSession( conf != null ? conf : getKieSessionConfiguration( kSessionModel ) );
    if (isJndiAvailable()) {
        wireSessionComponents( kSessionModel, statelessKieSession );
    }
    registerLoggers(kSessionModel, statelessKieSession);

    ((StatelessKnowledgeSessionImpl) statelessKieSession).initMBeans(containerId, ((InternalKnowledgeBase) kBase).getId(), kSessionModel.getName());

    statelessKSessions.put(kSessionModel.getName(), statelessKieSession);
    return statelessKieSession;
}
 
Example #16
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 #17
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 #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: CommandRegister.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> createCommandRegister() {
    Map<String, Object> register = new HashMap<String, Object>();

    register.put(KieContainer.class.getName(), null);
    register.put(KieBase.class.getName(), null);
    register.put(KieSession.class.getName(), null);
    register.put(StatelessKieSession.class.getName(), null);

    return register;
}
 
Example #20
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 #21
Source File: StatelessSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatelessKieSession getSession2(final Resource resource) throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( resource, ResourceType.DRL );
    
    if (kbuilder.hasErrors() ) {
        System.out.println( kbuilder.getErrors() );
    }
    
    assertFalse( kbuilder.hasErrors() );
    final Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    
   
    kbase.addPackages( pkgs );
    kbase    = SerializationHelper.serializeObject( kbase );
    final StatelessKieSession session = kbase.newStatelessKieSession();

    session.setGlobal( "list",
                       this.list );
    session.setGlobal( "cheesery",
                       this.cheesery );
    return session;
}
 
Example #22
Source File: KieBuilderTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatelessSessionDeclarativeChannelRegistration() {
    final String drl1 = "package org.drools.compiler\n" +
            "rule R1 when\n" +
            "   $m : Message()\n" +
            "then\n" +
            "end\n";

    final String kmodule = "<kmodule xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
            "         xmlns=\"http://www.drools.org/xsd/kmodule\">\n" +
            "  <kbase name=\"kbase1\">\n" +
            "    <ksession name=\"ksession1\" default=\"true\" type=\"stateless\">\n" +
            "       <channels>\n" +
            "         <channel name=\"testChannel\" type=\"org.drools.compiler.integrationtests.KieBuilderTest$MockChannel\" />\n" +
            "       </channels>\n" +
            "    </ksession>" +
            "  </kbase>\n" +
            "</kmodule>";

    final KieServices ks = KieServices.Factory.get();

    final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" );
    final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" );
    final KieModule km = createAndDeployJar( ks,
                                       kmodule,
                                       releaseId1,
                                       r1);

    KieContainer kieContainer = ks.newKieContainer( km.getReleaseId());
    
    StatelessKieSession statelessKieSession = kieContainer.newStatelessKieSession();
    assertEquals(1, statelessKieSession.getChannels().size());
    assertTrue(statelessKieSession.getChannels().keySet().contains("testChannel"));
}
 
Example #23
Source File: SerializedPackageMergeTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private void testRuleExecution(StatelessKieSession session) throws Exception {
    List<Object> list = new ArrayList<Object>();
    session.setGlobal( "list",
                       list );

    session.execute( getObject() );

    assertEquals( 2,
                  list.size() );
}
 
Example #24
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 #25
Source File: KieLoggersTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatelessKieSession getStatelessKieSession(Resource dt) {
    KieServices ks = populateKieFileSystem( dt );

    // get the session
    StatelessKieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newStatelessKieSession();
    return ksession;
}
 
Example #26
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 #27
Source File: FireAllRulesCommandTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private StatelessKieSession getSession(String drl) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
        System.err.println(kbuilder.getErrors());
    }
    assertFalse(kbuilder.hasErrors());

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

    return kbase.newStatelessKieSession();
}
 
Example #28
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 #29
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 #30
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);
}