Java源码示例:org.kie.api.runtime.StatelessKieSession

示例1
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());
        }
    }
}
 
示例2
@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() );
}
 
示例3
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;
}
 
示例4
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();
}
 
示例5
@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() );
}
 
示例6
@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 ) );
}
 
示例7
@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" ) );
}
 
示例8
@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);
}
 
示例9
@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);
}
 
示例10
@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);
}
 
示例11
@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);
}
 
示例12
@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();
}
 
示例13
@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();
}
 
示例14
@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());
}
 
示例15
@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;
}
 
示例16
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;
}
 
示例17
@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());
}
 
示例18
@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();
}
 
示例19
@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 ) );
}
 
示例20
@Test
public void testArrayObjectAssert() throws Exception {
    final StatelessKieSession session = getSession2( "statelessSessionTest.drl" );

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

    session.execute( Arrays.asList( new Object[]{stilton} ) );

    assertEquals( "stilton",
                  list.get( 0 ) );
}
 
示例21
@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 ) );
}
 
示例22
@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));
}
 
示例23
@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"));
}
 
示例24
@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"));
}
 
示例25
private void testRuleExecution(StatelessKieSession session) throws Exception {
    List<Object> list = new ArrayList<Object>();
    session.setGlobal( "list",
                       list );

    session.execute( getObject() );

    assertEquals( 2,
                  list.size() );
}
 
示例26
@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 ));
}
 
示例27
@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)));
}
 
示例28
@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);
}
 
示例29
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();
}
 
示例30
@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();
}