org.drools.core.impl.KnowledgeBaseFactory Java Examples

The following examples show how to use org.drools.core.impl.KnowledgeBaseFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MoreBatchExecutionTest.java    From kogito-runtimes with Apache License 2.0 7 votes vote down vote up
@Test
public void testQuery() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("org/drools/compiler/integrationtests/simple_query_test.drl"), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        fail(kbuilder.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    ksession = createKnowledgeSession(kbase);
    
    ksession.insert( new Cheese( "stinky", 5 ) );
    ksession.insert( new Cheese( "smelly", 7 ) );
    
    List<Command<?>> commands = new ArrayList<Command<?>>();
    commands.add(CommandFactory.newQuery("numStinkyCheeses", "simple query"));
    Command<?> cmds = CommandFactory.newBatchExecution(commands);
    ExecutionResults result = (ExecutionResults) ksession.execute(cmds);
    assertNotNull(result, "Batch execution result is null!");

    Object queryResultsObject = result.getValue("numStinkyCheeses");
    assertTrue(queryResultsObject != null && queryResultsObject instanceof QueryResults, "Retrieved object is null or incorrect!");
    
    assertEquals( 1, ((QueryResults) queryResultsObject).size() );
}
 
Example #2
Source File: CrossProductTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveIdentities() throws Exception {
    System.setProperty( "drools.removeIdentities",
                        "true" );
    try {
        InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
        kBase.addPackage( this.pkg );

        this.ksession = kBase.newKieSession();
        this.ksession.insert( "F1" );
        this.ksession.insert( "F2" );
        this.ksession.insert( "F3" );
        this.ksession.insert( "F4" );

        this.ksession.fireAllRules();

        // A full cross product is 16, this is just 12
        assertEquals( 12,
                      this.values.size() );
    } finally {
        System.setProperty( "drools.removeIdentities",
                            "false" );
    }
}
 
Example #3
Source File: ChangeSetTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntegregation() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource("changeset1Test.xml",
            getClass()),
                  ResourceType.CHANGE_SET );
    assertFalse( kbuilder.hasErrors() );
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    ksession.fireAllRules();
    ksession.dispose();

    assertEquals( 2,
                  list.size() );
    assertTrue( list.containsAll( Arrays.asList( new String[]{"rule1", "rule2"} ) ) );
}
 
Example #4
Source File: AddRemoveTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAdd() {
    /*
     * create a RuleBase with a single ObjectTypeNode we attach a
     * MockObjectSink so we can detect assertions and retractions
     */
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    BuildContext context = new BuildContext(kBase);

    NodeFactory nFacotry = kBase.getConfiguration().getComponentFactory().getNodeFactoryService();
    EntryPointNode entryPoint = context.getKnowledgeBase().getRete().getEntryPointNodes().values().iterator().next();

    final ObjectTypeNode objectTypeNode = nFacotry.buildObjectTypeNode( 0, entryPoint, new ClassObjectType( Object.class ), context );
    objectTypeNode.attach(context);

    final MockObjectSink sink = new MockObjectSink();
    objectTypeNode.addObjectSink( sink );

    kBase.newKieSession();

    // objectTypeNode.
}
 
Example #5
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallActivity() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivity.bpmn2"), ResourceType.BPMN2);
    kbuilder.add(ResourceFactory.newClassPathResource("BPMN2-CallActivitySubProcess.bpmn2"), ResourceType.BPMN2);
    if (!kbuilder.getErrors().isEmpty()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            logger.error("{}", error);
        }
        throw new IllegalArgumentException("Errors while parsing knowledge base");
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    KieSession ksession = createKnowledgeSession(kbase);
    
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("x", "oldValue");
    ProcessInstance processInstance = ksession.startProcess("ParentProcess", params);
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED);
    assertThat(((WorkflowProcessInstance) processInstance).getVariable("y")).isEqualTo("new value");
}
 
Example #6
Source File: ProcessInstanceResolverStrategyTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testAccept() {
    KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    KieSession ksession = kbase.newKieSession();
    WorkflowProcessImpl process = new WorkflowProcessImpl();

    RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
    processInstance.setState(ProcessInstance.STATE_ACTIVE);
    processInstance.setProcess(process);
    processInstance.setKnowledgeRuntime((InternalKnowledgeRuntime) ksession);

    ProcessInstanceResolverStrategy strategy = new ProcessInstanceResolverStrategy();
    
    assertTrue( strategy.accept(processInstance) );
    Object object = new Object();
    assertTrue( ! strategy.accept(object) );
}
 
Example #7
Source File: CustomWorkItemHandlerTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterHandlerWithKsessionUsingConfiguration() {
    KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    Properties props = new Properties();
    props.setProperty("drools.workItemHandlers", "CustomWorkItemHandlers.conf");
    KieSessionConfiguration config = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(props);
    
    KieSession ksession = kbase.newKieSession(config, EnvironmentFactory.newEnvironment());
    assertNotNull(ksession);
    // this test would fail on creation of the work item manager if injecting session is not supported
    WorkItemManager manager = ksession.getWorkItemManager();
    assertNotNull(manager);
    
    Map<String, WorkItemHandler> handlers = ((SessionConfiguration)config).getWorkItemHandlers();
    assertNotNull(handlers);
    assertEquals(1, handlers.size());
    assertTrue(handlers.containsKey("Custom"));
}
 
Example #8
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 #9
Source File: RuleUnlinkingWithSegmentMemoryTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRuleSegmentsAllLinkedTestMasks() {
    setUp( JOIN_NODE );

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl( 1L, kBase );
    
    PathMemory rs = (PathMemory) wm.getNodeMemory( rtn1 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 1, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn2 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 3, rs.getAllLinkedMaskTest() );
    
    rs = (PathMemory) wm.getNodeMemory( rtn3 );
    assertFalse( rs.isRuleLinked() );
    assertEquals( 7, rs.getAllLinkedMaskTest() );
}
 
Example #10
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected KieSession getSessionFromString( String drlString, KieBaseConfiguration kbConf ) {
    KieHelper kieHelper = new KieHelper();
    kieHelper.addContent( drlString, ResourceType.DRL );

    Results res = kieHelper.verify();
    if ( res.hasMessages( Message.Level.ERROR ) ) {
        fail( res.getMessages( Message.Level.ERROR ).toString() );
    }

    if ( kbConf == null ) {
        kbConf = KieServices.Factory.get().newKieBaseConfiguration();
    }
    kbConf.setOption( EqualityBehaviorOption.EQUALITY );
    KieBase kieBase = kieHelper.build( kbConf );


    KieSessionConfiguration ksConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ((SessionConfiguration) ksConf).setBeliefSystemType( BeliefSystemType.DEFEASIBLE );
    return kieBase.newKieSession( ksConf, null );
}
 
Example #11
Source File: DynamicEvalTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {

    baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    // use stream mode to enable proper event processing (see Drools Fusion 5.5.0 Doc "Event Processing Modes")
    baseConfig.setOption( EventProcessingOption.STREAM );
    kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig);

    // config
    sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    // use a pseudo clock, which starts at 0 and can be advanced manually
    sessionConfig.setOption( ClockTypeOption.get("pseudo") );

    // create and return session
    session = kbase.newKieSession(sessionConfig, null);
    clock = session.getSessionClock();

}
 
Example #12
Source File: AbstractKieModule.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public InternalKnowledgeBase createKieBase( KieBaseModelImpl kBaseModel, KieProject kieProject, ResultsImpl messages, KieBaseConfiguration conf ) {
    KnowledgePackagesBuildResult knowledgePackagesBuildResult = buildKnowledgePackages(kBaseModel, kieProject, messages);
    if(knowledgePackagesBuildResult.hasErrors()) {
        return null;
    }

    Collection<KiePackage> pkgs = knowledgePackagesBuildResult.getPkgs();
    checkStreamMode( kBaseModel, conf, pkgs );

    ClassLoader cl = kieProject.getClassLoader();
    if (conf == null) {
        conf = getKnowledgeBaseConfiguration(kBaseModel, cl);
    } else if (conf instanceof RuleBaseConfiguration ) {
        ((RuleBaseConfiguration)conf).setClassLoader(cl);
    }

    InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase(kBaseModel.getName(), conf );
    kBase.addPackages( pkgs );
    return kBase;
}
 
Example #13
Source File: Query3Test.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * @throws java.lang.Exception
 */
@BeforeEach
public void setUp() throws Exception {
    String text = "";
    text += "package org.drools.integrationtests\n";
    text += "import " + Query3Test.Bar.class.getCanonicalName() + "\n";
    text += "import " + Query3Test.Foo.class.getCanonicalName() + "\n";
    text += "import " + Query3Test.Foo2.class.getCanonicalName() + "\n";
    text += "query \"testDifferent\"\n";
    text += "    foo : Foo();\n";
    text += "    bar : Bar(id == foo.id)\n";
    text += "end\n";
    text += "query \"testSame\"\n";
    text += "    foo : Foo();\n";
    text += "    foo2 : Foo(id == foo.id);\n";
    text += "end\n";
    text += "query \"testExtends\"\n";
    text += "    foo : Foo();\n";
    text += "    foo2 : Foo2(id == foo.id);\n";
    text += "end\n";

    KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    knowledgeBuilder.add( ResourceFactory.newByteArrayResource(text.getBytes()),
                          ResourceType.DRL );
    assertFalse( knowledgeBuilder.hasErrors() );
    knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase.addPackages( knowledgeBuilder.getKnowledgePackages() );
}
 
Example #14
Source File: ParallelEvaluationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testImmediateEventsExpiration() {
    StringBuilder sb = new StringBuilder( 400 );
    sb.append( "global java.util.List list;\n" );
    sb.append( "import " + MyEvent.class.getCanonicalName() + ";\n" );
    sb.append( "declare MyEvent @role( event ) @expires( 1ms ) @timestamp( timestamp ) end\n" );
    for (int i = 0; i < 10; i++) {
        sb.append( getRuleWithEvent( i ) );
    }

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();

    KieSession ksession = new KieHelper().addContent( sb.toString(), ResourceType.DRL )
                                         .build( EventProcessingOption.STREAM, MultithreadEvaluationOption.YES )
                                         .newKieSession( sessionConfig, null );

    assertTrue( ( (InternalWorkingMemory) ksession ).getAgenda().isParallelAgenda() );

    List<Integer> list = new DebugList<Integer>();
    ksession.setGlobal( "list", list );

    for (int i = 0; i < 10; i++) {
        ksession.insert( new MyEvent( i, i*2L ) );
    }

    ksession.fireAllRules();

    assertEquals(10, list.size());
}
 
Example #15
Source File: ExtendsTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeclareInheritance() throws Exception {
    String s1 = "package org.drools;\n" +
                "import org.drools.compiler.integrationtests.ExtendsTest.*;\n" +
                "\n" +
                "declare A \n" +
                " @role( event )" +
                " @typesafe( false )\n" +
                "end\n" +
                "" +
                "declare C @role( event ) @typesafe( false ) end \n" +
                "" +
                "rule R \n" +
                "when " +
                "   $x : C( this.x == 1 ) \n" +
                "then\n" +
                "   System.out.println( $x ); \n" +
                "end\n" +
                "";

    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(  );
    kBuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL );
    if ( kBuilder.hasErrors() ) {
        System.err.println( kBuilder.getErrors() );
    }
    assertFalse( kBuilder.hasErrors() );

    InternalKnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase.addPackages( kBuilder.getKnowledgePackages() );

    KieSession knowledgeSession = knowledgeBase.newKieSession();
    FactHandle h = knowledgeSession.insert( new X() );

    assertTrue( ( (InternalFactHandle) h ).isEvent() );

}
 
Example #16
Source File: RemoveRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPopulatedSingleRuleNoSharingWithSubnetworkAtStart() throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase.newKieSession());

    wm.insert(new A(1));
    wm.insert(new A(2));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.insert(new C(2));
    wm.fireAllRules();


    kbase.addPackages( buildKnowledgePackage("r1", "   A() not( B() and C() ) D() E()\n") );
    List list = new ArrayList();
    wm.setGlobal("list", list);

    wm.fireAllRules();
    assertEquals(2, list.size() );
    assertEquals( "r1", ((Match)list.get(0)).getRule().getName() );
    assertEquals( "r1", ((Match)list.get(1)).getRule().getName() );

    kbase.removeRule("org.kie", "r1");
    wm.insert(new A(1));
    wm.fireAllRules();
    assertEquals(2, list.size() );
}
 
Example #17
Source File: ReteTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {
    this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();

    this.pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    this.buildContext = new BuildContext(kBase);

    this.entryPoint = buildContext.getKnowledgeBase().getRete().getEntryPointNodes().values().iterator().next();;
}
 
Example #18
Source File: AddRuleTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPopulatedSingleRuleNoSharing() throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase.newKieSession());

    wm.insert(new A(1));
    wm.insert(new B(1));
    wm.insert(new C(1));
    wm.insert(new C(2));
    wm.insert(new D(1));
    wm.insert(new E(1));

    wm.fireAllRules();


    kbase.addPackages( buildKnowledgePackage("r1", "   A() B() C(object == 2) D() E()\n") );
    List list = new ArrayList();
    wm.setGlobal("list", list);

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class );
    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getObjectSinkPropagator().getSinks()[0];

    LiaNodeMemory lm = ( LiaNodeMemory ) wm.getNodeMemory(liaNode);
    SegmentMemory sm = lm.getSegmentMemory();
    assertNotNull(sm.getStagedLeftTuples().getInsertFirst());

    wm.fireAllRules();
    assertNull(sm.getStagedLeftTuples().getInsertFirst());
    assertEquals(1, list.size() );

    assertEquals( "r1", ((Match)list.get(0)).getRule().getName() );
}
 
Example #19
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimpleBlockingUsingForall() {
    String str = "";
    str += "package org.domain.test \n";
    str += "import " + Match.class.getName() + "\n";
    str += "global java.util.List list \n";
    str += "dialect 'mvel' \n";
    str += "rule rule1 @department(sales) salience -100 \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";
    str += "rule rule2 salience 200\n";
    str += "when \n";        
    str += "     $s : String( this == 'go1' ) \n";
    str += "     exists  Match( department == 'sales' ) \n";  
    str += "     forall ( $a : Match( department == 'sales' ) Match( this == $a, active == false ) ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );
    KieBase kbase = loadKnowledgeBaseFromString( kconf, str );
    KieSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal( "list",
                        list );
    ksession.insert( "go1" );
    ksession.fireAllRules();

    assertEquals( 2,
                  list.size() );
    assertTrue( list.contains("rule1:go1") );
    assertTrue( list.contains("rule2:go1") );

    ksession.dispose();
}
 
Example #20
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogicalInsertionsLoop() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource( "test_LogicalInsertionsLoop.drl",
                                                        getClass() ),
                  ResourceType.DRL );
    Collection<KiePackage> kpkgs = kbuilder.getKnowledgePackages();

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kpkgs );
    kbase = SerializationHelper.serializeObject(kbase);
    final KieSession session = createKnowledgeSession(kbase);
    try {
        final List l = new ArrayList();
        final Person a = new Person( "a" );
        session.setGlobal( "a",
                           a );
        session.setGlobal( "l",
                           l );

        session.fireAllRules();
        Collection< ? > list = session.getObjects( new ClassObjectFilter( a.getClass() ) );
        assertEquals(0, list.size(), "a still asserted.");
        assertEquals(10, l.size(), "Rule has not fired (looped) expected number of times");
    } finally {
        session.dispose();
    }
}
 
Example #21
Source File: StartNodeInstanceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartNode() {
    
    KieBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    KieSession ksession = kbase.newKieSession();        
    
    MockNode mockNode = new MockNode();
    MockNodeInstanceFactory mockNodeFactory = new MockNodeInstanceFactory( new MockNodeInstance( mockNode ) );
    NodeInstanceFactoryRegistry.getInstance(ksession.getEnvironment()).register( mockNode.getClass(), mockNodeFactory );
    
    RuleFlowProcess process = new RuleFlowProcess(); 
    
    StartNode startNode = new StartNode();  
    startNode.setId( 1 );
    startNode.setName( "start node" );                
    
    mockNode.setId( 2 );
    new ConnectionImpl(
		startNode, org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE,
		mockNode, org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE);
    
    process.addNode( startNode );
    process.addNode( mockNode );
            
    RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();   
    processInstance.setProcess( process );
    processInstance.setKnowledgeRuntime( (InternalKnowledgeRuntime) ksession );              
    
    assertEquals(  ProcessInstance.STATE_PENDING, processInstance.getState() );
    processInstance.start();        
    assertEquals(  ProcessInstance.STATE_ACTIVE, processInstance.getState() );
    
    MockNodeInstance mockNodeInstance = mockNodeFactory.getMockNodeInstance();
    List<NodeInstance> triggeredBy =
    	mockNodeInstance.getTriggers().get(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE);
    assertNotNull(triggeredBy);
    assertEquals(1, triggeredBy.size());
    assertSame(startNode.getId(), triggeredBy.get(0).getNodeId());
}
 
Example #22
Source File: AbstractBaseTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSession createKieSession(boolean serializeKbase, KiePackage... pkg) throws Exception {
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(Arrays.asList(pkg));
    if( serializeKbase ) { 
        kbase = JbpmSerializationHelper.serializeObject( kbase );
    }

    KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption( ForceEagerActivationOption.YES );
    return kbase.newKieSession(conf, null);
}
 
Example #23
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testIncrementOperator() {
    String str = "";
    str += "package org.kie \n";
    str += "global java.util.List list \n";
    str += "rule rule1 \n";
    str += "    dialect \"mvel\" \n";
    str += "when \n";
    str += "    $I : Integer() \n";
    str += "then \n";
    str += "    i = $I.intValue(); \n";
    str += "    i += 5; \n";
    str += "    list.add( i ); \n";
    str += "end \n";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    assertFalse(kbuilder.hasErrors());

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

    final KieSession ksession = createKnowledgeSession(kbase);
    final List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.insert(5);

    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(10, list.get(0));
}
 
Example #24
Source File: GetFactHandlesCommandTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setup() { 
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    ksession = kbase.newKieSession();
    runner = ExecutableRunner.create();
    context = ( (RegistryContext) runner.createContext() ).register( KieSession.class, ksession );
}
 
Example #25
Source File: MVELTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvalWithBigDecimal() {
    String str = "";
    str += "package org.kie \n";
    str += "import java.math.BigDecimal; \n";
    str += "global java.util.List list \n";
    str += "rule rule1 \n";
    str += "    dialect \"mvel\" \n";
    str += "when \n";
    str += "    $bd : BigDecimal() \n";
    str += "    eval( $bd.compareTo( BigDecimal.ZERO ) > 0 ) \n";
    str += "then \n";
    str += "    list.add( $bd ); \n";
    str += "end \n";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        System.err.println(kbuilder.getErrors());
    }
    assertFalse(kbuilder.hasErrors());

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

    final KieSession ksession = createKnowledgeSession(kbase);
    final List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.insert(new BigDecimal(1.5));

    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(new BigDecimal(1.5), list.get(0));
}
 
Example #26
Source File: Query2Test.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvalRewrite() throws Exception {
    String str = "" +
    "package org.drools.compiler;\n" +
    "global java.util.List results;\n" +
    "rule \"eval rewrite\"\n" +
    "    when\n" +
    "        $o1 : OrderItem( order.number == 11, $seq : seq == 1 )\n" +
    //"        $o2 : OrderItem( order.number == $o1.order.number, seq != $seq )\n" +
    "        $o2 : Order( items[(Integer) 1] == $o1 ) \n" +
    "    then\n" +
    "        System.out.println( $o1 + \":\" + $o2 );\n" +
    "end        \n";
    
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL );
    
    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }
    
    final Order order1 = new Order( 11,
                                    "Bob" );
    final OrderItem item11 = new OrderItem( order1,
                                            1 );
    final OrderItem item12 = new OrderItem( order1,
                                            2 );

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages( kbuilder.getKnowledgePackages() );
    KieSession ksession = createKnowledgeSession(kbase);
    ksession.insert( order1 );
    ksession.insert( item11 );
    ksession.insert( item12 );
    
    ksession.fireAllRules();
    

}
 
Example #27
Source File: DeclarativeAgendaTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public KieSession getStatefulKnowledgeSession() {
    String str = "";
    str += "package org.domain.test \n";
    str += "import " + Match.class.getName() + "\n";
    str += "global java.util.List list \n";
    str += "dialect 'mvel' \n";

    str += "rule rule1 @department(sales) \n";
    str += "when \n";
    str += "     $s : String( this == 'go1' ) \n";
    str += "then \n";
    str += "    list.add( kcontext.rule.name + ':' + $s ); \n";
    str += "end \n";

    str += "rule blockerAllSalesRules @activationListener('direct') \n";
    str += "when \n";
    str += "     $s : String( this == 'go2' ) \n";
    str += "     $i : Match( department == 'sales' ) \n";
    str += "then \n";
    str += "    list.add( $i.rule.name + ':' + $s  ); \n";
    str += "    kcontext.blockMatch( $i ); \n";
    str += "end \n";

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption( DeclarativeAgendaOption.ENABLED );
    KieBase kbase = loadKnowledgeBaseFromString( kconf, str );
    KieSession ksession = createKnowledgeSession(kbase);

    return ksession;
}
 
Example #28
Source File: StatefulSessionTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFactHandleEqualityBehavior() throws Exception {
    final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbc.setOption(EqualityBehaviorOption.EQUALITY);
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc));
    final KieSession ksession = createKnowledgeSession(kbase);

    final CheeseEqual cheese = new CheeseEqual("stilton", 10);
    ksession.insert(cheese);
    final FactHandle fh = ksession.getFactHandle(new CheeseEqual("stilton", 10));
    assertNotNull(fh);
}
 
Example #29
Source File: FieldConstraintTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
/**
 * <pre>
 *
 *
 *                Cheese( price == 5 )
 *
 *
 * </pre>
 */
@Test
public void testPrimitiveLiteralConstraint() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl)kBase.newKieSession();

    final ClassFieldReader extractor = store.getReader(Cheese.class,
            "price");

    final MvelConstraint constraint = new MvelConstraintTestUtil( "price == 5",
                                                                  FieldFactory.getInstance().getFieldValue( 5 ),
                                                                  extractor );
    final Cheese cheddar = new Cheese( "cheddar",
                                       5 );

    final InternalFactHandle cheddarHandle = (InternalFactHandle) ksession.insert( cheddar );

    // check constraint
    assertTrue( constraint.isAllowed( cheddarHandle,
                                      ksession ) );

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

    final InternalFactHandle stiltonHandle = (InternalFactHandle) ksession.insert( stilton );

    // check constraint
    assertFalse(constraint.isAllowed(stiltonHandle,
                                     ksession));
}
 
Example #30
Source File: SegmentCreationTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieBase buildKnowledgeBase(String... rules) {
    String str = "";
    str += "package org.kie \n";
    str += "import " + LinkingTest.A.class.getCanonicalName() + "\n" ;
    str += "import " + LinkingTest.B.class.getCanonicalName() + "\n" ;
    str += "import " + LinkingTest.C.class.getCanonicalName() + "\n" ;
    str += "import " + LinkingTest.D.class.getCanonicalName() + "\n" ;
    str += "global java.util.List list \n";

    int i = 0;
    for ( String lhs : rules) {
        str += "rule rule" + (i++) +"  when \n";
        str +=  lhs;
        str += "then \n";
        str += "then[t1] \n";
        str += "end \n";            
    }
    
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    assertFalse(kbuilder.hasErrors(), kbuilder.getErrors().toString());

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